gitoriaLog in with ident

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitd6c59290d6c59290calendar: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gates 78/0 + 18/0mred6c59290/tests/short-id-switch.mjs

18.2 KB

  1. // tests/short-id-switch.mjs — THE SHORT-ID SWITCH GATE of calendar.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 8722, 8723 (ident, app; CALENDAR_SWITCH_IDENT_PORT / CALENDAR_SWITCH_PORT override). 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 = Number(process.env.CALENDAR_SWITCH_IDENT_PORT || 8722), PORT = Number(process.env.CALENDAR_SWITCH_PORT || 8723);
  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('calendar.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 + '/', 'calendar.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. // ---- calendar: what a user has — the events (faces calSave / calLoad) and the reminder settings ----------------------
  121. const appEnv = (store) => ({ CALENDAR_PORT: String(PORT), CALENDAR_STORAGE: join(store, 'mpackdb'), CALENDAR_SESSIONS: join(store, 'sessions') + '/', CALENDAR_WATCH: '0', CALENDAR_PUBLIC_URL: BASE });
  122. const prepareCode = async () => APP;
  123. const firstEnv = async () => ({});
  124. const laterEnv = async () => ({});
  125. const toolExtra = async () => {};
  126. const pad = (n) => String(n).padStart(2, '0');
  127. const dayOf = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
  128. const inDays = (n) => dayOf(new Date(Date.now() + n * 86400000));
  129. const WIN = [inDays(-3), inDays(30)];
  130. const titles = (v) => (v && v.events ? v.events.map(e => e.$title || e.title).sort() : null);
  131. async function makeData(ca, cb, cw) {
  132. const out = {};
  133. for (const [who, cookie, title] of [['alice', ca, 'Alice dentist'], ['bob', cb, 'Bob football'], ['work', cw, 'Work meeting']]) {
  134. const v = await appEmit(cookie, 'calSave', [{ title, allDay: false, startDate: inDays(3), startTime: '10:00', endDate: '', endTime: '', place: 'here', notes: who, zone: 'Europe/Vienna', custom: false, reminders: [] }, WIN[0], WIN[1]]);
  135. out[who] = { title, saved: v };
  136. }
  137. // alice also keeps her OWN default reminders (settings.db, owner = users @id)
  138. const st = await appEmit(ca, 'calSettingsSave', [[{ n: '2', unit: 'hours' }]]);
  139. out.alice.settings = (await appEmit(ca, 'calSettingsLoad', [])).rows;
  140. check('old world: three users, one event each; alice has her own default reminder', ['alice', 'bob', 'work'].every(w => J(titles(out[w].saved)) === J([out[w].title])) && !st.error && Array.isArray(out.alice.settings) && out.alice.settings.length === 1 && out.alice.settings[0].unit === 'hours' && out.alice.settings[0].n === '2',
  141. J([st, out.alice.settings, titles(out.alice.saved)]).slice(0, 600));
  142. return out;
  143. }
  144. async function isNewEmptyUser(cookie) {
  145. const v = await appEmit(cookie, 'calLoad', WIN);
  146. return v && !v.error && Array.isArray(v.events) && v.events.length === 0;
  147. }
  148. async function sameUser(label, cookie, who) {
  149. const v = await appEmit(cookie, 'calLoad', WIN);
  150. let ok = J(titles(v)) === J([who.title]);
  151. if (who.settings) ok = ok && J((await appEmit(cookie, 'calSettingsLoad', [])).rows) === J(who.settings);
  152. check(label + ': the SAME user — exactly the own event' + (who.settings ? ' and the own reminder settings' : ''), ok, J(v).slice(0, 400));
  153. }
  154. let identP = null, appP = null;
  155. try {
  156. rmSync(W, { recursive: true, force: true });
  157. mkdirSync(W, { recursive: true });
  158. const oldCode = join(W, 'ident-old-code'), newCode = join(W, 'ident-new-code');
  159. copyIdent(OLD_IDENT_DIR, oldCode);
  160. copyIdent(NEW_IDENT_DIR, newCode);
  161. const oldIsOld = !readFileSync(join(oldCode, 'store.hl'), 'utf8').includes('shortId');
  162. const newIsNew = readFileSync(join(newCode, 'project.hl'), 'utf8').includes('migrate-ids');
  163. check('the old ident has no short ids, the new one has /api/migrate-ids', oldIsOld && newIsNew);
  164. const CODE = await prepareCode();
  165. // ---- 1. the OLD world -------------------------------------------------------------------------------------------
  166. console.log('# 1. old ident + calendar.worldapi.org, data made');
  167. let id = await startIdentOn(oldCode, join(W, 'ident-data'));
  168. identP = id.p;
  169. const alice = await identSignIn(id.sink, '[email protected]');
  170. const bob = await identSignIn(id.sink, '[email protected]');
  171. const added = await identEmit('addIdentity', [{ identityName: 'Work' }], alice.cookie);
  172. const work = added.value && added.value.identities ? added.value.identities.find(i => i.identityName === 'Work') : null;
  173. const reg = await identEmit('appCreate', [{ name: 'calendar.worldapi.org', origins: [BASE] }], alice.cookie);
  174. if (!reg.value || !reg.value.secret) throw new Error('appCreate failed: ' + reg.raw);
  175. const app = { key: reg.value.app.apiKey, secret: reg.value.secret };
  176. writeFileSync(join(W, 'test-app-key.json'), J(app)); // the THROW-AWAY test app's key (for a by-hand rerun of the tool)
  177. appP = await startApp(CODE, join(W, 'app-store'), app, await firstEnv());
  178. const a1 = await appLogin(alice, app), b1 = await appLogin(bob, app);
  179. const w1 = await appLogin(alice, app, 'Work');
  180. check('old ident: alice, bob and alice\'s "Work" log in to calendar.worldapi.org', !a1.error && !b1.error && !w1.error && work != null, J([a1.error, b1.error, w1.error]));
  181. const before = await makeData(a1.cookie, b1.cookie, w1.cookie);
  182. await stop(appP); appP = null;
  183. const dropped = await identEmit('dropIdentity', [work.id], alice.cookie);
  184. check('alice deletes her "Work" identity in ident (its app user becomes UNMAPPED)', dropped.value && !dropped.value.error, dropped.raw.slice(0, 200));
  185. await stop(identP); identP = null;
  186. // ---- 2. copies --------------------------------------------------------------------------------------------------
  187. cpSync(join(W, 'ident-data'), join(W, 'ident-data-new'), { recursive: true });
  188. cpSync(join(W, 'app-store'), join(W, 'app-store-control'), { recursive: true });
  189. cpSync(join(W, 'app-store'), join(W, 'app-store-migrated'), { recursive: true });
  190. // ---- 3. the NEW ident on the copy -------------------------------------------------------------------------------
  191. console.log('# 2. new ident (ident#23) on a copy of the old ident store');
  192. id = await startIdentOn(newCode, join(W, 'ident-data-new'));
  193. identP = id.p;
  194. const mig = await (await fetch(ID + '/api/migrate-ids', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J(app) })).json();
  195. const olds = Object.keys(mig.ids || {});
  196. check('new ident: migrate-ids maps 2 old ids (alice Default, bob) to short ids; the deleted identity is left out; not finished',
  197. olds.length === 2 && olds.every(k => OLD.test(k)) && Object.values(mig.ids).every(v => SHORT.test(v)) && mig.finished === false, J(mig));
  198. // ---- 4. CONTROL: unmigrated store ---------------------------------------------------------------------------------
  199. console.log('# 3. control: the app on an UNMIGRATED copy');
  200. appP = await startApp(CODE, join(W, 'app-store-control'), app, await laterEnv(mig));
  201. const c1 = await appLogin(alice, app);
  202. if (c1.error) check('control: login through the new ident fails or …', false, c1.error);
  203. else check('control (not migrated): alice comes back as a NEW, EMPTY user — this is what the migration prevents', await isNewEmptyUser(c1.cookie, before), '');
  204. await stop(appP); appP = null;
  205. // ---- 5. the migration, twice --------------------------------------------------------------------------------------
  206. console.log('# 4. tools/migrate-short-ids.hl on the other copy, twice');
  207. const r1 = runTool(join(W, 'app-store-migrated'), app);
  208. writeFileSync(join(W, 'migrate-run1.txt'), r1);
  209. console.log(r1.trim().split('\n').map(l => ' | ' + l).join('\n'));
  210. 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)));
  211. const shorts = [...r1.matchAll(/MAPPED user \S+ → (\S+)/g)].map(m => m[1]).sort();
  212. 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]));
  213. check('run 1 never prints the key or the secret', !r1.includes(app.secret) && !r1.includes(app.key));
  214. const r2 = runTool(join(W, 'app-store-migrated'), app);
  215. writeFileSync(join(W, 'migrate-run2.txt'), r2);
  216. 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)));
  217. await toolExtra(r1, r2, mig, app, alice);
  218. 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 || ''); } })();
  219. // the control copy: the app ran with the new ident BEFORE the migration and made a new user for alice's short id
  220. const rc = (() => { try { return 'exit 0: ' + runTool(join(W, 'app-store-control'), app); } catch (e) { return String(e.stdout || '') + String(e.stderr || ''); } })();
  221. writeFileSync(join(W, 'migrate-control.txt'), rc);
  222. check('the tool on the control copy (app ran before the migration): alice = CONFLICT, left alone, exit non-zero',
  223. 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));
  224. check('a wrong secret: the tool stops with ident\'s 401, changes nothing', /401/.test(badSecret), badSecret.slice(0, 300));
  225. // ---- 6. the app on the migrated store ------------------------------------------------------------------------------
  226. console.log('# 5. the app on the MIGRATED copy with the new ident');
  227. appP = await startApp(CODE, join(W, 'app-store-migrated'), app, await laterEnv(mig));
  228. await sameUser('alice, OLD app session (no new login)', a1.cookie, before.alice);
  229. const a2 = await appLogin(alice, app);
  230. check('alice logs in again through the new ident', !a2.error, a2.error);
  231. if (!a2.error) await sameUser('alice, fresh login through the new ident', a2.cookie, before.alice, mig);
  232. const b2 = await appLogin(bob, app);
  233. check('bob logs in again through the new ident', !b2.error, b2.error);
  234. if (!b2.error) await sameUser('bob, fresh login through the new ident', b2.cookie, before.bob, mig);
  235. await stop(appP); appP = null;
  236. const r3 = runTool(join(W, 'app-store-migrated'), app);
  237. writeFileSync(join(W, 'migrate-run3.txt'), r3);
  238. 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)));
  239. await stop(identP); identP = null;
  240. } catch (err) {
  241. failed++; console.log(' FAIL (aborted) ' + (err.stack || err));
  242. } finally {
  243. for (const p of [...procs]) await stop(p);
  244. mkdirSync(W, { recursive: true });
  245. writeFileSync(join(W, 'servers.log'), log);
  246. }
  247. console.log(`\n${passed} passed, ${failed} failed`);
  248. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • d6c59290calendar: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gates 78/0 + 18/0mre
  • 7bd0337ccalendar: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gates 78/0 + 18/0mre
  • ff41310ccalendar: Hybriel master 8efba065 (#126 memory, #48 lambda copy; audit: no & needed)mre
  • 14ba08c7antcolony#40: mission references point to the moved missionsmre
  • 99c73346antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 76edaa62calendar: Hybriel master ff51cf46 (re-vendor round, static workaround removed)mre
  • 90a3fc2cdeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • 6722b72ddeploy.sh: never send .git or .gitignore to Byrodinmre
  • be099807State of 2026-09-27, before the move to gitoriamre