gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchmain0f39e181Merge branch 'w64-org-slash' into mainGitoriamain/tests/owner-members.mjs

35.3 KB

  1. import { requiredPort, requiredPortRange } from './gate-ports.mjs';
  2. // tests/owner-members.mjs — gitoria#55: membership and confirmed ownership transfer.
  3. // Own ident/server/storage; real git pushes and the same SSH authorization door as private.mjs.
  4. // Explicit GITORIA_OWNER_PORT and GITORIA_OWNER_IDENT_PORT; optional GITORIA_OWNER_PROOF in shared Chrome.
  5. import { spawn, execFileSync } from 'node:child_process';
  6. import { request } from 'node:http';
  7. import { mkdirSync, rmSync, writeFileSync, existsSync, readdirSync } from 'node:fs';
  8. import { dirname, join, resolve } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. import { launchBrowser } from './cdp.mjs';
  11. import { startIdent } from './identkit.mjs';
  12. const HERE = dirname(fileURLToPath(import.meta.url));
  13. const APP = resolve(HERE, '..');
  14. const HOSTNAME = process.env.HL_CDP_URL ? 'w56.localhost' : 'localhost';
  15. const PORT = requiredPort('GITORIA_OWNER_PORT'), IDENT_PORT = requiredPort('GITORIA_OWNER_IDENT_PORT');
  16. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  17. const STORE = process.env.GITORIA_OWNER_STORE || join(APP, '.scratch/owner-members-store');
  18. const SSH_SECRET = 'sshsecret-for-the-private-gate';
  19. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  20. let passes = 0, failures = 0;
  21. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  22. function raw(method, path, { host = `${HOSTNAME}:${PORT}`, headers = {}, body = null, cookie = null } = {}) {
  23. return new Promise((res, rej) => {
  24. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  25. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  26. const r = request({ host: '127.0.0.1', port: PORT, method, path, headers: h }, (m) => { const c = []; m.on('data', d => c.push(d)); m.on('end', () => res({ status: m.statusCode, headers: m.headers, body: Buffer.concat(c).toString('latin1') })); });
  27. r.on('error', rej); if (body !== null) r.write(body); r.end();
  28. });
  29. }
  30. const get = (path, o = {}) => raw('GET', path, o);
  31. const g404 = (r) => r.status === 404 || /No such repository/.test(r.body);
  32. const at = (label, path = '/', o = {}) => get(path, { host: `${label}.${HOSTNAME}:${PORT}`, ...o });
  33. let server = null, log = '';
  34. function startServer(env) {
  35. log = '';
  36. const executable = process.env.GITORIA_OWNER_EXIT_PROBE ? process.execPath : join(APP, 'bin/hybriel');
  37. const entry = process.env.GITORIA_OWNER_EXIT_PROBE ? ['-e', 'process.exit(17)'] : ['project.hl'];
  38. const p = spawn(executable, entry, { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  39. env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_COOKIE_DOMAIN: '-', GITORIA_PUBLIC_URL: `http://${HOSTNAME}:${PORT}`, GITORIA_SSH_SECRET: SSH_SECRET, GITORIA_TICKETS_URL: 'http://127.0.0.1:1', ...env } });
  40. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d);
  41. server = p; return p;
  42. }
  43. async function up() { for (let i = 0; i < 960; i++) { if (server.exitCode !== null || server.signalCode !== null) throw new Error('gitoria exited: ' + log); try { if ((await get('/api/repos')).status === 200) return; } catch {} await sleep(250); } throw new Error('gitoria did not come up\n' + log); }
  44. const stop = async () => { if (server) { const p = server; server = null; if (p.exitCode === null && p.signalCode === null) { p.kill(); await new Promise(r => p.once('exit', r)); } } };
  45. let ident, browser, page;
  46. try {
  47. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  48. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  49. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');
  50. const BASE = `http://${HOSTNAME}:${PORT}`;
  51. const app = await ident.registerApp(alice, 'gitoria (private gate)', [BASE]);
  52. const ENV = { GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: join(STORE, 'git'), IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret };
  53. startServer(ENV); writeFileSync(join(STORE,'pids.txt'),`gitoria ${server.pid}\nident ${ident.proc.pid}\n`); await up();
  54. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  55. const login = async (who) => {
  56. const ck = cookieOf(await get('/'));
  57. const code = await ident.selectorCode(who, app, BASE);
  58. const cb = await get('/login/callback?ident_code=' + code + '&next=%2F', { cookie: ck });
  59. return { cookie: cookieOf(cb) || ck };
  60. };
  61. let n = 0;
  62. const face = async (who, event, payload) => {
  63. const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who && who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) });
  64. let j = null; try { j = JSON.parse(r.body); } catch {}
  65. return { status: r.status, value: j && j.value, error: j && j.error };
  66. };
  67. const A = await login(alice), B = await login(bob), C = await login(carol);
  68. const unnamed = await ident.signIn('[email protected]'), U = await login(unnamed);
  69. const tU = (await face(U, 'gitoriaMakeToken', ['unnamed'])).value.token;
  70. await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);
  71. const tok = async (who, name) => (await face(who, 'gitoriaMakeToken', [name])).value.token;
  72. const tA = await tok(A, 'a'), tB = await tok(B, 'b'), tC = await tok(C, 'c');
  73. if (process.env.GITORIA_OWNER_PROOF) {
  74. await face(A, 'gitoriaCreate', ['transfer-ui', 'Transfer UI proof']);
  75. const endpoint = process.env.HL_CDP_URL;
  76. const targets = async () => (await (await fetch(endpoint + '/json/list')).json()).filter(t => t.type === 'page');
  77. const before = await targets();
  78. writeFileSync(join(STORE, 'tabs-before.json'), J(before));
  79. const lock = spawn('timeout',['600','flock','/media/STORAGE/claude-scratch/atlas/lisbeth.lock','sh','-c','echo locked; cat'],{cwd:APP,stdio:['pipe','pipe','inherit']});
  80. await new Promise((resolve,reject) => { lock.stdout.once('data',resolve); lock.once('exit',()=>reject(new Error('Chrome lock unavailable'))); });
  81. browser = await launchBrowser();
  82. try {
  83. page = await browser.newPage();
  84. const origin = `http://transfer-ui.${HOSTNAME}:${PORT}`;
  85. const code = await ident.selectorCode(alice, app, BASE);
  86. await page.goto(origin + '/login/callback?ident_code=' + code + '&next=%2Fsettings');
  87. await page.waitForSelector('#transfer-form', {timeout:30000});
  88. await page.waitFor('!!window.__hl?.socket && window.__hl.socket.readyState === 1', {timeout:30000});
  89. for (const [width,height] of [[390,844],[800,1280],[1280,800],[1280,900]]) {
  90. await page.send('Emulation.setDeviceMetricsOverride',{width,height,deviceScaleFactor:1,mobile:width < 600});
  91. await page.box('#transfer-form');
  92. const shot = await page.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:true});
  93. writeFileSync(join(STORE,`transfer-${width}-${height}.png`),Buffer.from(shot.data,'base64'));
  94. check('form fits ' + width + 'x' + height, await page.evaluate(`document.documentElement.scrollWidth <= ${width}`));
  95. }
  96. check('transfer disabled before confirmation', await page.evaluate('document.querySelector("#transfer-repo").disabled'));
  97. await page.type('#new-owner','Bob');
  98. await page.type('#transfer-confirm','wrong');
  99. check('wrong confirmation stays disabled',await page.evaluate('document.querySelector("#transfer-repo").disabled'));
  100. await page.goto(origin + '/settings');
  101. await page.waitForSelector('#transfer-form');
  102. await page.waitFor('!!window.__hl?.socket && window.__hl.socket.readyState === 1',{timeout:30000});
  103. await page.type('#new-owner','Bob');
  104. await page.type('#transfer-confirm','transfer-ui');
  105. await page.waitFor('!document.querySelector("#transfer-repo").disabled');
  106. await page.send('Input.dispatchKeyEvent',{type:'keyDown',key:'Tab',code:'Tab',windowsVirtualKeyCode:9});
  107. await page.send('Input.dispatchKeyEvent',{type:'keyUp',key:'Tab',code:'Tab',windowsVirtualKeyCode:9});
  108. await page.send('Input.dispatchKeyEvent',{type:'keyDown',key:'Enter',code:'Enter',windowsVirtualKeyCode:13,text:'\r'});
  109. await page.send('Input.dispatchKeyEvent',{type:'keyUp',key:'Enter',code:'Enter',windowsVirtualKeyCode:13});
  110. await page.waitFor('location.pathname === "/"',{timeout:30000});
  111. check('keyboard transfer navigates to repo',true);
  112. await page.goto(origin + '/settings');
  113. await page.waitFor('!document.querySelector("#transfer-form")');
  114. check('second visit no longer offers transfer to former owner',true);
  115. } finally {
  116. if (page) { await page.close(); page = null; }
  117. if (browser) { await browser.close(); browser = null; }
  118. writeFileSync(join(STORE,'tabs-after.json'),J(await targets()));
  119. lock.stdin.end();
  120. await new Promise(r => lock.once('exit',r));
  121. }
  122. }
  123. const json = r => JSON.parse(r.body);
  124. const api = async (method, slug, suffix, token = tA, input) => raw(method, '/api/repos/' + slug.split('/').map(encodeURIComponent).join('/') + suffix, { headers: token ? { authorization: 'Bearer ' + token, 'content-type': 'application/json' } : {}, body: input === undefined ? null : J(input) });
  125. const create = async (name, token = tA, org = '', priv = false) => json(await raw('POST', '/api/repos', { headers: { authorization: 'Bearer ' + token }, body: J({ name, org, private: priv }) }));
  126. const top = await create('transfer-top');
  127. check('fixture created', top.owner === 'Alice');
  128. check('no token refused', (await api('GET', 'transfer-top', '/members', null)).status === 401);
  129. check('unknown repo is 404', (await api('GET', 'missing', '/members')).status === 404);
  130. check('public non-member list refused', (await api('GET', 'transfer-top', '/members', tC)).status === 403);
  131. check('non-owner cannot add', (await api('POST', 'transfer-top', '/members', tB, { name: 'Bob' })).status === 403);
  132. check('unknown name refused', (await api('POST', 'transfer-top', '/members', tA, { name: 'Nobody' })).status === 422);
  133. check('add returns names', J(json(await api('POST', 'transfer-top', '/members', tA, { name: 'Bob' }))) === J(['Bob']));
  134. check('member lists names', J(json(await api('GET', 'transfer-top', '/members', tB))) === J(['Bob']));
  135. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  136. const genv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_AUTHOR_NAME: 'a', GIT_AUTHOR_EMAIL: 'a@a', GIT_COMMITTER_NAME: 'a', GIT_COMMITTER_EMAIL: 'a@a' };
  137. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  138. g('init', '-q', '-b', 'main'); g('commit', '-q', '--allow-empty', '-m', 'initial');
  139. const push = (token, host = 'transfer-top', name = 'transfer-top') => { g('commit', '-q', '--allow-empty', '-m', 'next'); try { g('push', '-q', `http://u:${token}@${host}.${HOSTNAME}:${PORT}/${name}.git`, 'main'); return true; } catch { return false; } };
  140. check('member can push', push(tB));
  141. check('remove returns empty list', J(json(await api('DELETE', 'transfer-top', '/members',tA,{name:'Bob'}))) === '[]');
  142. check('removed member cannot push', !push(tB));
  143. const key = (await face(A, 'gitoriaAppAdd', ['transfer-top', 'Owner gate', 'https://example.worldapi.org/hook'])).value.key;
  144. const gat = json(await raw('POST', '/api/apps/token', { host: `transfer-top.${HOSTNAME}:${PORT}`, headers: { authorization: 'Bearer ' + key } })).token;
  145. for (const [method, path, input] of [['GET', '/members'], ['POST', '/members', {name:'Bob'}], ['DELETE','/members',{name:'Bob'}], ['POST','/owner',{name:'Bob',confirm:'transfer-top'}]]) {
  146. check('app refused ' + method + path, (await api(method, 'transfer-top', path, gat, input)).status === 403);
  147. }
  148. for (const confirm of [undefined, '', 'wrong']) {
  149. const r = await api('POST', 'transfer-top', '/owner', tA, { name: 'Bob', confirm });
  150. check('confirmation refused ' + String(confirm), r.status === 422 && json(r).error.details.field === 'confirm');
  151. }
  152. check('self-transfer refused', (await api('POST', 'transfer-top', '/owner', tA, {name:'Alice',confirm:'transfer-top'})).status === 422);
  153. check('non-owner transfer refused', (await api('POST', 'transfer-top', '/owner', tC, {name:'Bob',confirm:'transfer-top'})).status === 403);
  154. await api('POST', 'transfer-top', '/members', tA, {name:'Bob'});
  155. const transferred = await api('POST', 'transfer-top', '/owner', tA, {name:'Bob',confirm:'transfer-top'});
  156. check('transfer keeps repo identity and address', transferred.status === 200 && json(transferred).id === top.id && json(transferred).slug === top.slug && json(transferred).owner === 'Bob');
  157. check('new owner removed from members', J(json(await api('GET','transfer-top','/members',tB))) === '[]');
  158. check('old owner API denied', (await api('POST','transfer-top','/members',tA,{name:'Carol'})).status === 403);
  159. check('old owner Settings face denied', !!(await face(A,'gitoriaTransferRepo',['transfer-top','Carol','transfer-top'])).value?.error);
  160. check('old owner cannot push', !push(tA));
  161. check('new owner can push', push(tB));
  162. const settings = await at('transfer-top','/settings',{cookie:A.cookie});
  163. check('old owner transfer form hidden', !settings.body.includes('id="transfer-form"'));
  164. await create('private-transfer',tA,'',true);
  165. for (const suffix of ['/members','/owner']) check('private invisible ' + suffix, (await api(suffix === '/owner' ? 'POST':'GET','private-transfer',suffix,tC,{name:'Bob',confirm:'private-transfer'})).status === 404);
  166. await face(A,'gitoriaCreateOrg',['owner-org',false]);
  167. await face(A,'gitoriaChangeOrgMember',['owner-org','Bob',true]);
  168. const orgRepo = await create('org-repo', tB, 'owner-org');
  169. const isRepoPage = r => r.status === 200 && !r.body.includes('No such repository') && /id="reponame"[^>]*>owner-org[/]org-repo</.test(r.body) && r.body.includes('id="repoaddress"');
  170. for (const path of ['/org-repo', '/org-repo/']) {
  171. check('org repo homepage resolves ' + path, isRepoPage(await at('owner-org', path)));
  172. }
  173. const address = new URL(orgRepo.address);
  174. check('API org address leads to repo homepage', address.pathname === '/org-repo/' && isRepoPage(await get(address.pathname, {host: address.host})));
  175. for (const [label, response] of [['home', await get('/')], ['organization', await at('owner-org')]]) {
  176. const hrefs = [...response.body.matchAll(/href="([^"]+)"/g)].map(m => m[1]);
  177. const link = hrefs.find(h => h === orgRepo.address);
  178. check(label + ' list links to org repo homepage', !!link && isRepoPage(await get(new URL(link).pathname, {host: new URL(link).host})));
  179. }
  180. for (const path of ['/unknown-repo', '/unknown-repo/']) check('unknown org repo remains missing ' + path, (await at('owner-org', path)).body.includes('No such repository'));
  181. for (const suffix of ['/code', '/pulls', '/settings']) check('org repo subpage still resolves ' + suffix, !g404(await at('owner-org', '/org-repo' + suffix, {cookie:B.cookie})));
  182. const orgTransfer = await api('POST','owner-org/org-repo','/owner',tB,{name:'Carol',confirm:'owner-org/org-repo'});
  183. check('organization repo transferred', orgTransfer.status === 200 && json(orgTransfer).owner === 'Carol', J(orgTransfer));
  184. check('old owner retains organization push access', push(tB,'owner-org','org-repo'));
  185. // Everything below is cookie-free: only user access tokens authorize the full flow.
  186. const orgApi = (method, org, suffix, token = tA, input) => raw(method, '/api/orgs' + (org ? '/' + encodeURIComponent(org) : '') + suffix, { headers: token ? { authorization: 'Bearer ' + token, 'content-type': 'application/json' } : {}, body: input === undefined ? null : J(input) });
  187. const x = await orgApi('POST', '', '', tA, {name:'flow-org',title:'Flow organization',private:true});
  188. check('token creates organization with owner, title and private flag', x.status === 201 && json(x).owner === 'Alice' && json(x).title === 'Flow organization' && json(x).isPrivate);
  189. check('taken organization slug returns 409', (await orgApi('POST','','',tA,{name:'flow-org'})).status === 409);
  190. check('invalid organization input returns 422', (await orgApi('POST','','',tA,{name:'Invalid'})).status === 422 && (await orgApi('POST','','',tA,{name:'bad-type',private:'yes'})).status === 422);
  191. check('no token cannot create org', (await orgApi('POST','','',null,{name:'unsigned-org'})).status === 401);
  192. check('organization member add returns names', J(json(await orgApi('POST','flow-org','/members',tA,{name:'Carol'}))) === J(['Carol']));
  193. check('organization owner lists members', J(json(await orgApi('GET','flow-org','/members'))) === J(['Carol']));
  194. check('organization member cannot list owner-only members', (await orgApi('GET','flow-org','/members',tC)).status === 403);
  195. check('private organization invisible to stranger', (await orgApi('GET','flow-org','/members',tB)).status === 404);
  196. await orgApi('POST','flow-org','/members',tA,{name:'Bob'});
  197. check('organization member remove returns names', J(json(await orgApi('DELETE','flow-org','/members',tA,{name:'Bob'}))) === J(['Carol']));
  198. await create('flow-one'); await create('flow-two');
  199. check('initial owner pushes both top-level repos', push(tA,'flow-one','flow-one') && push(tA,'flow-two','flow-two'));
  200. const moved = [];
  201. for (const name of ['flow-one','flow-two']) {
  202. const r = await api('POST',name,'/move',tA,{org:'flow-org'});
  203. check('API moves ' + name + ' preserving its owner', r.status === 200 && json(r).slug === 'flow-org/' + name && json(r).owner === 'Alice', r.body);
  204. moved.push(json(r));
  205. check('old page forwards to organization repo ' + name, (await at(name,'/',{cookie:A.cookie})).body.includes('This repository moved to'));
  206. const cloneUrl = new URL(json(r).clone); cloneUrl.username = 'u'; cloneUrl.password = tA;
  207. const cloneDir = join(STORE,'clone-' + name);
  208. g('clone','-q',cloneUrl.href,cloneDir);
  209. check('new clone URL retains commits ' + name, !!execFileSync('git',['-C',cloneDir,'rev-parse','HEAD'],{encoding:'utf8'}).trim());
  210. }
  211. for (const confirm of [undefined,'wrong']) {
  212. const r = await orgApi('POST','flow-org','/owner',tA,{name:'Bob',confirm,stayMember:true});
  213. check('organization confirmation refused ' + String(confirm), r.status === 422 && json(r).error.details.field === 'confirm');
  214. }
  215. check('non-owner org transfer refused', (await orgApi('POST','flow-org','/owner',tC,{name:'Bob',confirm:'flow-org'})).status === 403);
  216. check('non-owner org member mutation refused', (await orgApi('POST','flow-org','/members',tC,{name:'Alice'})).status === 403);
  217. check('stayMember requires boolean', (await orgApi('POST','flow-org','/owner',tA,{name:'Bob',confirm:'flow-org',stayMember:'yes'})).status === 422);
  218. for (const [method,org,suffix,input] of [['POST','','',{name:'app-org'}],['GET','flow-org','/members'],['POST','flow-org','/members',{name:'Bob'}],['DELETE','flow-org','/members',{name:'Carol'}],['POST','flow-org','/owner',{name:'Bob',confirm:'flow-org'}]]) {
  219. check('app token cannot use org API ' + method + suffix, (await orgApi(method,org,suffix,gat,input)).status === 403);
  220. }
  221. check('app token cannot move repo', (await api('POST','flow-org/flow-one','/move',gat,{org:'owner-org'})).status === 403);
  222. check('non-owner cannot move repo', (await api('POST','flow-org/flow-one','/move',tC,{org:'owner-org'})).status === 403);
  223. await orgApi('POST','','',tB,{name:'foreign-org'});
  224. check('move into foreign organization refused', (await api('POST','flow-org/flow-one','/move',tA,{org:'foreign-org'})).status === 403);
  225. const ownerChange = await orgApi('POST','flow-org','/owner',tA,{name:'Bob',confirm:'flow-org',stayMember:true});
  226. check('organization transfer returns new owner and same identity', ownerChange.status === 200 && json(ownerChange).owner === 'Bob' && json(ownerChange).id === json(x).id, ownerChange.body);
  227. const kept = json(await orgApi('GET','flow-org','/members',tB));
  228. check('stayMember retains A alongside C', kept.includes('Alice') && kept.includes('Carol') && !kept.includes('Bob'));
  229. check('old organization owner loses administration', (await orgApi('POST','flow-org','/members',tA,{name:'Bob'})).status === 403);
  230. for (const name of ['flow-one','flow-two']) {
  231. check('A and C push after org transfer ' + name, push(tA,'flow-org',name) && push(tC,'flow-org',name));
  232. const r = await api('POST','flow-org/' + name,'/owner',tA,{name:'Bob',confirm:'flow-org/' + name});
  233. check('A transfers repository ownership to B ' + name, r.status === 200 && json(r).owner === 'Bob');
  234. check('B and retained members push after repo transfer ' + name, push(tB,'flow-org',name) && push(tA,'flow-org',name) && push(tC,'flow-org',name));
  235. }
  236. await create('member-move');
  237. const memberMoved = await api('POST','member-move','/move',tA,{org:'flow-org',name:'member-renamed'});
  238. check('member can move own repo into an organization owned by B', memberMoved.status === 200 && json(memberMoved).slug === 'flow-org/member-renamed');
  239. await create('member-choice');
  240. check('Settings destination list includes member organizations', (await at('member-choice','/settings',{cookie:A.cookie})).body.includes('value="flow-org"'));
  241. await orgApi('POST','','',tA,{name:'no-stay'});
  242. await create('no-stay-repo',tB,'',true);
  243. await orgApi('POST','no-stay','/members',tA,{name:'Bob'});
  244. await api('POST','no-stay-repo','/move',tB,{org:'no-stay'});
  245. check('former org owner can push before transfer', push(tA,'no-stay','no-stay-repo'));
  246. check('organization transfer without stayMember succeeds', (await orgApi('POST','no-stay','/owner',tA,{name:'Bob',confirm:'no-stay'})).status === 200);
  247. check('without stayMember former owner loses inherited push rights', !push(tA,'no-stay','no-stay-repo'));
  248. const out = await api('POST','no-stay/no-stay-repo','/move',tB,{org:'flow-org',name:'still-private'});
  249. check('move retains private flag and optional name', out.status === 200 && json(out).isPrivate && json(out).slug === 'flow-org/still-private');
  250. const specialName = 'Dana / 50% off';
  251. await face(U,'gitoriaSaveName',[specialName]);
  252. const specialOrgAdd = await orgApi('POST','flow-org','/members',tB,{name:specialName});
  253. check('organization adds a display name containing slash and percent',specialOrgAdd.status === 200 && json(specialOrgAdd).includes(specialName));
  254. const specialOrgRemove = await orgApi('DELETE','flow-org','/members',tB,{name:specialName});
  255. check('organization removes an exact JSON display name containing slash and percent',specialOrgRemove.status === 200 && !json(specialOrgRemove).includes(specialName));
  256. const specialRepoAdd = await api('POST','transfer-top','/members',tB,{name:specialName});
  257. check('repository adds a display name containing slash and percent',specialRepoAdd.status === 200 && json(specialRepoAdd).includes(specialName));
  258. const specialRepoRemove = await api('DELETE','transfer-top','/members',tB,{name:specialName});
  259. check('repository removes an exact JSON display name containing slash and percent',specialRepoRemove.status === 200 && !json(specialRepoRemove).includes(specialName));
  260. // Body names cannot be normalized, truncated or routed as endpoint names.
  261. await api('POST','transfer-top','/members',tB,{name:'Bob'});
  262. await orgApi('POST','flow-org','/members',tB,{name:'Bob'});
  263. for (const [i,name] of ['Bob#ops','Bob?ops','Bob//ops','members','owner','move'].entries()) {
  264. const who = await ident.signIn(`exact-${i}@example.org`), named = await login(who);
  265. await face(named,'gitoriaSaveName',[name]);
  266. const ra = await api('POST','transfer-top','/members',tB,{name});
  267. check('repository adds exact body name ' + name,ra.status === 200 && json(ra).includes(name));
  268. const rd = await api('DELETE','transfer-top','/members',tB,{name});
  269. check('repository deletes only exact body name ' + name,rd.status === 200 && !json(rd).includes(name) && json(rd).includes('Bob'));
  270. const oa = await orgApi('POST','flow-org','/members',tB,{name});
  271. check('organization adds exact body name ' + name,oa.status === 200 && json(oa).includes(name));
  272. const od = await orgApi('DELETE','flow-org','/members',tB,{name});
  273. check('organization deletes only exact body name ' + name,od.status === 200 && !json(od).includes(name) && json(od).includes('Bob'));
  274. }
  275. check('DELETE requires a JSON name', (await api('DELETE','transfer-top','/members',tB,{})).status === 422 && (await orgApi('DELETE','flow-org','/members',tB,{})).status === 422);
  276. // Open pages follow token-only writes; all browser cookies belong to throwaway hosts.
  277. let liveLock;
  278. const liveTargets = async () => (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t=>t.type==='page');
  279. if(process.env.HL_CDP_URL) {
  280. liveLock=spawn('timeout',['600','flock','/media/STORAGE/claude-scratch/atlas/lisbeth.lock','sh','-c','echo locked; cat'],{cwd:APP,stdio:['pipe','pipe','inherit']});
  281. await new Promise((resolve,reject)=>{liveLock.stdout.once('data',resolve);liveLock.once('exit',()=>reject(new Error('Chrome lock unavailable')));});
  282. writeFileSync(join(STORE,'live-tabs-before.json'),J(await liveTargets()));
  283. }
  284. try {
  285. browser=await launchBrowser({debugPortRange:requiredPortRange('GITORIA_GATE_CHROME')});page=await browser.newPage();
  286. if (process.env.GITORIA_SLASH_PROOF) {
  287. for (const [width,height] of [[390,844],[800,1280],[1280,800],[1280,900]]) {
  288. await page.send('Emulation.setDeviceMetricsOverride',{width,height,deviceScaleFactor:1,mobile:width<600});
  289. await page.goto(BASE + '/');
  290. await page.click('a[href="' + orgRepo.address + '"]');
  291. await page.waitFor('!!document.querySelector("#reponame") || document.body.textContent.includes("No such repository")');
  292. check('list click opens org repo at ' + width + 'x' + height, await page.text('#reponame') === 'owner-org/org-repo' && !!await page.text('#repoaddress'));
  293. const shot = await page.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:true});
  294. writeFileSync(join(STORE,`slash-${width}-${height}.png`),Buffer.from(shot.data,'base64'));
  295. await page.goto(orgRepo.address);
  296. check('reload keeps org repo at ' + width + 'x' + height, await page.text('#reponame') === 'owner-org/org-repo' && !!await page.text('#repoaddress'));
  297. await page.goto(orgRepo.address.replace(/\/$/, ''));
  298. check('slashless address opens same repo at ' + width + 'x' + height, await page.text('#reponame') === 'owner-org/org-repo' && !!await page.text('#repoaddress'));
  299. }
  300. }
  301. const visit = async (who,origin,path) => {
  302. const code=await ident.selectorCode(who,app,BASE);
  303. await page.goto(origin + '/login/callback?ident_code=' + code + '&next=' + encodeURIComponent(path));
  304. await page.waitFor('!!window.__hl?.socket && window.__hl.socket.readyState === 1',{timeout:30000});
  305. };
  306. await visit(alice,BASE,'/');
  307. await orgApi('POST','','',tA,{name:'live-org',title:'Live organization'});
  308. await page.waitFor('document.querySelector("#orgs")?.textContent.includes("Live organization")');
  309. check('API organization creation updates an open main list',true);
  310. await visit(alice,`http://live-org.${HOSTNAME}:${PORT}`,'/');
  311. await orgApi('POST','live-org','/members',tA,{name:'Carol'});
  312. await page.waitFor('document.querySelector("#members")?.textContent.includes("Carol")');
  313. check('API org member add updates an open owner list',true);
  314. await orgApi('DELETE','live-org','/members',tA,{name:'Carol'});
  315. await page.waitFor('!document.querySelector("#members")?.textContent.includes("Carol")');
  316. check('API org member delete updates an open owner list',true);
  317. await visit(bob,`http://transfer-top.${HOSTNAME}:${PORT}`,'/settings');
  318. await api('POST','transfer-top','/members',tB,{name:'Carol'});
  319. await page.waitFor('document.querySelector("#members")?.textContent.includes("Carol")');
  320. check('API repo member add updates open Settings',true);
  321. await api('DELETE','transfer-top','/members',tB,{name:'Carol'});
  322. await page.waitFor('!document.querySelector("#members")?.textContent.includes("Carol")');
  323. check('API repo member delete updates open Settings',true);
  324. await visit(carol,BASE,'/');await page.send('Network.enable');
  325. const frames=[];
  326. const off=browser.conn.onEvent(m=>{if(m.method==='Network.webSocketFrameReceived' && m.sessionId===page.sessionId){const t=m.params?.response?.payloadData || '';frames.push(t+'|'+Buffer.from(t,'base64').toString('utf8'));}});
  327. await orgApi('POST','','',tA,{name:'live-hidden',private:true});await sleep(700);
  328. check('private organization creation is not broadcast to strangers',!frames.some(t=>t.includes('live-hidden')) && !(await page.text('#orgs'))?.includes('live-hidden'));off();
  329. await orgApi('POST','live-hidden','/members',tA,{name:'Carol'});
  330. await page.waitFor('document.querySelector("#orgs")?.textContent.includes("live-hidden")');
  331. check('added org member sees the private organization in an open list',true);
  332. await orgApi('DELETE','live-hidden','/members',tA,{name:'Carol'});
  333. await page.waitFor('!document.querySelector("#orgs")?.textContent.includes("live-hidden")');
  334. check('removed org member loses private organization in an open list',true);
  335. await create('live-destination',tC);
  336. await visit(carol,`http://live-destination.${HOSTNAME}:${PORT}`,'/settings');
  337. await orgApi('POST','live-hidden','/members',tA,{name:'Carol'});
  338. await page.waitFor('[...document.querySelector("#rename-org").options].some(o=>o.value==="live-hidden")');
  339. check('membership add refreshes indexed Settings destinations',true);
  340. await page.focus('#rename-org');
  341. const choiceIndex=await page.evaluate('[...document.querySelector("#rename-org").options].findIndex(o=>o.value==="live-hidden")');
  342. for(const key of ['Home',...Array(choiceIndex).fill('ArrowDown')]) {
  343. const keyCode=key==='Home'?36:40;
  344. await page.send('Input.dispatchKeyEvent',{type:'keyDown',key,code:key,windowsVirtualKeyCode:keyCode});
  345. await page.send('Input.dispatchKeyEvent',{type:'keyUp',key,code:key,windowsVirtualKeyCode:keyCode});
  346. }
  347. await page.waitFor('document.querySelector("#rename-org").value === "live-hidden"');
  348. await orgApi('DELETE','live-hidden','/members',tA,{name:'Carol'});
  349. await page.waitFor('![...document.querySelector("#rename-org").options].some(o=>o.value==="live-hidden")');
  350. check('membership delete refreshes indexed Settings destinations',true);
  351. check('membership deletion clears a selected destination that is no longer available',await page.evaluate('document.querySelector("#rename-org").value === ""'));
  352. for(const [width,height] of [[390,844],[1280,800]]) {
  353. await page.send('Emulation.setDeviceMetricsOverride',{width,height,deviceScaleFactor:1,mobile:width<600});
  354. await page.box('#members');
  355. if(process.env.HL_CDP_URL){const shot=await page.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:true});writeFileSync(join(STORE,`review-live-${width}.png`),Buffer.from(shot.data,'base64'));}
  356. }
  357. } finally {
  358. if(page){await page.close();page=null;}if(browser){await browser.close();browser=null;}
  359. if(liveLock){writeFileSync(join(STORE,'live-tabs-after.json'),J(await liveTargets()));liveLock.stdin.end();await new Promise(r=>liveLock.once('exit',r));}
  360. }
  361. if (process.env.GITORIA_ORG_PROOF) {
  362. await orgApi('POST','','',tA,{name:'org-transfer-ui',title:'Organization transfer proof'});
  363. const endpoint = process.env.HL_CDP_URL;
  364. const targets = async () => (await (await fetch(endpoint + '/json/list')).json()).filter(t => t.type === 'page');
  365. const lock = spawn('timeout',['600','flock','/media/STORAGE/claude-scratch/atlas/lisbeth.lock','sh','-c','echo locked; cat'],{cwd:APP,stdio:['pipe','pipe','inherit']});
  366. await new Promise((resolve,reject) => { lock.stdout.once('data',resolve); lock.once('exit',()=>reject(new Error('Chrome lock unavailable'))); });
  367. writeFileSync(join(STORE,'org-tabs-before.json'),J(await targets()));
  368. try {
  369. browser = await launchBrowser(); page = await browser.newPage();
  370. const origin = `http://org-transfer-ui.${HOSTNAME}:${PORT}`;
  371. const code = await ident.selectorCode(alice,app,BASE);
  372. await page.goto(origin + '/login/callback?ident_code=' + code + '&next=%2Fsettings');
  373. await page.waitForSelector('#org-transfer-form',{timeout:30000});
  374. await page.waitFor('!!window.__hl?.socket && window.__hl.socket.readyState === 1',{timeout:30000});
  375. for (const [width,height] of [[390,844],[800,1280],[1280,800],[1280,900]]) {
  376. await page.send('Emulation.setDeviceMetricsOverride',{width,height,deviceScaleFactor:1,mobile:width<600});
  377. await page.box('#org-transfer-form');
  378. const shot=await page.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:true});
  379. writeFileSync(join(STORE,`org-transfer-${width}-${height}.png`),Buffer.from(shot.data,'base64'));
  380. check('organization form fits ' + width + 'x' + height,await page.evaluate(`document.documentElement.scrollWidth <= ${width}`));
  381. }
  382. check('organization Settings has no missing-repository banner',!(await page.evaluate('!!document.querySelector("#missing")')));
  383. check('organization transfer initially disabled',await page.evaluate('document.querySelector("#org-transfer").disabled'));
  384. await page.type('#org-new-owner','Bob'); await page.type('#org-transfer-confirm','wrong');
  385. check('organization wrong confirmation disabled',await page.evaluate('document.querySelector("#org-transfer").disabled'));
  386. await page.goto(origin + '/settings');
  387. await page.waitForSelector('#org-transfer-form');
  388. await page.waitFor('!!window.__hl?.socket && window.__hl.socket.readyState === 1',{timeout:30000});
  389. await page.type('#org-new-owner','Bob'); await page.type('#org-transfer-confirm','org-transfer-ui');
  390. await page.click('#org-stay-member');
  391. check('Stay a member checkbox is checked',await page.evaluate('document.querySelector("#org-stay-member").checked'));
  392. await page.click('#org-transfer');
  393. await page.waitFor('location.pathname === "/"',{timeout:30000});
  394. check('organization form transfers and navigates',true);
  395. const retained=json(await orgApi('GET','org-transfer-ui','/members',tB));
  396. check('organization form retained former owner',retained.includes('Alice'));
  397. await page.goto(origin + '/settings');
  398. await page.waitForSelector('#org-settings');
  399. check('second visit former owner has no organization transfer form',!(await page.evaluate('!!document.querySelector("#org-transfer-form")')));
  400. } finally {
  401. if(page){await page.close();page=null;}
  402. if(browser){await browser.close();browser=null;}
  403. writeFileSync(join(STORE,'org-tabs-after.json'),J(await targets()));
  404. lock.stdin.end(); await new Promise(r=>lock.once('exit',r));
  405. }
  406. }
  407. await stop(); startServer(ENV); await up();
  408. check('ownership persists after restart', (await api('GET','transfer-top','/members',tB)).status === 200 && (await api('POST','transfer-top','/owner',tA,{name:'Carol',confirm:'transfer-top'})).status === 403);
  409. } catch (e) {
  410. check('gate completes', false, String(e.message).replace(/gtr_[0-9a-f]+|gat_[0-9a-f]+|gak_[0-9a-f]+/g, '[redacted]'));
  411. } finally {
  412. if (page) await page.close().catch(() => {});
  413. if (browser) await browser.close().catch(() => {});
  414. await stop().catch(() => {});
  415. if (ident) await ident.stop().catch(() => {});
  416. }
  417. console.log(`\n${passes} passed, ${failures} failed`);
  418. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 0f39e181Merge branch 'w64-org-slash' into mainGitoria
  • 9c72d0bf|||PR org repo addresses work with a trailing slashmre
  • a4a33081Merge branch 'w63-force-push' into mainGitoria
  • 52576cb0force push: defer on a failed scan, one-to-one pairs, docs (#56)mre
  • 5a7b3e68|||PR a force push keeps the same pull request (#56)mre
  • cc1be2d6Merge branch 'w62-pr-close' into mainGitoria
  • 6e03be0apull state: keep the resync marker until the sync ran (#56)mre
  • 93bdd26cpull state: wait for a claimed row, resync when it stays busy (#56)mre
  • e53d284bpull state: stop on a failed branch scan, claim the row on writes (#56)mre
  • d8608224close and reopen: keep a manual close against sync (#56)mre
  • ffb60746|||PR close and reopen pull requests (#56)mre
  • fe209ffeMerge branch 'w56-owner-members' into mainGitoria
  • fa0754c8|||PR repository owner transfer and members API (#55)mre
  • 8862e537Merge branch 'w55-rename-org' into mainGitoria
  • 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
  • 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
  • 499f25f2Review fixes for the Settings organization move (#53)mre
  • ed3b922b|||PR move a repository into an organization in Settings (#53)mre
  • 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
  • 9f7ce8d8Preserve rename compatibility and live page titlesmre