gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita80da7bda80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmrea80da7bd/tests/signin-return.mjs

8.7 KB

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

Branches

Latest commits

  • a80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmre
  • 23fb05d8re-vendor Hybriel aaa39e69 (hl:web batch 20: login emit and Sessions.mint, tab follows a login, signed-in session cookie wins among duplicates and is re-issued with the Domain, W85 faster render, lazy sessions)mre
  • a0727ca3ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 32ba9d59gitoria: leave the host-only cookie experiment out of the browser gate (gitoria#24 is a separate mission)mre
  • 43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre
  • ac2c4e3fident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • b279f536theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 2b01515ctests/ticketskit: a failed start kills the tickets server (own process group); stop() kills the groupmre
  • 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
  • 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b3911918reports/MG-mobile.md: 404 fixed, rebased gatesMG
  • 9da65b42tests/browser.mjs: 404 checks (host, no hydration wait)MG
  • 00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG
  • d9e977f0reports/MG-mobile.md, LOGMG
  • 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
  • 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
  • c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
  • 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
  • 570138cddeploy: security gate (tests/security.mjs)mre