gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitd69665f6d69665f6|||PR ident#34 part 3: shared look classes (wide, avatar, chip/used, conn, choose, who, inboxlink) moved to statics or droppedmred69665f6/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 / main.hl shellSignOutAllNow) 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, 'shellSignOutAllNow', []);
  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

  • d69665f6|||PR ident#34 part 3: shared look classes (wide, avatar, chip/used, conn, choose, who, inboxlink) moved to statics or droppedmre
  • 3a64dc48ident#34: chipLook: radius as the same var() string (a bare token name in a static does not compile); selector gate selectormre
  • eb039073ident#34: tests: signin and migration find the choice without the classmre
  • 4b94a594ident#34: tests: fix selector of the identity choicemre
  • bebc88e4ident#34: main.hl drops the unstyled classes inboxlink and whomre
  • b4e7ad04ident#34: the identity choice link/button has no class (rule on #chooselist a)mre
  • 3c33d6eaident#34: the connection link in inbox has no class (rule on #conns a)mre
  • dc97ec0dident#34: the Notif. chip and the Used in link share chipLook (Style.pChip) instead of the classes chip/used/notifmre
  • 378bd432ident#34: the identity picture look is a static in styles.hl (Style.pAvatar); sizes stay with each listmre
  • 1cf79e7eident#34: the wide page column is a static in styles.hl (Style.pWide), not the class "wide"mre
  • ddc7d135Merge branch 'f7-hooks' into mainIdent
  • eee0b513|||PR ident#34 part: test-hook classes replaced by name/element/attribute selectors (tests adjusted), the shared lead/message/notice looks are statics in styles.hlmre
  • ccd6d0c4ident#34: browser gate: rowButton finds the row's button by namemre
  • 24dd414eident#34: the shared lead, message and notice looks are statics in components/styles.hl, imported by the components (lib/looks.hl gone)mre
  • 03ed26c7ident#34: access.hl: the remaining lead classes droppedmre
  • 1d066c42ident#34: access.hl drops its unstyled lead class (the shared lead rule would otherwise mute it)mre
  • 1e1dd7b4ident#34: the access page keeps its lead class string (the page has no ident-card, so its lead line was never muted; a shared rule would change the look)mre
  • 89ac6553ident#34: the lead, message and notice lines are named with Style.pLead / pMessage / pNotice (shared bodies in lib/looks.hl) instead of class stringsmre
  • e84be3deident#34: browser gate lists the Edit/Delete buttons by namemre
  • fb7111faident#34: access page: unstyled test-hook classes (idrow, never, who, whoname, appname, neverrevoke) dropped; the tests use element/name selectorsmre