gitoriaLog in with ident

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commite2deed6de2deed6dgitoria#20: "Add code" only on the Code page of an empty repository, no collapsiblemree2deed6d/tests/short-id-switch.mjs

18.7 KB

  1. // tests/short-id-switch.mjs — THE SHORT-ID SWITCH GATE of gitoria.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 8724, 8725 (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 = 8724, PORT = 8725;
  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('gitoria.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 + '/', 'gitoria.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. // ---- gitoria: what a user has — the display name, repos (owner), access tokens (user); checked through the faces and
  121. // git's own push handshake (/<slug>.git/info/refs?service=git-receive-pack answers 200 only to a token of the OWNER) ----
  122. import { request as httpRequest } from 'node:http';
  123. const appEnv = (store) => ({ GITORIA_PORT: String(PORT), GITORIA_STORAGE: join(store, 'mpackdb'), GITORIA_SESSIONS: join(store, 'sessions') + '/', GITORIA_GIT: join(store, 'git'),
  124. GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: BASE, GITORIA_TICKETS_URL: 'http://127.0.0.1:1', GITORIA_SSH_SECRET: '' });
  125. const prepareCode = async () => APP;
  126. const firstEnv = async () => ({});
  127. const laterEnv = async () => ({});
  128. const toolExtra = async () => {};
  129. const hostOf = (slug) => `${slug}.127.0.0.1:${PORT}`;
  130. const pushAsk = (slug, token) => new Promise((res, rej) => {
  131. const rq = httpRequest({ host: '127.0.0.1', port: PORT, path: `/${slug}.git/info/refs?service=git-receive-pack`, method: 'GET',
  132. headers: { host: hostOf(slug), authorization: 'Basic ' + Buffer.from('x:' + token).toString('base64') } }, (r) => { r.resume(); r.on('end', () => res(r.statusCode)); });
  133. rq.on('error', rej); rq.end();
  134. });
  135. async function makeData(ca, cb, cw) {
  136. const out = {};
  137. for (const [who, cookie, name, slug] of [['alice', ca, 'Alice', 'alice-m039'], ['bob', cb, 'Bob', 'bob-m039'], ['work', cw, 'Workname', null]]) {
  138. const n = await appEmit(cookie, 'gitoriaSaveName', [name]);
  139. const r = slug ? await appEmit(cookie, 'gitoriaCreate', [slug, 'repo of ' + name]) : null;
  140. const t = await appEmit(cookie, 'gitoriaMakeToken', ['laptop']);
  141. out[who] = { name, slug, token: t.token, nameOk: n && n.name === name && !n.error, repoOk: !slug || (r && !r.error) };
  142. }
  143. out.alice.other = out.bob.slug; out.bob.other = out.alice.slug;
  144. const own = await pushAsk('alice-m039', out.alice.token), foreign = await pushAsk('alice-m039', out.bob.token);
  145. check('old world: three users with names and tokens, two repos; the push handshake: owner\'s token 200, another\'s 403',
  146. ['alice', 'bob', 'work'].every(w => out[w].nameOk && out[w].repoOk && /^gtr_/.test(out[w].token || '')) && own === 200 && foreign === 403, J([out, own, foreign]).slice(0, 600));
  147. return out;
  148. }
  149. async function isNewEmptyUser(cookie) {
  150. const n = await appEmit(cookie, 'gitoriaSaveName', ['Alice again']);
  151. return n && !n.error && n.name === 'Alice again'; // a new user: no name yet
  152. }
  153. async function sameUser(label, cookie, who) {
  154. const n = await appEmit(cookie, 'gitoriaSaveName', ['Someone else']);
  155. const t = await appEmit(cookie, 'gitoriaMakeToken', ['after the switch']);
  156. const fresh = t && t.token ? await pushAsk(who.slug, t.token) : 0;
  157. const old = await pushAsk(who.slug, who.token);
  158. const other = t && t.token ? await pushAsk(who.other, t.token) : 0;
  159. check(label + ': the SAME user — name kept (' + who.name + '), a token made now may push to the OWN old repo (200), not to the other\'s (403), the old token still works',
  160. n && /already set/.test(n.error || '') && fresh === 200 && old === 200 && other === 403, J([n, fresh, old, other]));
  161. }
  162. let identP = null, appP = null;
  163. try {
  164. rmSync(W, { recursive: true, force: true });
  165. mkdirSync(W, { recursive: true });
  166. const oldCode = join(W, 'ident-old-code'), newCode = join(W, 'ident-new-code');
  167. copyIdent(OLD_IDENT_DIR, oldCode);
  168. copyIdent(NEW_IDENT_DIR, newCode);
  169. const oldIsOld = !readFileSync(join(oldCode, 'store.hl'), 'utf8').includes('shortId');
  170. const newIsNew = readFileSync(join(newCode, 'project.hl'), 'utf8').includes('migrate-ids');
  171. check('the old ident has no short ids, the new one has /api/migrate-ids', oldIsOld && newIsNew);
  172. const CODE = await prepareCode();
  173. // ---- 1. the OLD world -------------------------------------------------------------------------------------------
  174. console.log('# 1. old ident + gitoria.worldapi.org, data made');
  175. let id = await startIdentOn(oldCode, join(W, 'ident-data'));
  176. identP = id.p;
  177. const alice = await identSignIn(id.sink, '[email protected]');
  178. const bob = await identSignIn(id.sink, '[email protected]');
  179. const added = await identEmit('addIdentity', [{ identityName: 'Work' }], alice.cookie);
  180. const work = added.value && added.value.identities ? added.value.identities.find(i => i.identityName === 'Work') : null;
  181. const reg = await identEmit('appCreate', [{ name: 'gitoria.worldapi.org', origins: [BASE] }], alice.cookie);
  182. if (!reg.value || !reg.value.secret) throw new Error('appCreate failed: ' + reg.raw);
  183. const app = { key: reg.value.app.apiKey, secret: reg.value.secret };
  184. writeFileSync(join(W, 'test-app-key.json'), J(app)); // the THROW-AWAY test app's key (for a by-hand rerun of the tool)
  185. appP = await startApp(CODE, join(W, 'app-store'), app, await firstEnv());
  186. const a1 = await appLogin(alice, app), b1 = await appLogin(bob, app);
  187. const w1 = await appLogin(alice, app, 'Work');
  188. check('old ident: alice, bob and alice\'s "Work" log in to gitoria.worldapi.org', !a1.error && !b1.error && !w1.error && work != null, J([a1.error, b1.error, w1.error]));
  189. const before = await makeData(a1.cookie, b1.cookie, w1.cookie);
  190. await stop(appP); appP = null;
  191. const dropped = await identEmit('dropIdentity', [work.id], alice.cookie);
  192. check('alice deletes her "Work" identity in ident (its app user becomes UNMAPPED)', dropped.value && !dropped.value.error, dropped.raw.slice(0, 200));
  193. await stop(identP); identP = null;
  194. // ---- 2. copies --------------------------------------------------------------------------------------------------
  195. cpSync(join(W, 'ident-data'), join(W, 'ident-data-new'), { recursive: true });
  196. cpSync(join(W, 'app-store'), join(W, 'app-store-control'), { recursive: true });
  197. cpSync(join(W, 'app-store'), join(W, 'app-store-migrated'), { recursive: true });
  198. // ---- 3. the NEW ident on the copy -------------------------------------------------------------------------------
  199. console.log('# 2. new ident (ident#23) on a copy of the old ident store');
  200. id = await startIdentOn(newCode, join(W, 'ident-data-new'));
  201. identP = id.p;
  202. const mig = await (await fetch(ID + '/api/migrate-ids', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J(app) })).json();
  203. const olds = Object.keys(mig.ids || {});
  204. check('new ident: migrate-ids maps 2 old ids (alice Default, bob) to short ids; the deleted identity is left out; not finished',
  205. olds.length === 2 && olds.every(k => OLD.test(k)) && Object.values(mig.ids).every(v => SHORT.test(v)) && mig.finished === false, J(mig));
  206. // ---- 4. CONTROL: unmigrated store ---------------------------------------------------------------------------------
  207. console.log('# 3. control: the app on an UNMIGRATED copy');
  208. appP = await startApp(CODE, join(W, 'app-store-control'), app, await laterEnv(mig));
  209. const c1 = await appLogin(alice, app);
  210. if (c1.error) check('control: login through the new ident fails or …', false, c1.error);
  211. else check('control (not migrated): alice comes back as a NEW, EMPTY user — this is what the migration prevents', await isNewEmptyUser(c1.cookie, before), '');
  212. await stop(appP); appP = null;
  213. // ---- 5. the migration, twice --------------------------------------------------------------------------------------
  214. console.log('# 4. tools/migrate-short-ids.hl on the other copy, twice');
  215. const r1 = runTool(join(W, 'app-store-migrated'), app);
  216. writeFileSync(join(W, 'migrate-run1.txt'), r1);
  217. console.log(r1.trim().split('\n').map(l => ' | ' + l).join('\n'));
  218. 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)));
  219. const shorts = [...r1.matchAll(/MAPPED user \S+ → (\S+)/g)].map(m => m[1]).sort();
  220. 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]));
  221. check('run 1 never prints the key or the secret', !r1.includes(app.secret) && !r1.includes(app.key));
  222. const r2 = runTool(join(W, 'app-store-migrated'), app);
  223. writeFileSync(join(W, 'migrate-run2.txt'), r2);
  224. 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)));
  225. await toolExtra(r1, r2, mig, app, alice);
  226. 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 || ''); } })();
  227. // the control copy: the app ran with the new ident BEFORE the migration and made a new user for alice's short id
  228. const rc = (() => { try { return 'exit 0: ' + runTool(join(W, 'app-store-control'), app); } catch (e) { return String(e.stdout || '') + String(e.stderr || ''); } })();
  229. writeFileSync(join(W, 'migrate-control.txt'), rc);
  230. check('the tool on the control copy (app ran before the migration): alice = CONFLICT, left alone, exit non-zero',
  231. 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));
  232. check('a wrong secret: the tool stops with ident\'s 401, changes nothing', /401/.test(badSecret), badSecret.slice(0, 300));
  233. // ---- 6. the app on the migrated store ------------------------------------------------------------------------------
  234. console.log('# 5. the app on the MIGRATED copy with the new ident');
  235. appP = await startApp(CODE, join(W, 'app-store-migrated'), app, await laterEnv(mig));
  236. await sameUser('alice, OLD app session (no new login)', a1.cookie, before.alice);
  237. const a2 = await appLogin(alice, app);
  238. check('alice logs in again through the new ident', !a2.error, a2.error);
  239. if (!a2.error) await sameUser('alice, fresh login through the new ident', a2.cookie, before.alice, mig);
  240. const b2 = await appLogin(bob, app);
  241. check('bob logs in again through the new ident', !b2.error, b2.error);
  242. if (!b2.error) await sameUser('bob, fresh login through the new ident', b2.cookie, before.bob, mig);
  243. await stop(appP); appP = null;
  244. const r3 = runTool(join(W, 'app-store-migrated'), app);
  245. writeFileSync(join(W, 'migrate-run3.txt'), r3);
  246. 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)));
  247. await stop(identP); identP = null;
  248. } catch (err) {
  249. failed++; console.log(' FAIL (aborted) ' + (err.stack || err));
  250. } finally {
  251. for (const p of [...procs]) await stop(p);
  252. mkdirSync(W, { recursive: true });
  253. writeFileSync(join(W, 'servers.log'), log);
  254. }
  255. console.log(`\n${passed} passed, ${failed} failed`);
  256. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • e2deed6dgitoria#20: "Add code" only on the Code page of an empty repository, no collapsiblemre
  • 8bb97ffddeploy.sh: never send .git or .gitignore to Byrodinmre
  • fd981932State of 2026-09-27; bin/ no longer tracked (Hybriel commit is in README)mre
  • 4a2d7125initial commitmre