gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit1a8603d11a8603d1notes mission 011 WIP: deploy.sh gate summary also matches check-theme, browser.mjs logout via the user menumre1a8603d1/tests/identkit.mjs

6.7 KB

  1. // tests/identkit.mjs — helpers for notes' tests that need a REAL ident (ticket #7): a
  2. // throw-away ident instance from ident's code (a COPY without .env, storage, sessions — so it
  3. // can never send mail: codes go to IDENT_MAIL_SINK), its accounts, a registered app, and the
  4. // ident side of the two login flows. Never the live ident, never the dev server on :8351.
  5. //
  6. // const id = await startIdent({ identDir, workDir, port }) // copies the code, starts it
  7. // const alice = await id.signIn('[email protected]') // → { cookie } (identsid=…)
  8. // const app = await id.registerApp(alice, 'tickets', [origin]) // → { key, secret }
  9. // const code = await id.selectorCode(alice, app, origin) // one-time code (the selector's path)
  10. // const pid = await id.exchange(app, code) // → the per-app identity id
  11. // id.stop()
  12. import { spawn } from 'node:child_process';
  13. import { cpSync, mkdirSync, readFileSync, rmSync, existsSync, writeFileSync } from 'node:fs';
  14. import { join } from 'node:path';
  15. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  16. const J = JSON.stringify;
  17. // the ident code, copied without anything that holds secrets or data
  18. const SKIP = new Set(['.env', 'storage', '.sessions', '.scratch', 'server.log', 'server.pid', 'testapp', '.git']);
  19. export function copyIdent(identDir, to) {
  20. rmSync(to, { recursive: true, force: true });
  21. mkdirSync(to, { recursive: true });
  22. cpSync(identDir, to, { recursive: true, filter: (src) => {
  23. const rel = src.slice(identDir.length).replace(/^\/+/, '');
  24. if (rel === '') return true;
  25. return !SKIP.has(rel.split('/')[0]);
  26. } });
  27. if (existsSync(join(to, '.env'))) throw new Error('identkit: a .env was copied — refusing to start');
  28. }
  29. export async function startIdent({ identDir, workDir, port }) {
  30. const code = join(workDir, 'ident-code');
  31. const data = join(workDir, 'ident-data');
  32. copyIdent(identDir, code);
  33. rmSync(data, { recursive: true, force: true });
  34. mkdirSync(data, { recursive: true });
  35. const sink = join(data, 'mail.txt');
  36. writeFileSync(sink, '');
  37. const base = `http://127.0.0.1:${port}`;
  38. // something already answers on the port: our sign-ins would go to ITS mail sink and the code would never be found
  39. // ("email and code must be strings"). Refuse at once, with the real reason.
  40. let taken = false; try { await fetch(base + '/'); taken = true; } catch {}
  41. if (taken) throw new Error('identkit: port ' + port + ' is already in use — another process answers there (NOTES_GATE_IDENT_PORT)');
  42. let log = '';
  43. const proc = spawn(join(code, 'bin/hybriel'), ['project.hl'], {
  44. cwd: code,
  45. env: { ...process.env, IDENT_PORT: String(port), IDENT_STORAGE: join(data, 'mpackdb'), IDENT_SESSIONS: join(data, 'sessions') + '/',
  46. IDENT_MAIL_SINK: sink, IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000', IDENT_WATCH: '0', HL_HOST: '127.0.0.1',
  47. SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '' },
  48. stdio: ['ignore', 'pipe', 'pipe'],
  49. });
  50. proc.stdout.on('data', d => log += d); proc.stderr.on('data', d => log += d);
  51. let up = false;
  52. // a compiling Hybriel (hybriel#148) starts cold in ~20 s: wait up to NOTES_COLD_MS (default 120 s)
  53. for (const end = Date.now() + Number(process.env.NOTES_COLD_MS || 120000); !up && Date.now() < end;) {
  54. if (proc.exitCode !== null || proc.signalCode !== null) throw new Error('ident exited before it came up (port ' + port + ' taken?)\n' + log);
  55. try { const r = await fetch(base + '/'); up = r.ok; } catch {} if (!up) await sleep(250);
  56. }
  57. if (!up) throw new Error('ident did not come up\n' + log);
  58. let emitI = 0;
  59. const emit = async (event, payload, cookie) => {
  60. const r = await fetch(base + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++emitI, event, payload }) });
  61. const setCookie = (r.headers.get('set-cookie') || '').split(';')[0];
  62. const t = await r.text();
  63. let j = null; try { j = JSON.parse(t); } catch {}
  64. return { value: j && j.value, raw: t, setCookie };
  65. };
  66. const lastCode = (email) => {
  67. if (!existsSync(sink)) return null;
  68. const lines = readFileSync(sink, 'utf8').trim().split('\n').filter(l => l.startsWith(email + ' '));
  69. return lines.length ? lines[lines.length - 1].split(' ')[1] : null;
  70. };
  71. return {
  72. base, sink, lastCode, emit, log: () => log, proc,
  73. // an ident account signed in over the REST carrier (the first login creates it)
  74. async signIn(email) {
  75. const c = await fetch(base + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email }) });
  76. if (c.status !== 200) throw new Error('ident code refused: ' + c.status + ' ' + await c.text());
  77. const code = lastCode(email);
  78. if (!code) throw new Error('ident sign-in: no code for ' + email + ' in the mail sink ' + sink + ' — is this our ident answering on ' + base + '?');
  79. const v = await emit('verifyCode', [email, code, 'Europe/Vienna']);
  80. if (!v.value || !v.value.account || !v.setCookie) throw new Error('ident sign-in failed: ' + v.raw);
  81. return { email, cookie: v.setCookie, identities: (v.value.identities || []) };
  82. },
  83. async registerApp(who, name, origins) {
  84. const r = await emit('appCreate', [{ name, origins }], who.cookie);
  85. if (!r.value || !r.value.secret) throw new Error('appCreate failed: ' + r.raw);
  86. return { key: r.value.app.apiKey, secret: r.value.secret, raw: r.value };
  87. },
  88. // the selector's path without a browser: the identities (as the page at `origin` asks) → choose → code
  89. async selectorCode(who, app, origin, identityName = null) {
  90. const l = await fetch(base + '/api/selector/identities?key=' + app.key, { headers: { origin, cookie: who.cookie } });
  91. const lj = await l.json();
  92. if (!lj.identities || !lj.identities.length) throw new Error('no identities: ' + J(lj));
  93. const pick = identityName ? lj.identities.find(i => i.name === identityName) : lj.identities[0];
  94. const c = await fetch(base + '/api/selector/choose?key=' + app.key, { method: 'POST', headers: { origin, cookie: who.cookie, 'content-type': 'application/json' }, body: J({ identity: pick.id }) });
  95. const cj = await c.json();
  96. if (!cj.code) throw new Error('choose failed: ' + J(cj));
  97. return cj.code;
  98. },
  99. async exchange(app, code) {
  100. const r = await fetch(base + '/api/exchange', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ key: app.key, secret: app.secret, code }) });
  101. const j = await r.json();
  102. if (!j.identity) throw new Error('exchange failed: ' + J(j));
  103. return j.identity;
  104. },
  105. async stop() {
  106. try { proc.kill('SIGTERM'); } catch {}
  107. await new Promise(r => { if (proc.exitCode !== null || proc.signalCode !== null) return r(); proc.once('exit', r); setTimeout(r, 3000); });
  108. },
  109. };
  110. }

