gitoriaLog in with ident

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit8cda54128cda5412notes mission 002 (1/4): code order — files moved: lib/notes.hl, lib/users.hl, lib/jsoncheck.hl, components/styles.hl (imports only); gates 50/0 + 18/0, live-data run identicalmre8cda5412/tests/short-id-switch.mjs

17.7 KB

  1. // tests/short-id-switch.mjs — THE SHORT-ID SWITCH GATE of notes.worldapi.org (mission 039, ident#23), all over HTTP, no browser:
  2. // 1. the OLD ident (the pre-ident#23 build, a copy of its code: OLD_IDENT_DIR, default
  3. // ident.worldapi.org/.scratch/pre-023-ident) + this app on a fresh store: alice (Default AND a second identity
  4. // "Work") and bob log in and make data; alice's "Work" identity is deleted in ident afterwards;
  5. // 2. both stop; the ident store and the app store are COPIED (the originals stay as they were);
  6. // 3. the NEW ident (ident#23's dev build, a copy of ident.worldapi.org's code: NEW_IDENT_DIR) on the ident copy;
  7. // 4. CONTROL: the app on an UNMIGRATED copy → alice comes back as a NEW user (why the migration is needed);
  8. // 5. tools/migrate-short-ids.hl on the other copy, TWICE: counts; the second run changes nothing;
  9. // 6. the app on the migrated copy with the new ident: alice's OLD app session still works; a fresh login through the
  10. // new ident finds the SAME user with the SAME data; bob too; nobody sees the other's data.
  11. // Ports 8720, 8721 (ident, app). Work dir .scratch/m039-switch (wiped at start). Every process started is stopped by PID.
  12. // node tests/short-id-switch.mjs
  13. import { spawn, execFileSync } from 'node:child_process';
  14. import { cpSync, mkdirSync, readFileSync, rmSync, existsSync, writeFileSync } from 'node:fs';
  15. import { dirname, join, resolve } from 'node:path';
  16. import { fileURLToPath } from 'node:url';
  17. import { copyIdent } from './identkit.mjs';
  18. const HERE = dirname(fileURLToPath(import.meta.url));
  19. const APP = resolve(HERE, '..');
  20. const BIN = join(APP, 'bin/hybriel');
  21. const PROJECTS = resolve(APP, '..');
  22. const NEW_IDENT_DIR = process.env.NEW_IDENT_DIR || join(PROJECTS, 'ident.worldapi.org');
  23. const OLD_IDENT_DIR = process.env.OLD_IDENT_DIR || join(PROJECTS, 'ident.worldapi.org/.scratch/pre-023-ident');
  24. const IDENT_PORT = 8720, PORT = 8721;
  25. const ID = `http://127.0.0.1:${IDENT_PORT}`;
  26. const BASE = `http://127.0.0.1:${PORT}`;
  27. const W = join(APP, '.scratch/m039-switch');
  28. const J = JSON.stringify;
  29. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  30. const SHORT = /^[2-9a-hj-km-np-z]{5}$/;
  31. const OLD = /^[0-9a-f]{32}$/;
  32. let passed = 0, failed = 0;
  33. const check = (name, ok, detail = '') => {
  34. if (ok) { passed++; console.log(' ok ' + name); } else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); }
  35. };
  36. let log = '';
  37. const procs = new Set();
  38. function start(label, bin, args, cwd, env) {
  39. log += `\n==== ${label}\n`;
  40. const p = spawn(bin, args, { cwd, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] });
  41. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d);
  42. procs.add(p);
  43. return p;
  44. }
  45. async function stop(p) {
  46. if (!p) return;
  47. try { p.kill('SIGTERM'); } catch {}
  48. await new Promise(r => { if (p.exitCode !== null || p.signalCode !== null) return r(); p.once('exit', r); setTimeout(r, 3000); });
  49. procs.delete(p);
  50. }
  51. async function up(url, what) {
  52. for (let i = 0; i < 120; i++) { try { const r = await fetch(url, { redirect: 'manual' }); if (r.status < 500) return; } catch {} await sleep(250); }
  53. throw new Error(what + ' did not come up\n' + log.slice(-3000));
  54. }
  55. // ---- ident (old or new code, on a given data dir; codes go to a mail sink — never real mail) -------------------
  56. async function startIdentOn(codeDir, dataDir) {
  57. mkdirSync(dataDir, { recursive: true });
  58. const sink = join(dataDir, 'mail.txt');
  59. if (!existsSync(sink)) writeFileSync(sink, '');
  60. const p = start('ident ' + codeDir, join(codeDir, 'bin/hybriel'), ['project.hl'], codeDir, {
  61. IDENT_PORT: String(IDENT_PORT), IDENT_STORAGE: join(dataDir, 'mpackdb'), IDENT_SESSIONS: join(dataDir, 'sessions') + '/',
  62. IDENT_MAIL_SINK: sink, IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000', IDENT_WATCH: '0', HL_HOST: '127.0.0.1',
  63. SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '' });
  64. await up(ID + '/', 'ident');
  65. return { p, sink };
  66. }
  67. let iemitI = 0;
  68. async function identEmit(event, payload, cookie) {
  69. const r = await fetch(ID + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++iemitI, event, payload }) });
  70. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  71. return { value: j && j.value, raw: t, setCookie: (r.headers.get('set-cookie') || '').split(';')[0] };
  72. }
  73. async function identSignIn(sink, email) {
  74. const c = await fetch(ID + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email }) });
  75. if (c.status !== 200) throw new Error('ident code refused: ' + c.status);
  76. const code = readFileSync(sink, 'utf8').trim().split('\n').filter(l => l.startsWith(email + ' ')).pop().split(' ')[1];
  77. const v = await identEmit('verifyCode', [email, code, 'Europe/Vienna']);
  78. if (!v.value || !v.value.account) throw new Error('ident sign-in failed: ' + v.raw);
  79. return { email, cookie: v.setCookie, identities: v.value.identities };
  80. }
  81. // the selector's path: identities (as the app's page asks) → choose → one-time code
  82. async function selectorCode(who, app, identityName = null) {
  83. const l = await (await fetch(ID + '/api/selector/identities?key=' + app.key, { headers: { origin: BASE, cookie: who.cookie } })).json();
  84. if (!l.identities || !l.identities.length) throw new Error('no identities: ' + J(l));
  85. const pick = identityName ? l.identities.find(i => i.name === identityName) : l.identities[0];
  86. if (!pick) throw new Error('no identity named ' + identityName + ': ' + J(l));
  87. const c = await (await fetch(ID + '/api/selector/choose?key=' + app.key, { method: 'POST', headers: { origin: BASE, cookie: who.cookie, 'content-type': 'application/json' }, body: J({ identity: pick.id }) })).json();
  88. if (!c.code) throw new Error('choose failed: ' + J(c));
  89. return c.code;
  90. }
  91. // ---- the app -----------------------------------------------------------------------------------------------------
  92. async function startApp(codeDir, store, app, extra = {}) {
  93. const p = start('notes.worldapi.org on ' + store, join(codeDir, 'bin/hybriel'), ['project.hl'], codeDir, {
  94. ...appEnv(store), HL_HOST: '127.0.0.1', IDENT_URL: ID, IDENT_EXCHANGE_URL: ID, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret, ...extra });
  95. await up(BASE + '/', 'notes.worldapi.org');
  96. return p;
  97. }
  98. // the login button's / selector's landing: <app>/login/callback?ident_code= → the app's session cookie
  99. async function appLogin(who, app, identityName = null, cookie = null) {
  100. const code = await selectorCode(who, app, identityName);
  101. const r = await fetch(BASE + '/login/callback?ident_code=' + code, { redirect: 'manual', headers: cookie ? { cookie } : {} });
  102. const loc = r.headers.get('location') || '';
  103. if (r.status !== 302 || loc.startsWith('/login/failed')) {
  104. let why = r.status !== 302 ? (await r.text()).replace(/<(style|script)[\s\S]*?<\/(style|script)>/g, " ").replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200) : '';
  105. const sc = (r.headers.get('set-cookie') || '').split(';')[0] || cookie;
  106. if (r.status === 302) try { why = await (await fetch(BASE + '/login/failed', { headers: sc ? { cookie: sc } : {} })).text(); why = (why.match(/login failed[^<]*|ident refused[^<]*|that is not[^<]*/i) || [why.slice(0, 200)])[0]; } catch {}
  107. return { error: 'login failed (' + r.status + ' → ' + loc + ') ' + why };
  108. }
  109. return { cookie: (r.headers.get('set-cookie') || '').split(';')[0] || cookie };
  110. }
  111. let aemitI = 0;
  112. async function appEmit(cookie, event, payload) {
  113. const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie }, body: J({ t: 'emit', i: ++aemitI, event, payload }) });
  114. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  115. return j && j.value !== undefined ? j.value : { error: 'no value: ' + t.slice(0, 300) };
  116. }
  117. const runTool = (store, app) => execFileSync(BIN, ['tools/migrate-short-ids.hl'], { cwd: APP, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],
  118. env: { ...process.env, ...appEnv(store), IDENT_EXCHANGE_URL: ID, IDENT_URL: ID, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret } });
  119. const counts = (out) => { const m = out.match(/users seen (\d+), mapped (\d+), already short (\d+), unmapped (\d+), conflicts (\d+), failed (\d+)/); return m ? m.slice(1).map(Number) : null; };
  120. // ---- notes: what a user has — /api/me (the users @id) and the notes (/api/notes) ------------------------------------
  121. const appEnv = (store) => ({ NOTES_PORT: String(PORT), NOTES_STORAGE: join(store, 'mpackdb'), NOTES_SESSIONS: join(store, 'sessions') + '/', NOTES_WATCH: '0', NOTES_PUBLIC_URL: BASE });
  122. const prepareCode = async () => APP;
  123. const firstEnv = async () => ({});
  124. const laterEnv = async () => ({});
  125. const toolExtra = async () => {};
  126. const getJ = async (path, cookie) => { const r = await fetch(BASE + path, { headers: { cookie } }); return { status: r.status, j: await r.json() }; };
  127. const postJ = async (body, cookie) => { const r = await fetch(BASE + '/api/notes', { method: 'POST', headers: { cookie, 'content-type': 'application/json' }, body: J(body) }); return { status: r.status, j: await r.json() }; };
  128. async function makeData(ca, cb, cw) {
  129. const out = {};
  130. for (const [who, cookie, text] of [['alice', ca, '# Alice note\nonly hers'], ['bob', cb, '# Bob note\nonly his'], ['work', cw, '# Work note']]) {
  131. const me = (await getJ('/api/me', cookie)).j.user;
  132. const s = await postJ({ op: 'save', id: '', local: 'l-' + who, text, base: 0, at: Date.now() }, cookie);
  133. out[who] = { user: me, note: s.j.id, text };
  134. }
  135. check('old world: three users, one note each', new Set([out.alice.user, out.bob.user, out.work.user]).size === 3 && out.alice.note && out.bob.note && out.work.note, J(out));
  136. return out;
  137. }
  138. async function isNewEmptyUser(cookie, before) {
  139. const me = (await getJ('/api/me', cookie)).j.user;
  140. const list = (await getJ('/api/notes', cookie)).j.notes;
  141. return me && me !== before.alice.user && Array.isArray(list) && list.length === 0;
  142. }
  143. async function sameUser(label, cookie, who) {
  144. const me = (await getJ('/api/me', cookie)).j.user;
  145. const list = (await getJ('/api/notes', cookie)).j.notes || [];
  146. const n = await getJ('/api/notes?id=' + who.note, cookie);
  147. check(label + ': the SAME user (users @id), exactly the own note, same text',
  148. me === who.user && list.length === 1 && list[0].id === who.note && n.status === 200 && n.j.text === who.text, J({ me, want: who.user, list, n: n.status }));
  149. }
  150. let identP = null, appP = null;
  151. try {
  152. rmSync(W, { recursive: true, force: true });
  153. mkdirSync(W, { recursive: true });
  154. const oldCode = join(W, 'ident-old-code'), newCode = join(W, 'ident-new-code');
  155. copyIdent(OLD_IDENT_DIR, oldCode);
  156. copyIdent(NEW_IDENT_DIR, newCode);
  157. const oldIsOld = !readFileSync(join(oldCode, 'store.hl'), 'utf8').includes('shortId');
  158. const newIsNew = readFileSync(join(newCode, 'project.hl'), 'utf8').includes('migrate-ids');
  159. check('the old ident has no short ids, the new one has /api/migrate-ids', oldIsOld && newIsNew);
  160. const CODE = await prepareCode();
  161. // ---- 1. the OLD world -------------------------------------------------------------------------------------------
  162. console.log('# 1. old ident + notes.worldapi.org, data made');
  163. let id = await startIdentOn(oldCode, join(W, 'ident-data'));
  164. identP = id.p;
  165. const alice = await identSignIn(id.sink, '[email protected]');
  166. const bob = await identSignIn(id.sink, '[email protected]');
  167. const added = await identEmit('addIdentity', [{ identityName: 'Work' }], alice.cookie);
  168. const work = added.value && added.value.identities ? added.value.identities.find(i => i.identityName === 'Work') : null;
  169. const reg = await identEmit('appCreate', [{ name: 'notes.worldapi.org', origins: [BASE] }], alice.cookie);
  170. if (!reg.value || !reg.value.secret) throw new Error('appCreate failed: ' + reg.raw);
  171. const app = { key: reg.value.app.apiKey, secret: reg.value.secret };
  172. writeFileSync(join(W, 'test-app-key.json'), J(app)); // the THROW-AWAY test app's key (for a by-hand rerun of the tool)
  173. appP = await startApp(CODE, join(W, 'app-store'), app, await firstEnv());
  174. const a1 = await appLogin(alice, app), b1 = await appLogin(bob, app);
  175. const w1 = await appLogin(alice, app, 'Work');
  176. check('old ident: alice, bob and alice\'s "Work" log in to notes.worldapi.org', !a1.error && !b1.error && !w1.error && work != null, J([a1.error, b1.error, w1.error]));
  177. const before = await makeData(a1.cookie, b1.cookie, w1.cookie);
  178. await stop(appP); appP = null;
  179. const dropped = await identEmit('dropIdentity', [work.id], alice.cookie);
  180. check('alice deletes her "Work" identity in ident (its app user becomes UNMAPPED)', dropped.value && !dropped.value.error, dropped.raw.slice(0, 200));
  181. await stop(identP); identP = null;
  182. // ---- 2. copies --------------------------------------------------------------------------------------------------
  183. cpSync(join(W, 'ident-data'), join(W, 'ident-data-new'), { recursive: true });
  184. cpSync(join(W, 'app-store'), join(W, 'app-store-control'), { recursive: true });
  185. cpSync(join(W, 'app-store'), join(W, 'app-store-migrated'), { recursive: true });
  186. // ---- 3. the NEW ident on the copy -------------------------------------------------------------------------------
  187. console.log('# 2. new ident (ident#23) on a copy of the old ident store');
  188. id = await startIdentOn(newCode, join(W, 'ident-data-new'));
  189. identP = id.p;
  190. const mig = await (await fetch(ID + '/api/migrate-ids', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J(app) })).json();
  191. const olds = Object.keys(mig.ids || {});
  192. check('new ident: migrate-ids maps 2 old ids (alice Default, bob) to short ids; the deleted identity is left out; not finished',
  193. olds.length === 2 && olds.every(k => OLD.test(k)) && Object.values(mig.ids).every(v => SHORT.test(v)) && mig.finished === false, J(mig));
  194. // ---- 4. CONTROL: unmigrated store ---------------------------------------------------------------------------------
  195. console.log('# 3. control: the app on an UNMIGRATED copy');
  196. appP = await startApp(CODE, join(W, 'app-store-control'), app, await laterEnv(mig));
  197. const c1 = await appLogin(alice, app);
  198. if (c1.error) check('control: login through the new ident fails or …', false, c1.error);
  199. else check('control (not migrated): alice comes back as a NEW, EMPTY user — this is what the migration prevents', await isNewEmptyUser(c1.cookie, before), '');
  200. await stop(appP); appP = null;
  201. // ---- 5. the migration, twice --------------------------------------------------------------------------------------
  202. console.log('# 4. tools/migrate-short-ids.hl on the other copy, twice');
  203. const r1 = runTool(join(W, 'app-store-migrated'), app);
  204. writeFileSync(join(W, 'migrate-run1.txt'), r1);
  205. console.log(r1.trim().split('\n').map(l => ' | ' + l).join('\n'));
  206. check('run 1: users seen 3, mapped 2, already short 0, unmapped 1 (deleted identity), conflicts 0, failed 0', J(counts(r1)) === J([3, 2, 0, 1, 0, 0]), J(counts(r1)));
  207. const shorts = [...r1.matchAll(/MAPPED user \S+ → (\S+)/g)].map(m => m[1]).sort();
  208. check('run 1: the users now hold exactly the short ids ident mapped', J(shorts) === J(Object.values(mig.ids).sort()), J([shorts, mig.ids]));
  209. check('run 1 never prints the key or the secret', !r1.includes(app.secret) && !r1.includes(app.key));
  210. const r2 = runTool(join(W, 'app-store-migrated'), app);
  211. writeFileSync(join(W, 'migrate-run2.txt'), r2);
  212. check('run 2 (idempotent): seen 3, mapped 0, already short 2, unmapped 1', J(counts(r2)) === J([3, 0, 2, 1, 0, 0]), J(counts(r2)));
  213. await toolExtra(r1, r2, mig, app, alice);
  214. const badSecret = (() => { try { runTool(join(W, 'app-store-migrated'), { key: app.key, secret: 'sk_' + '0'.repeat(48) }); return 'ran'; } catch (e) { return String(e.stdout || '') + String(e.stderr || ''); } })();
  215. // the control copy: the app ran with the new ident BEFORE the migration and made a new user for alice's short id
  216. const rc = (() => { try { return 'exit 0: ' + runTool(join(W, 'app-store-control'), app); } catch (e) { return String(e.stdout || '') + String(e.stderr || ''); } })();
  217. writeFileSync(join(W, 'migrate-control.txt'), rc);
  218. check('the tool on the control copy (app ran before the migration): alice = CONFLICT, left alone, exit non-zero',
  219. J(counts(rc)) === J([4, 1, 1, 1, 1, 0]) && /CONFLICT user/.test(rc) && /CONFLICTS:/.test(rc) && !rc.startsWith('exit 0'), rc.slice(0, 400));
  220. check('a wrong secret: the tool stops with ident\'s 401, changes nothing', /401/.test(badSecret), badSecret.slice(0, 300));
  221. // ---- 6. the app on the migrated store ------------------------------------------------------------------------------
  222. console.log('# 5. the app on the MIGRATED copy with the new ident');
  223. appP = await startApp(CODE, join(W, 'app-store-migrated'), app, await laterEnv(mig));
  224. await sameUser('alice, OLD app session (no new login)', a1.cookie, before.alice);
  225. const a2 = await appLogin(alice, app);
  226. check('alice logs in again through the new ident', !a2.error, a2.error);
  227. if (!a2.error) await sameUser('alice, fresh login through the new ident', a2.cookie, before.alice, mig);
  228. const b2 = await appLogin(bob, app);
  229. check('bob logs in again through the new ident', !b2.error, b2.error);
  230. if (!b2.error) await sameUser('bob, fresh login through the new ident', b2.cookie, before.bob, mig);
  231. await stop(appP); appP = null;
  232. const r3 = runTool(join(W, 'app-store-migrated'), app);
  233. writeFileSync(join(W, 'migrate-run3.txt'), r3);
  234. check('after the logins: still 3 users (no new one was made), all short or unmapped as before', J(counts(r3)) === J([3, 0, 2, 1, 0, 0]), J(counts(r3)));
  235. await stop(identP); identP = null;
  236. } catch (err) {
  237. failed++; console.log(' FAIL (aborted) ' + (err.stack || err));
  238. } finally {
  239. for (const p of [...procs]) await stop(p);
  240. mkdirSync(W, { recursive: true });
  241. writeFileSync(join(W, 'servers.log'), log);
  242. }
  243. console.log(`\n${passed} passed, ${failed} failed`);
  244. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • 8cda5412notes mission 002 (1/4): code order — files moved: lib/notes.hl, lib/users.hl, lib/jsoncheck.hl, components/styles.hl (imports only); gates 50/0 + 18/0, live-data run identicalmre
  • 47dad68bnotes: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gates 50/0 + 18/0mre
  • a4a2b2aeantcolony#40: tracker missions moved too — references to them in missions/reports/LOG.md updatedmre
  • 3dea0ef2notes: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gate 50/0mre
  • e27c7d71notes: Hybriel master 8efba065 (#126 GC by bytes, #48 lambda params copy; audit: nothing to fix; gate 50/0)mre
  • 124613b6antcolony#40: mission references point to the moved missionsmre
  • 1ca2f34dantcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 2bebebdanotes: Hybriel master ff51cf46 (re-vendor round)mre
  • 3eff126dnotes#3: installable app (manifest + own icon/favicon; notes' own sw.js kept)mre
  • 9883c540deploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • eee693b8deploy.sh: never send .git or .gitignore to Byrodinmre
  • c8904061State of 2026-09-27, before the move to gitoriamre