ident
All repositories: gitoria
9.5 KB
// tests/sessionwrites.mjs — GATE A28G: the functions of lib/login.hl and lib/api.hl that take the session as an &-parameter must really// 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// vanish silently. This gate looks at the SESSION FILES on disk and at what the next request sees, over plain HTTP (no browser):// 1. home path: the pending address is recorded (rememberPending), the /code page shows the code step, verifyCode signs the session in// (user in the file, pendingEmail cleared), a reload (new request, same cookie) is still signed in, /code then redirects away.// 2. forgetPending clears a recorded address in the file.// 3. embed path: a second visitor signs in through /embed/signin + verifyCode; the session file carries the user.// 4. selector: the signed-in cookie sees its identities and a choice gives a code, again on a fresh request.// Own server (NEVER the dev server, NEVER real mail): ident on SESSIONWRITES_PORT (default 8700), storage .scratch/sessionwrites-gate (wiped at start).// Run: node tests/sessionwrites.mjs (SESSIONWRITES_APP=<checkout> runs it against that code)import { spawn } from 'node:child_process';import { readFileSync, readdirSync, rmSync, mkdirSync, writeFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';const APP = process.env.SESSIONWRITES_APP || join(dirname(fileURLToPath(import.meta.url)), '..');const G = join(APP, '.scratch/sessionwrites-gate');const PORT = Number(process.env.SESSIONWRITES_PORT || 8700);const ID = 'http://127.0.0.1:' + PORT;const ORIGIN = 'http://127.0.0.1:' + (PORT + 1); // the origin registered for the app (nothing listens there; only the Origin header matters)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 ? ' — ' + detail : '')); } };rmSync(G, { recursive: true, force: true });mkdirSync(G, { recursive: true });const sessDir = join(G, 'sess');const mail = join(G, 'mail.txt');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'] });let out = ''; p.stdout.on('data', d => { out += d; }); p.stderr.on('data', d => { out += d; });p.on('exit', () => writeFileSync(join(G, 'ident.log'), out));const stop = () => { try { p.kill(); } catch {} };// a visitor: its own cookie jarconst visitor = () => {const jar = {};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); } };const cookie = () => Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ');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() }; };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() }; };let n = 0;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) }; } };return { get, post, face };};const sessions = () => readdirSync(sessDir).map(f => { try { return JSON.parse(readFileSync(join(sessDir, f), 'utf8')); } catch { return null; } }).filter(Boolean);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; };try {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'); } }// ---- 1. the home page path ----------------------------------------------------------------------------------------------------const a = visitor();await a.get('/');const em = '[email protected]';const sent = await a.post('/api/code', { email: em });check('a code is mailed', sent.status === 200 && /^\d{6}$/.test(lastCode(em) || ''), sent.text);const rp = await a.face('rememberPending', [em]);check('rememberPending answers the address', rp.email === em, JSON.stringify(rp));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)));const cp = await a.get('/code');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);const bad = await a.face('verifyCode', [em, lastCode(em) === '000000' ? '111111' : '000000', 'Europe/Vienna']);check('a wrong code does not sign in', !!bad.error, JSON.stringify(bad).slice(0, 120));const vc = await a.face('verifyCode', [em, lastCode(em), 'Europe/Vienna']);check('verifyCode signs in', vc.account && vc.account.email === em, JSON.stringify(vc).slice(0, 160));const acct = vc.account && vc.account.id;const mine = sessions().filter(s => s.user && s.user.id === acct);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)));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));const reload = await a.get('/');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));const cp2 = await a.get('/code');check('RELOAD: /code of a signed-in visitor goes back home', cp2.status === 302, cp2.status + ' ' + cp2.location);// ---- 2. forgetPending ---------------------------------------------------------------------------------------------------------const f = visitor();await f.get('/');const em2 = '[email protected]';await f.post('/api/code', { email: em2 });await f.face('rememberPending', [em2]);check('forgetPending setup: recorded', sessions().some(s => s.data && s.data.pendingEmail === em2));await f.face('forgetPending', []);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)));// ---- 3. register an app (as the signed-in visitor a), then the embed path --------------------------------------------------------const ap = await a.face('appCreate', [{ name: 'sw app', origins: [ORIGIN] }]);const key = ap.app && ap.app.apiKey;check('an app is registered', /^pk_[0-9a-f]{32}$/.test(key || ''), JSON.stringify(ap).slice(0, 200));const e = visitor();const emb = await e.get('/embed/signin?key=' + key + '&return=' + encodeURIComponent(ORIGIN + '/callback'));check('/embed/signin answers 200', emb.status === 200, String(emb.status));const em3 = '[email protected]';await e.post('/api/code', { email: em3 });const ve = await e.face('verifyCode', [em3, lastCode(em3), 'Europe/Vienna']);check('verifyCode signs in', ve.account && ve.account.email === em3, JSON.stringify(ve).slice(0, 160));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)));// ---- 4. the selector: on a fresh request the cookie is still signed in, a choice gives a code -----------------------------------const H = { origin: ORIGIN };const ids = JSON.parse((await e.get('/api/selector/identities?key=' + key, H)).text);check('SELECTOR: the embed-signed-in cookie sees its identities', ids.signedIn === true && ids.identities.length >= 1, JSON.stringify(ids).slice(0, 200));const ch = JSON.parse((await e.post('/api/selector/choose?key=' + key, { identity: ids.identities[0].id }, H)).text);check('SELECTOR: choosing an identity gives a one-time code', typeof ch.code === 'string' && ch.code.length > 8, JSON.stringify(ch).slice(0, 200));const ids2 = JSON.parse((await e.get('/api/selector/identities?key=' + key, H)).text);check('SELECTOR: after the choice the visitor is still signed in', ids2.signedIn === true, JSON.stringify(ids2).slice(0, 120));const nobody = visitor();await nobody.get('/');const ids3 = JSON.parse((await nobody.get('/api/selector/identities?key=' + key, H)).text);check('SELECTOR: a visitor who never signed in is signed out', ids3.signedIn === false, JSON.stringify(ids3));} catch (err) {check('gate ran without an exception', false, String(err && err.stack || err));} finally {stop();}console.log(`\nsessionwrites: ${passed} passed, ${failed} failed`);process.exit(failed ? 1 : 0);
Branches
Latest commits
- 8370b748ident#33: the app request box moves into home.hl's Stylemre
- 40bf3b97ident#33: the 404 page's home link rule moves into notfound.hlmre
- 40627a89ident#33: the time zone section's spacing moves into timezone.hlmre
- d389db08ident#33: the identity page's rules and the Notif. chip move into identity.hl's Stylemre
- ddda0b5bident#33: the identity row's parts move into identitylist.hl's Stylemre
- 47e516afident#33 ident#34: the identity form's avatar rules move into identityform.hl; the preview and Remove button are hidden with the hidden attribute instead of built class strings (avatarPreviewClass, avatarRemoveClass gone)mre
- 5cb5cf0eident#33: the code field's look moves into codestep.hl's Stylemre
- f421cd60ident#33: the shell's own rules (user menu address, offline note, network probe) move into main.hl's Stylemre
- c512fb96Merge branch 'f4-homesplit' into mainIdent
- 07d1717c|||PR ident#40 home.hl is split into components, one per area: email step, identity form, identity list, app identity choice, time zone; each moves its faces with it, the email step is shared with embed.hl (#40.3, rest of #40.2)mre
- 59e8fcc1ident#40.3: the app's identity choice is one component (components/chooseidentity.hl); its face chooseIdentity moves with itmre
- e23efdfcident#40.3: the identity list is one component (components/identitylist.hl); its delete and face dropIdentity move with itmre
- e24b59a6ident#40.3: the time zone is one component (components/timezone.hl); its face changeTimeZone moves with itmre
- 8cbc5717ident#40.3: the email step is one component (components/emailstep.hl) placed by home.hl and embed.hlmre
- 6fad3bd2Merge branch 'f3-codestep' into mainIdent
- 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