gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchnotes17-ghost-noteae1075b2Preserve rejected drafts during note ID adoptionAtlasnotes17-ghost-note/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

  • ae1075b2Preserve rejected drafts during note ID adoptionAtlas
  • 383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas
  • 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
  • 649cef37|||PR Vendor Hybriel day56Atlas
  • aadd0abcMerge branch 'hl-standard-2' into mainAtlas
  • 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
  • 617ee8c0Merge branch 'hl-standard' into mainAtlas
  • 452458ee|||PR Type the function parameters of notes' own .hl files (HL-STANDARD L10)Atlas
  • 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
  • 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
  • 3e07b1cfVendor complete Hybriel day39 plugin sources and librariesmre
  • d7366702Check session cookie flags after login and assert anonymous GET stays cookielessmre
  • 16bc8fd8Re-vendor Hybriel day38b with the mpackdb store-open race fixmre
  • d860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mre
  • 2e7f8664notes#13: the list and back links pass the note key from the loop (emit pick(e, r.key)) instead of writing data-note into the View and reading it back with getAttribute; the two window.history.replaceState calls and the identcode e.target.value read stay (hl:web has no replace-navigation, a bound hidden input is not adopted on a script's change event), see NO13 reportmre
  • 4dc98282notes#15: a deleted note made in this tab leaves the list at once (the delete now removes this tab's edit under every key the row has: local id, server id); gate: browser.mjs notes#15 section, red on the old codemre
  • e4e7402fnotes#11: plain declarations instead of let for variables never reassigned (components/notes.hl 3, lib/jsoncheck.hl 5, lib/util.hl 2, tools/migrate-short-ids.hl 8)mre
  • 27b6a09enotes#8: Style blocks in the nested form (note-list, note-editor, .ask with their children nested, :empty as a nested pseudo-class); the same CSS rules, the pages look the samemre
  • 71a9538bnotes: B27W report, log linemre
  • 78ba0073notes: an ident access key (Authorization: Bearer idt_…) reads and writes its identity's notes through /api/me and /api/notes; gate tests/ident-access-notes.mjs (ident#27)mre