Branches

Latest commits

  • 1a8603d1notes mission 011 WIP: deploy.sh gate summary also matches check-theme, browser.mjs logout via the user menumre
  • dae2e508notes mission 011 WIP: theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ListFirst, styles cut to the app's own, check-theme gate, e2e auditmre
  • fd36da27notes mission 010: the note editor is the Hybriel MdEditor block (components.hybriel 1442e58, verbatim); md-editor.js, its route, script tag and offlineFiles retired; gate 66/0, realdata-offline 12/0, round-trip and Chrome E2E tests; report 010mre
  • efa92170notes tests/identkit.mjs: refuse a taken ident port, cold-wait deadline, emit, identities; mission 009 reportmre
  • f3dec0f1Merge branch 'w7'mre
  • d1cf966dre-vendor hybriel 97bcf128: offlineFiles for the editor script, 44 px taps, 390 px offline checks, mission 008mre
  • 4a610a21paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • eeaea980report 007: say which runs included the removed checkmre
  • 8a8ad9banotes mission 007: report, LOG, STATUSmre
  • 2cce9c96code order: plain declarations where never reassigned (letcount 0 never); gate: scan every IndexedDB at log-out, soft mode for old-code runs, drop a check that could not failmre
  • 7f6a4090README: offline in Hybriel (hl:web offline, continuation, known md-editor gap); gate waits report instead of crash; realdata-offline checkmre
  • 632223f2notes#4: delete notes-offline.js and sw.js (hl:web's generated worker and kept state replace them)mre
  • 52a2acadgate: offline checks on hl:web's worker/queue, Chrome offline via CDP (reload offline first), one-offline conflict, log-out forgets the kept copymre
  • e5785b03notes#4: the notes page in Hybriel — hl:web offline = [Notes], queued faces notesPut/notesDrop, push notesChanged, value-form notesPull on a tick; notes-offline.js/sw.js no longer loaded or routedmre
  • 510aff75notes#4: server continues a run of saves of one login (by + since), loser keeps writing into its copy; notesFor listmre
  • 0176c4b5mission brief 007mre
  • 06cfa870notes mission 006: re-vendor hybriel 0f396652 (static), reportmre
  • 6c07bd91mission brief w6mre
  • cf64d3d5notes mission 005: stopped at a Hybriel gap (for list repainted during hl:web boot throws, rowKidless); report, LOG, STATUSmre
  • a43b5d2dmission brief 005mre