gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitedcfce3fedcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmreedcfce3f/tests/hardening.mjs

11.2 KB

  1. // tests/hardening.mjs — SESSION HARDENING GATE (ticket ident#2, mission 022):
  2. // * a signed-in session has its OWN expiry (store.hl sessionUserTtl), independent of the
  3. // webex session file's rolling idle/maxAge — IDENT_SESSION_TTL_MS on a short-clock server;
  4. // * an OLDER session (no `since`/`epoch` yet, as after the mission-009 migration or from
  5. // before this ticket) is NOT force-signed-out — it is upgraded on its next use;
  6. // * "sign out everywhere" (store.hl signOutEverywhere / home.hl signOutAll) invalidates
  7. // EVERY session of the account at once, the caller's own included, without touching any
  8. // other session file;
  9. // * "sign out of an app" (apps.hl disconnectConnection / appsettings.hl inboxDisconnect)
  10. // forgets one connection: the app gets the same short id on a later login.
  11. // Own servers (.scratch/hardening-gate, wiped at start): ident main :8700 (default TTL),
  12. // ident short :8701 (IDENT_SESSION_TTL_MS=2000). No Chrome — HTTP + the face carrier only,
  13. // same as migration.mjs's non-browser checks.
  14. import { spawn } from 'node:child_process';
  15. import { readFileSync, writeFileSync, rmSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
  16. import { createHash } from 'node:crypto';
  17. import { dirname, join } from 'node:path';
  18. import { fileURLToPath } from 'node:url';
  19. const APP = join(dirname(fileURLToPath(import.meta.url)), '..');
  20. const G = join(APP, '.scratch/hardening-gate');
  21. const BIN = join(APP, 'bin/hybriel');
  22. const P0 = Number(process.env.HARDENING_GATE_PORT || 8700); // ident main = P0, ident short = P0+1, the fixture app origin (never listens) = P0+3
  23. const MAIN = 'http://127.0.0.1:' + P0, SHORT = 'http://127.0.0.1:' + (P0 + 1), FIXAPP = 'http://127.0.0.1:' + (P0 + 3);
  24. const J = JSON.stringify;
  25. const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  26. let passed = 0, failed = 0;
  27. const check = (name, ok, detail = '') => {
  28. if (ok) { passed++; console.log(' ok ' + name); }
  29. else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); }
  30. };
  31. rmSync(G, { recursive: true, force: true });
  32. mkdirSync(join(G, 'main-sess'), { recursive: true });
  33. mkdirSync(join(G, 'short-sess'), { recursive: true });
  34. const procs = [];
  35. function start(name, env) {
  36. let out = '';
  37. const p = spawn(BIN, ['project.hl'], { cwd: APP, env: { ...process.env, SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', ...env }, stdio: ['ignore', 'pipe', 'pipe'] });
  38. p.stdout.on('data', (d) => { out += d; }); p.stderr.on('data', (d) => { out += d; });
  39. p.on('exit', () => writeFileSync(join(G, `${name}.log`), out));
  40. procs.push(p);
  41. }
  42. start('main', { IDENT_PORT: String(P0), IDENT_STORAGE: join(G, 'main-store'), IDENT_SESSIONS: join(G, 'main-sess'), IDENT_MAIL_SINK: join(G, 'main-mail.txt'), IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000' });
  43. start('short', { IDENT_PORT: String(P0 + 1), IDENT_STORAGE: join(G, 'short-store'), IDENT_SESSIONS: join(G, 'short-sess'), IDENT_MAIL_SINK: join(G, 'short-mail.txt'), IDENT_SESSION_TTL_MS: '2000', IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000' });
  44. for (const u of [MAIN, SHORT]) { for (let i = 0; i < 80; i++) { try { await fetch(u + '/', { redirect: 'manual' }); break; } catch {} await sleep(250); } }
  45. // ---- helpers --------------------------------------------------------------------------
  46. const mailCodeOnce = (sink, email) => {
  47. if (!existsSync(sink)) return null;
  48. const lines = readFileSync(sink, 'utf8').split('\n').filter((l) => l.startsWith(email + ' '));
  49. return lines.length ? lines.at(-1).split(' ')[1] : null;
  50. };
  51. // the sink write lands after the /api/code response (apiCode returns before the write is
  52. // guaranteed flushed) — poll briefly instead of reading it once right away
  53. const mailCode = async (sink, email) => {
  54. for (let i = 0; i < 20; i++) {
  55. const c = mailCodeOnce(sink, email);
  56. if (c) return c;
  57. await sleep(100);
  58. }
  59. return null;
  60. };
  61. const cookieOf = (setCookie) => setCookie ? setCookie.split(';')[0] : null;
  62. async function signIn(base, sink, email) {
  63. // /api/code is a plain function route (no session, no Set-Cookie, project.hl apiCode):
  64. // the FIRST cookie is minted by the /__hl/emit call below (the framework's `fresh`
  65. // session path, WebFramework.hl). r1 never carries one — only r2 does.
  66. const r1 = await fetch(base + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email }) });
  67. const code = await mailCode(sink, email);
  68. const r2 = await fetch(base + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: 1, event: 'verifyCode', payload: [email, code, 'UTC'] }) });
  69. const cookie = cookieOf(r2.headers.get('set-cookie'));
  70. const v = (await r2.json()).value;
  71. return { cookie, value: v };
  72. }
  73. async function emit(base, cookie, event, payload) {
  74. const r = await fetch(base + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie }, body: J({ t: 'emit', i: 1, event, payload }) });
  75. return (await r.json()).value;
  76. }
  77. // ---- 1. a session's own expiry (independent server, TTL 2s) ---------------------------
  78. console.log('# session expiry (IDENT_SESSION_TTL_MS)');
  79. {
  80. const { cookie } = await signIn(SHORT, join(G, 'short-mail.txt'), '[email protected]');
  81. let v = await emit(SHORT, cookie, 'addIdentity', [{}]);
  82. check('right after signing in: an authenticated face works', v && v.error == null, J(v));
  83. await sleep(2600);
  84. v = await emit(SHORT, cookie, 'addIdentity', [{}]);
  85. check('2.6s later (TTL 2s): the same cookie is signed out', v && v.error === 'you are not signed in', J(v));
  86. }
  87. // ---- 2. an older session (no since/epoch) is upgraded, not force-signed-out -----------
  88. console.log('# older session (pre-hardening shape) stays signed in');
  89. {
  90. const { value } = await signIn(MAIN, join(G, 'main-mail.txt'), '[email protected]');
  91. const accountId = value.account.id;
  92. const sid = 'f'.repeat(32);
  93. const file = join(G, 'main-sess', createHash('sha256').update(sid).digest('hex'));
  94. writeFileSync(file, J({ created: Date.now() - 999999, data: {}, id: sid, seen: Date.now() - 999999, user: { id: accountId } }), { mode: 0o600 });
  95. const v = await emit(MAIN, 'identsid=' + sid, 'addIdentity', [{}]);
  96. check('an old-shape session (user: {id} only) still signs its account in', v && v.error == null && v.identities && v.identities.length === 2, J(v));
  97. const after = JSON.parse(readFileSync(file, 'utf8'));
  98. check('…and gets upgraded on disk (since + epoch stamped)', typeof after.user.since === 'number' && typeof after.user.epoch === 'number', J(after.user));
  99. }
  100. // ---- 3. sign out everywhere --------------------------------------------------------------
  101. console.log('# sign out everywhere');
  102. {
  103. const email = '[email protected]';
  104. const a = await signIn(MAIN, join(G, 'main-mail.txt'), email);
  105. let v = await emit(MAIN, a.cookie, 'addIdentity', [{}]);
  106. check('device A: signed in', v && v.error == null, J(v));
  107. await fetch(MAIN + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email }) });
  108. const code = await mailCode(join(G, "main-mail.txt"), email);
  109. const r2 = await fetch(MAIN + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: 1, event: 'verifyCode', payload: [email, code, 'UTC'] }) });
  110. const cookieB = cookieOf(r2.headers.get('set-cookie'));
  111. v = (await r2.json()).value;
  112. check('device B: same account, signed in too', v && v.error == null, J(v));
  113. const mine = () => readdirSync(join(G, 'main-sess')).filter((f) => { const r = JSON.parse(readFileSync(join(G, 'main-sess', f), 'utf8')); return r.user != null && r.user.id === a.value.account.id; });
  114. check('before: the account has 2 session files', mine().length === 2, J(mine()));
  115. v = await emit(MAIN, cookieB, 'signOutAll', []);
  116. check('device B calls "sign out everywhere"', v && v.ok === true, J(v));
  117. const left = mine();
  118. check('every session file of the account is deleted at once', left.length === 0, J(left));
  119. v = await emit(MAIN, a.cookie, 'addIdentity', [{}]);
  120. check('device A is now signed out too', v && v.error === 'you are not signed in', J(v));
  121. v = await emit(MAIN, cookieB, 'addIdentity', [{}]);
  122. check('device B (the caller) is signed out too', v && v.error === 'you are not signed in', J(v));
  123. const again = await signIn(MAIN, join(G, 'main-mail.txt'), email);
  124. check('the account can still sign in again afterwards', again.value && again.value.error == null, J(again.value));
  125. }
  126. // ---- 4. sign out of one app (disconnect) --------------------------------------------------
  127. console.log('# sign out of one app');
  128. {
  129. const { cookie, value } = await signIn(MAIN, join(G, 'main-mail.txt'), '[email protected]');
  130. const identityId = value.identities[0].id;
  131. const created = await emit(MAIN, cookie, 'appCreate', [{ name: 'Hardening test app', origins: [FIXAPP] }]);
  132. const { apiKey } = created.app; const secret = created.secret;
  133. const login1 = await fetch(MAIN + `/login?key=${apiKey}&return=${encodeURIComponent(FIXAPP + '/cb')}`, { redirect: 'manual' });
  134. const rid1 = login1.headers.get('location').split('/').pop();
  135. const choice1 = await emit(MAIN, cookie, 'chooseIdentity', [rid1, identityId]);
  136. const code1 = new URL(choice1.url).searchParams.get('ident_code');
  137. const ex1 = await (await fetch(MAIN + '/api/exchange', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ key: apiKey, secret, code: code1 }) })).json();
  138. check('the app first exchanges an id for the identity', ex1.identity && /^[2-9a-hj-km-np-z]{5}$/.test(ex1.identity), J(ex1));
  139. // find the connection id the same way the inbox page would (a fresh dump on a COPY)
  140. const cpDir = join(G, 'conn-dump'); mkdirSync(cpDir, { recursive: true });
  141. const { cpSync, execFileSync } = await import('node:fs').then(async (fs) => ({ cpSync: fs.cpSync, execFileSync: (await import('node:child_process')).execFileSync }));
  142. cpSync(join(G, 'main-store'), cpDir, { recursive: true });
  143. const dump = JSON.parse(execFileSync(BIN, [join(APP, 'tools/dump-store.hl')], { cwd: APP, env: { ...process.env, IDENT_STORAGE: cpDir }, encoding: 'utf8' }));
  144. const conn = dump.connections.find((c) => c.identity === identityId);
  145. check('the connection for that app+identity exists', !!conn, J(dump.connections));
  146. const disc = await emit(MAIN, cookie, 'inboxDisconnect', [conn.id]);
  147. check('signing out of the app (disconnect) succeeds', disc && disc.disconnected === conn.id, J(disc));
  148. const disc2 = await emit(MAIN, cookie, 'inboxDisconnect', [conn.id]);
  149. check('…and cannot be repeated (the connection is gone)', disc2 && disc2.error != null, J(disc2));
  150. const login2 = await fetch(MAIN + `/login?key=${apiKey}&return=${encodeURIComponent(FIXAPP + '/cb')}`, { redirect: 'manual' });
  151. const rid2 = login2.headers.get('location').split('/').pop();
  152. const choice2 = await emit(MAIN, cookie, 'chooseIdentity', [rid2, identityId]);
  153. const code2 = new URL(choice2.url).searchParams.get('ident_code');
  154. const ex2 = await (await fetch(MAIN + '/api/exchange', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ key: apiKey, secret, code: code2 }) })).json();
  155. check('a later login gets the SAME short id again (it never changes)', ex2.identity && ex2.identity === ex1.identity, J({ old: ex1.identity, new: ex2.identity }));
  156. }
  157. for (const p of procs) p.kill();
  158. console.log(`\n${passed} passed, ${failed} failed`);
  159. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
  • 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre
  • c7eef14aMerge branch 'nv1-navigate' into mainIdent
  • 644f9775|||PR ident#36 navigate() instead of window.location in the shell, start shell and homemre
  • 4ca2f921deploy.sh: tar --hard-dereference so backups hold no hard linksmre
  • 23971fb7ident#49: media queries in the language's @media formmre
  • 73f4f97dident: re-vendor to hybriel day38b (mpackdb store-open fix)mre
  • aa056c03ident: a startup error prints its message before exit 1 (hybriel#247)mre
  • ee37a861ident#G48: gitoria's registration gets the wildcard origin of its repo addresses at load (gate tests/gitoria-origin.mjs)mre
  • dc6d486fident#27: the docs gate expects the new Access entry in the main menumre
  • d277633cident#27: README: identity access and the introspect endpointmre
  • e999b0d3ident#27: the Access tab — one key per identity for all its apps: give access in three steps, the overview matrix, a cell's sheet (since, last use, level, rotate, revoke), the app's check POST /api/introspect, agent identities hidden from the login picker, an inbox icon in the header's icon style (gate: tests/access.mjs)mre
  • 436206fcident#47: deploy.sh runs the sign-in gate on the deploy's own port slot, like the sessionwrites and docs gates (the default 8700 can be taken by another process)mre
  • a4887ea3ident#47: the selector's sign-in frame no longer has a Continue button; the identity row itself is the link (gate tests/signin.mjs fails on the old code)mre
  • d8ec703dident#45: /docs shows docs/IDENT.md (hl:markdown, vendored from ac1ed9da), one Docs entry in the main menu, README for developers only, gates tests/docs.mjs and tests/sessionwrites.mjs in deploy.shmre
  • ec6aad35Merge branch 'a28g-amp-callsites' into d45-docsmre
  • 6bfbd3f2ident#45: docs/IDENT.md, what ident is and how it works; CONCEPT.md marks one id per app as droppedmre
  • c0edca26ident#28 A28G: write & at every call that hands a session to an &-parameter; gate tests/sessionwrites.mjs pins that sign-in, pending address, embed sign-in and selector land in the session filesmre
  • 80965c08ident#28: README says the deploy goes through the standbymre
  • 2f41670cident#28: ident-standby service on port 45012 (no background round in the standby) and deploy.sh hands over through standby-swap.shmre