ident
All repositories: gitoria
6.3 KB
// tests/cookie.mjs — GATE of ident#28 (F28F): a session whose browser cookie was issued before the 99-year change (issuedAt 0,// the old 14-day life) gets the 99-year cookie again on its next request: on a selector endpoint, on a page, signed in and anonymous,// with the same id, and stays signed in. A request with no cookie gets no cookie (lazy sessions). HTTP only, own server (P0, default 8781).import { spawn } from 'node:child_process';import { readFileSync, writeFileSync, rmSync, mkdirSync, existsSync } from 'node:fs';import { createHash } from 'node:crypto';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';const APP = join(dirname(fileURLToPath(import.meta.url)), '..');const G = join(APP, '.scratch/cookie-gate');const P0 = Number(process.env.COOKIE_GATE_PORT || 8781);const BASE = 'http://127.0.0.1:' + P0;const J = JSON.stringify;const sleep = (ms) => new Promise((r) => setTimeout(r, ms));let passed = 0, failed = 0;const check = (name, ok, detail = '') => { if (ok) { passed++; console.log(' ok ' + name); } else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + String(detail).slice(0, 300) : '')); } };rmSync(G, { recursive: true, force: true }); mkdirSync(join(G, 'sess'), { recursive: true });let out = '';const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, env: { ...process.env, HL_HOST: '127.0.0.1', SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', IDENT_WATCH: '0', IDENT_PORT: String(P0), IDENT_STORAGE: join(G, 'store'), IDENT_SESSIONS: join(G, 'sess'), IDENT_MAIL_SINK: join(G, 'mail.txt'), IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000' }, stdio: ['ignore', 'pipe', 'pipe'] });p.stdout.on('data', (d) => { out += d; }); p.stderr.on('data', (d) => { out += d; });p.on('exit', () => writeFileSync(join(G, 'ident.log'), out));process.on('exit', () => { try { p.kill('SIGTERM'); } catch {} });let up = false; for (let i = 0; i < 480 && !up; i++) { try { await fetch(BASE + '/api/online'); up = true; } catch { await sleep(250); } }if (!up) { console.log('FAIL server did not start'); process.exit(1); }async function emit(cookie, event, payload) {const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: 1, event, payload }) });const sc = r.headers.get('set-cookie'); let j = null; try { j = await r.json(); } catch {}return { v: j && j.value !== undefined ? j.value : j, cookie: sc ? sc.split(';')[0] : null };}async function signIn(email) {const sink = join(G, 'mail.txt');await fetch(BASE + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email }) });let code = null;for (let i = 0; i < 50 && !code; i++) { if (existsSync(sink)) { const l = readFileSync(sink, 'utf8').split('\n').filter((x) => x.startsWith(email + ' ')); if (l.length) code = l.at(-1).split(' ')[1]; } await sleep(100); }return (await emit(null, 'verifyCode', [email, code, 'UTC'])).cookie;}const idOf = (c) => /identsid=([0-9a-f]+)/.exec(c)[1];const file = (id) => join(G, 'sess', createHash('sha256').update(id).digest('hex'));const edit = (id, f) => { const j = JSON.parse(readFileSync(file(id), 'utf8')); f(j); writeFileSync(file(id), J(j)); return j; };const KEY = 'ignored';// an app so the selector endpoint answers: sign in, create an appconst alice = await signIn('[email protected]');const app = (await emit(alice, 'appCreate', [{ name: 'GateApp', origins: ['http://127.0.0.1:' + (P0 + 5)] }])).v;const key = app.app.apiKey, origin = 'http://127.0.0.1:' + (P0 + 5);// an anonymous session with content: a sign-in code asked for makes oneawait fetch(BASE + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email: '[email protected]' }) });const anonRes = await emit(null, 'rememberPending', ['[email protected]']);const anonCookie = anonRes.cookie || '';check('setup: an anonymous session with a cookie exists (pending address remembered)', /identsid=/.test(anonCookie), J(anonRes.v));const signedId = idOf(alice), anonId = anonCookie ? idOf(anonCookie) : null;const age = (sc) => { const m = /Max-Age=(\d+)/.exec(sc || ''); return m ? Number(m[1]) : null; };const ask = async (path, cookie, headers = {}) => { const r = await fetch(BASE + path, { redirect: 'manual', headers: { cookie, ...headers } }); await r.text(); return r.headers.getSetCookie(); };const old = (id) => edit(id, (j) => { j.issuedSig = ''; j.issuedAt = 0; }); // what a session has whose cookie went out before the changefor (const [who, id, cookie] of [['signed in', signedId, alice], ['anonymous', anonId, anonCookie]]) {old(id);let c = await ask('/api/selector/identities?key=' + key, cookie, { origin });check(who + ': an old cookie on the selector endpoint gets Set-Cookie with the same id and Max-Age 99 years', c.length === 1 && c[0].startsWith('identsid=' + id + ';') && age(c[0]) === 3122064000, J(c));check(who + ': the session file records the issue now', edit(id, () => {}).issuedAt > 0);c = await ask('/api/selector/identities?key=' + key, cookie, { origin });check(who + ': the next selector request sets none', c.length === 0, J(c));old(id);c = await ask('/start', cookie);check(who + ': an old cookie on a page gets the 99-year cookie, same id', c.length === 1 && c[0].startsWith('identsid=' + id + ';') && age(c[0]) === 3122064000, J(c));old(id);c = await ask('/api/online', cookie);check(who + ': an old cookie on another function route (/api/online) gets it too', c.length === 1 && c[0].startsWith('identsid=' + id + ';') && age(c[0]) === 3122064000, J(c));}const still = await (await fetch(BASE + '/api/selector/identities?key=' + key, { headers: { cookie: alice, origin } })).json();check('the signed-in session is still signed in after the re-issue', still.signedIn === true, J(still));const none = await fetch(BASE + '/api/selector/identities?key=' + key, { headers: { origin } }); await none.text();check('a selector request with no cookie gets no cookie', none.headers.getSetCookie().length === 0, J(none.headers.getSetCookie()));const nonePage = await fetch(BASE + '/start'); await nonePage.text();check('a page request with no cookie gets no cookie (lazy sessions)', nonePage.headers.getSetCookie().length === 0, J(nonePage.headers.getSetCookie()));console.log(`cookie gate: ${passed} passed, ${failed} failed`);process.exit(failed ? 1 : 0);
Branches
Latest commits
- 51e387f2|||PR ident#40 the code step is one component (components/codestep.hl) placed by home.hl and embed.hl; its verify face, setCode, browserZone and verify call exist once (#40.2)mre
- c28bddeeMerge branch 'f2-shell' into mainIdent
- c3a40ff6|||PR ident#40 one shell for the app and /start (account part off on /start, #40.1); startshell.hl removed; unused signOut faces gone (#40.4)mre
- 060f3870ident#40.4: use the shell sign-out faces in regression gatesmre
- 9b94aa6aMerge branch 'f1b-cleanup' into mainIdent
- edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
- 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre
- c7eef14aMerge branch 'nv1-navigate' into mainIdent
- 644f9775|||PR ident#36 navigate() instead of window.location in the shell, start shell and homemre
- 4ca2f921deploy.sh: tar --hard-dereference so backups hold no hard linksmre
- 23971fb7ident#49: media queries in the language's @media formmre
- 73f4f97dident: re-vendor to hybriel day38b (mpackdb store-open fix)mre
- aa056c03ident: a startup error prints its message before exit 1 (hybriel#247)mre
- ee37a861ident#G48: gitoria's registration gets the wildcard origin of its repo addresses at load (gate tests/gitoria-origin.mjs)mre
- dc6d486fident#27: the docs gate expects the new Access entry in the main menumre
- d277633cident#27: README: identity access and the introspect endpointmre
- e999b0d3ident#27: the Access tab — one key per identity for all its apps: give access in three steps, the overview matrix, a cell's sheet (since, last use, level, rotate, revoke), the app's check POST /api/introspect, agent identities hidden from the login picker, an inbox icon in the header's icon style (gate: tests/access.mjs)mre
- 436206fcident#47: deploy.sh runs the sign-in gate on the deploy's own port slot, like the sessionwrites and docs gates (the default 8700 can be taken by another process)mre
- a4887ea3ident#47: the selector's sign-in frame no longer has a Continue button; the identity row itself is the link (gate tests/signin.mjs fails on the old code)mre
- d8ec703dident#45: /docs shows docs/IDENT.md (hl:markdown, vendored from ac1ed9da), one Docs entry in the main menu, README for developers only, gates tests/docs.mjs and tests/sessionwrites.mjs in deploy.shmre