gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain0f6d1592Merge branch 'f18b-shell-session' into mainIdentmain/tests/sessionwrites.mjs

9.5 KB

  1. // tests/sessionwrites.mjs — GATE A28G: the functions of lib/login.hl and lib/api.hl that take the session as an &-parameter must really
  2. // write to the visitor's session. Since Hybriel day26 (hybriel#48/#76) a call without & hands over a COPY, so a write in the callee can
  3. // vanish silently. This gate looks at the SESSION FILES on disk and at what the next request sees, over plain HTTP (no browser):
  4. // 1. home path: the pending address is recorded (rememberPending), the /code page shows the code step, verifyCode signs the session in
  5. // (user in the file, pendingEmail cleared), a reload (new request, same cookie) is still signed in, /code then redirects away.
  6. // 2. forgetPending clears a recorded address in the file.
  7. // 3. embed path: a second visitor signs in through /embed/signin + verifyCode; the session file carries the user.
  8. // 4. selector: the signed-in cookie sees its identities and a choice gives a code, again on a fresh request.
  9. // Own server (NEVER the dev server, NEVER real mail): ident on SESSIONWRITES_PORT (default 8700), storage .scratch/sessionwrites-gate (wiped at start).
  10. // Run: node tests/sessionwrites.mjs (SESSIONWRITES_APP=<checkout> runs it against that code)
  11. import { spawn } from 'node:child_process';
  12. import { readFileSync, readdirSync, rmSync, mkdirSync, writeFileSync } from 'node:fs';
  13. import { dirname, join } from 'node:path';
  14. import { fileURLToPath } from 'node:url';
  15. const APP = process.env.SESSIONWRITES_APP || join(dirname(fileURLToPath(import.meta.url)), '..');
  16. const G = join(APP, '.scratch/sessionwrites-gate');
  17. const PORT = Number(process.env.SESSIONWRITES_PORT || 8700);
  18. const ID = 'http://127.0.0.1:' + PORT;
  19. const ORIGIN = 'http://127.0.0.1:' + (PORT + 1); // the origin registered for the app (nothing listens there; only the Origin header matters)
  20. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  21. let passed = 0, failed = 0;
  22. const check = (name, ok, detail = '') => { if (ok) { passed++; console.log(' ok ' + name); } else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); } };
  23. rmSync(G, { recursive: true, force: true });
  24. mkdirSync(G, { recursive: true });
  25. const sessDir = join(G, 'sess');
  26. const mail = join(G, 'mail.txt');
  27. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, env: { ...process.env, SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', IDENT_PORT: String(PORT), IDENT_STORAGE: join(G, 'ident'), IDENT_SESSIONS: sessDir + '/', IDENT_MAIL_SINK: mail, IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000' }, stdio: ['ignore', 'pipe', 'pipe'] });
  28. let out = ''; p.stdout.on('data', d => { out += d; }); p.stderr.on('data', d => { out += d; });
  29. p.on('exit', () => writeFileSync(join(G, 'ident.log'), out));
  30. const stop = () => { try { p.kill(); } catch {} };
  31. // a visitor: its own cookie jar
  32. const visitor = () => {
  33. const jar = {};
  34. const take = (r) => { for (const c of r.headers.getSetCookie()) { const [kv] = c.split(';'); const i = kv.indexOf('='); jar[kv.slice(0, i)] = kv.slice(i + 1); } };
  35. const cookie = () => Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ');
  36. const get = async (path, headers = {}) => { const r = await fetch(ID + path, { redirect: 'manual', headers: { cookie: cookie(), ...headers } }); take(r); return { status: r.status, location: r.headers.get('location'), text: await r.text() }; };
  37. const post = async (path, body, headers = {}) => { const r = await fetch(ID + path, { method: 'POST', redirect: 'manual', headers: { 'content-type': 'application/json', cookie: cookie(), ...headers }, body: JSON.stringify(body) }); take(r); return { status: r.status, text: await r.text() }; };
  38. let n = 0;
  39. const face = async (event, payload) => { const r = await post('/__hl/emit', { t: 'emit', i: ++n, event, payload }); try { const j = JSON.parse(r.text); return j.ok ? j.value : { transport: r.status, text: r.text.slice(0, 200) }; } catch { return { transport: r.status, text: r.text.slice(0, 200) }; } };
  40. return { get, post, face };
  41. };
  42. const sessions = () => readdirSync(sessDir).map(f => { try { return JSON.parse(readFileSync(join(sessDir, f), 'utf8')); } catch { return null; } }).filter(Boolean);
  43. const lastCode = (email) => { const l = readFileSync(mail, 'utf8').trim().split('\n').filter(x => x.startsWith(email + ' ')); return l.length ? l[l.length - 1].split(' ')[1] : null; };
  44. try {
  45. for (const end = Date.now() + Number(process.env.IDENT_COLD_MS || 120000); ; await sleep(250)) { try { await fetch(ID + '/', { redirect: 'manual' }); break; } catch { if (Date.now() > end) throw new Error('ident did not come up'); } }
  46. // ---- 1. the home page path ----------------------------------------------------------------------------------------------------
  47. const a = visitor();
  48. await a.get('/');
  49. const em = '[email protected]';
  50. const sent = await a.post('/api/code', { email: em });
  51. check('a code is mailed', sent.status === 200 && /^\d{6}$/.test(lastCode(em) || ''), sent.text);
  52. const rp = await a.face('rememberPending', [em]);
  53. check('rememberPending answers the address', rp.email === em, JSON.stringify(rp));
  54. check('PENDING STICKS: the session file holds the pending address', sessions().some(s => s.data && s.data.pendingEmail === em), JSON.stringify(sessions().map(s => s.data)));
  55. const cp = await a.get('/code');
  56. check('PENDING STICKS: /code shows the code step for the address (no redirect home)', cp.status === 200 && cp.text.includes(em), cp.status + ' ' + cp.location);
  57. const bad = await a.face('verifyCode', [em, lastCode(em) === '000000' ? '111111' : '000000', 'Europe/Vienna']);
  58. check('a wrong code does not sign in', !!bad.error, JSON.stringify(bad).slice(0, 120));
  59. const vc = await a.face('verifyCode', [em, lastCode(em), 'Europe/Vienna']);
  60. check('verifyCode signs in', vc.account && vc.account.email === em, JSON.stringify(vc).slice(0, 160));
  61. const acct = vc.account && vc.account.id;
  62. const mine = sessions().filter(s => s.user && s.user.id === acct);
  63. check('SIGN-IN STICKS: the session file carries the user (id, since, epoch)', mine.length === 1 && mine[0].user.since > 0 && mine[0].user.epoch === 0, JSON.stringify(sessions().map(s => s.user)));
  64. check('SIGN-IN STICKS: the pending address is cleared in the file', mine.length === 1 && mine[0].data.pendingEmail == null, JSON.stringify(mine[0] && mine[0].data));
  65. const reload = await a.get('/');
  66. check('RELOAD: the home page still shows the signed-in address', reload.status === 200 && reload.text.includes(em) && !reload.text.includes('id="emailform"'), String(reload.status));
  67. const cp2 = await a.get('/code');
  68. check('RELOAD: /code of a signed-in visitor goes back home', cp2.status === 302, cp2.status + ' ' + cp2.location);
  69. // ---- 2. forgetPending ---------------------------------------------------------------------------------------------------------
  70. const f = visitor();
  71. await f.get('/');
  72. const em2 = '[email protected]';
  73. await f.post('/api/code', { email: em2 });
  74. await f.face('rememberPending', [em2]);
  75. check('forgetPending setup: recorded', sessions().some(s => s.data && s.data.pendingEmail === em2));
  76. await f.face('forgetPending', []);
  77. check('FORGET STICKS: "Other address" clears the pending address in the file', !sessions().some(s => s.data && s.data.pendingEmail === em2), JSON.stringify(sessions().map(s => s.data)));
  78. // ---- 3. register an app (as the signed-in visitor a), then the embed path --------------------------------------------------------
  79. const ap = await a.face('appCreate', [{ name: 'sw app', origins: [ORIGIN] }]);
  80. const key = ap.app && ap.app.apiKey;
  81. check('an app is registered', /^pk_[0-9a-f]{32}$/.test(key || ''), JSON.stringify(ap).slice(0, 200));
  82. const e = visitor();
  83. const emb = await e.get('/embed/signin?key=' + key + '&return=' + encodeURIComponent(ORIGIN + '/callback'));
  84. check('/embed/signin answers 200', emb.status === 200, String(emb.status));
  85. const em3 = '[email protected]';
  86. await e.post('/api/code', { email: em3 });
  87. const ve = await e.face('verifyCode', [em3, lastCode(em3), 'Europe/Vienna']);
  88. check('verifyCode signs in', ve.account && ve.account.email === em3, JSON.stringify(ve).slice(0, 160));
  89. check('EMBED SIGN-IN STICKS: the session file carries the user', sessions().some(s => s.user && s.user.id === (ve.account && ve.account.id)), JSON.stringify(sessions().map(s => s.user)));
  90. // ---- 4. the selector: on a fresh request the cookie is still signed in, a choice gives a code -----------------------------------
  91. const H = { origin: ORIGIN };
  92. const ids = JSON.parse((await e.get('/api/selector/identities?key=' + key, H)).text);
  93. check('SELECTOR: the embed-signed-in cookie sees its identities', ids.signedIn === true && ids.identities.length >= 1, JSON.stringify(ids).slice(0, 200));
  94. const ch = JSON.parse((await e.post('/api/selector/choose?key=' + key, { identity: ids.identities[0].id }, H)).text);
  95. check('SELECTOR: choosing an identity gives a one-time code', typeof ch.code === 'string' && ch.code.length > 8, JSON.stringify(ch).slice(0, 200));
  96. const ids2 = JSON.parse((await e.get('/api/selector/identities?key=' + key, H)).text);
  97. check('SELECTOR: after the choice the visitor is still signed in', ids2.signedIn === true, JSON.stringify(ids2).slice(0, 120));
  98. const nobody = visitor();
  99. await nobody.get('/');
  100. const ids3 = JSON.parse((await nobody.get('/api/selector/identities?key=' + key, H)).text);
  101. check('SELECTOR: a visitor who never signed in is signed out', ids3.signedIn === false, JSON.stringify(ids3));
  102. } catch (err) {
  103. check('gate ran without an exception', false, String(err && err.stack || err));
  104. } finally {
  105. stop();
  106. }
  107. console.log(`\nsessionwrites: ${passed} passed, ${failed} failed`);
  108. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • 0f6d1592Merge branch 'f18b-shell-session' into mainIdent
  • 19868218|||PR ident#39 shell reads its session member instead of a cross-file emitmre
  • 5d1b3fedMerge branch 'v61-day61' into mainIdent
  • 83faeb15|||PR ident: vendor Hybriel day61mre
  • b2572b34Merge branch 'v59-day59' into mainIdent
  • 67cf016d|||PR ident: vendor Hybriel day59mre
  • 600c043dMerge branch 'v58-day58' into mainIdent
  • 365f8c80|||PR ident: vendor Hybriel day58mre
  • 585126e5Merge branch 'f16-setf' into mainIdent
  • 953bf03a|||PR ident setF mirror dropped (hybriel#370)mre
  • a1419d9cMerge branch 'f15-navigate' into mainIdent
  • 3b3e451f|||PR ident#36 navigate to the app instead of location.assignmre
  • e36f4516Merge branch 'f14-online' into mainIdent
  • 2c5eac91|||PR ident#38 online state without probe timermre
  • bf1980f2Merge branch 'v56-day56' into mainIdent
  • 62ae0adf|||PR ident: vendor Hybriel day56mre
  • 0d18abc4Merge branch 'f13-avatar' into mainIdent
  • 2a99730a|||PR ident#37 avatar in hlmre
  • fa4ed25bMerge branch 'f11-upsert' into mainIdent
  • 8f3d9bc9|||PR ident#42 keyed upsert and removemre