gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainfe209ffeMerge branch 'w56-owner-members' into mainGitoriamain/tests/signin-return.mjs

8.8 KB

  1. import { requiredPort, requiredPortRange } from './gate-ports.mjs';
  2. // tests/signin-return.mjs — ident#31: signed out on an INNER page of gitoria, sign in through the selector's panel (email → code → identity, all in
  3. // ident's frame), and the browser is back on THE SAME inner page, signed in. Fails on main: the selector has no `return` attribute there, so the
  4. // panel's sign-in comes back to the page that is the current URL, which does not handle ident_code (no session, ident_code left in the URL).
  5. // Real Chrome, real clicks and keys; ident is a copy of the branch's code (GITORIA_GATE_IDENT_DIR) with a mail sink, never live data.
  6. // Ports (required): GITORIA_SIGNIN_PORT app, +1 ident; Chrome GITORIA_SIGNIN_CHROME (required).
  7. import { spawn } from 'node:child_process';
  8. import { mkdirSync, rmSync, existsSync, writeFileSync } from 'node:fs';
  9. import { dirname, join, resolve } from 'node:path';
  10. import { fileURLToPath } from 'node:url';
  11. import { launchBrowser } from './cdp.mjs';
  12. import { startIdent } from './identkit.mjs';
  13. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  14. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  15. const BIN = join(APP, 'bin/hybriel');
  16. const PORT = requiredPort('GITORIA_SIGNIN_PORT'), BASE = `http://127.0.0.1:${PORT}`;
  17. const IDENT_PORT = PORT + 1;
  18. 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')));
  19. const CHROME = requiredPortRange('GITORIA_SIGNIN_CHROME');
  20. const INNER = '/pulls';
  21. const G = join(APP, '.scratch/signin-return');
  22. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  23. let passed = 0, failed = 0;
  24. const check = (name, ok, detail = '') => { if (ok) { passed++; console.log(' ok ' + name); } else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); } };
  25. rmSync(G, { recursive: true, force: true }); mkdirSync(join(G, 'mpackdb'), { recursive: true });
  26. let ident, server, browser, page, log = '', APPKEY;
  27. const sh = (hostSel, expr) => `(() => { const h = document.querySelector(${J(hostSel)}); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;
  28. const worlds = new Map();
  29. function trackWorlds(p) {
  30. p.conn.onEvent((msg) => {
  31. if (msg.sessionId !== p.sessionId) return;
  32. const c = msg.params && msg.params.context;
  33. if (msg.method === 'Runtime.executionContextCreated' && c && c.auxData && c.auxData.isDefault) worlds.set(c.auxData.frameId, c.id);
  34. if (msg.method === 'Runtime.executionContextDestroyed') for (const [f, id] of worlds) if (id === msg.params.executionContextId) worlds.delete(f);
  35. if (msg.method === 'Runtime.executionContextsCleared') worlds.clear();
  36. });
  37. return p.send('Runtime.enable');
  38. }
  39. async function fEval(p, expr) {
  40. const t = await p.send('Page.getFrameTree');
  41. const f = (t.frameTree.childFrames || [])[0];
  42. if (!f) throw new Error('no frame');
  43. const id = worlds.get(f.frame.id);
  44. if (!id) throw new Error('no context for the frame');
  45. const r = await p.send('Runtime.evaluate', { contextId: id, expression: expr, returnByValue: true, awaitPromise: true });
  46. if (r.exceptionDetails) throw new Error('frame evaluate threw: ' + ((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || r.exceptionDetails.text));
  47. return r.result.value;
  48. }
  49. async function fWait(p, expr, label) {
  50. const end = Date.now() + 30000; let last;
  51. while (Date.now() < end) { try { last = await fEval(p, expr); if (last) return last; } catch (e) { last = e.message; } await sleep(100); }
  52. throw new Error('frame waitFor timed out: ' + label + ' (' + last + ')');
  53. }
  54. async function mouse(p, x, y) {
  55. const base = { x: Math.round(x), y: Math.round(y), button: 'left', clickCount: 1 };
  56. await p.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...base, buttons: 0 });
  57. await p.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...base, buttons: 1 });
  58. await p.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...base, buttons: 0 });
  59. }
  60. async function shClick(p, inner) {
  61. const box = await p.waitFor(sh('#selector', `(() => { const el = r.querySelector(${J(inner)}); if (!el) return null; el.scrollIntoView({ block: 'center' }); const b = el.getBoundingClientRect(); return b.width ? { x: b.left + b.width / 2, y: b.top + b.height / 2 } : null; })()`), { label: 'selector ' + inner });
  62. await mouse(p, box.x, box.y);
  63. }
  64. async function fClick(p, sel) {
  65. await fWait(p, `!!document.querySelector(${J(sel)})`, sel);
  66. const b = await fEval(p, `(() => { const r = document.querySelector(${J(sel)}).getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; })()`);
  67. const o = await p.evaluate(sh('#selector', `(() => { const b = r.querySelector('iframe#signin').getBoundingClientRect(); return { x: b.left, y: b.top }; })()`));
  68. await mouse(p, o.x + b.x, o.y + b.y);
  69. }
  70. async function fType(p, sel, text) {
  71. await fClick(p, sel);
  72. for (const ch of text) {
  73. await p.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  74. await p.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  75. }
  76. }
  77. async function up(url) {
  78. for (const end = Date.now() + Number(process.env.GITORIA_COLD_MS || 120000); Date.now() < end;) { try { const r = await fetch(url + '/'); if (r.ok) return; } catch {} await sleep(250); }
  79. throw new Error('did not come up: ' + url + '\n' + log);
  80. }
  81. try {
  82. ident = await startIdent({ identDir: IDENT_DIR, workDir: G, port: IDENT_PORT });
  83. const alice = await ident.signIn('[email protected]'); // her ident account exists (with its default identity); the BROWSER is signed out of ident
  84. APPKEY = await ident.registerApp(alice, 'gitoria (signin gate)', [BASE]);
  85. server = spawn(BIN, ['project.hl'], { cwd: APP, env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_STORAGE: join(G, 'mpackdb'), GITORIA_SESSIONS: join(G, 'sessions') + '/', GITORIA_WATCH: '0', GITORIA_GIT: join(G, 'git'), GITORIA_PUBLIC_URL: BASE, IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base }, stdio: ['ignore', 'pipe', 'pipe'] });
  86. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  87. await up(BASE);
  88. browser = await launchBrowser({ debugPortRange: CHROME });
  89. page = await browser.newPage(); await trackWorlds(page);
  90. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  91. await page.goto(BASE + INNER);
  92. await page.waitFor('!!customElements.get("ident-selector") && !!document.querySelector("#selector") && !!document.querySelector("#selector").shadowRoot', { label: 'the selector' });
  93. check('signed out on the inner page ' + INNER, (await page.evaluate('document.querySelector("#selector").classList.contains("out")')) === true && (await page.evaluate('location.pathname')) === INNER);
  94. await shClick(page, '#choose');
  95. await page.waitFor(sh('#selector', `!!r.querySelector('iframe#signin')`), { label: 'the sign-in frame' });
  96. await fWait(page, '!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1 && !!document.querySelector("#email")', 'frame hydrated');
  97. await fType(page, '#email', '[email protected]');
  98. await fClick(page, '#sendcode');
  99. await fWait(page, '!!document.querySelector("#code")', 'code field');
  100. await fType(page, '#code', ident.lastCode('[email protected]'));
  101. await fClick(page, '#verify');
  102. await fWait(page, 'document.querySelectorAll("#chooselist li").length >= 1', 'identity list');
  103. await page.evaluate('window.__still = 1');
  104. await fClick(page, '#chooselist li:nth-child(1) :is(a, button)');
  105. await page.waitFor(`!window.__still && document.readyState === 'complete' && location.pathname === ${J(INNER)} && !!document.querySelector('#selector') && document.querySelector('#selector').classList.contains('in')`, { timeout: 30000, label: 'back on the same page, signed in' });
  106. check('back on the SAME inner page (' + INNER + '), not the start page', (await page.evaluate('location.pathname')) === INNER, await page.evaluate('location.href'));
  107. check('signed in: the selector says so and the one-time code is not left in the URL', (await page.evaluate('document.querySelector("#selector").classList.contains("in") && !/ident_code/.test(location.href)')) === true, await page.evaluate('location.href'));
  108. } catch (e) {
  109. failed++; console.log(' FAIL the flow threw: ' + e.message.slice(0, 600));
  110. try { console.log(' at ' + (await page.evaluate('location.href'))); } catch {}
  111. } finally {
  112. try { await page.close(); } catch {}
  113. try { await browser.close(); } catch {}
  114. try { server.kill('SIGTERM'); } catch {}
  115. try { await ident.stop(); } catch {}
  116. writeFileSync(join(G, 'app.log'), log);
  117. }
  118. console.log(`\n${passed} passed, ${failed} failed`);
  119. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • 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
  • c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
  • ce08920dMerge branch 'w52c-header-phone' into mainGitoria
  • 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
  • e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
  • c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
  • 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
  • 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
  • 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
  • 155861f6Merge branch 'w52-person-approval' into mainGitoria
  • b5435de8|||PR person approvals: second Kunibert round (#52)mre
  • 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre