ident
All repositories: gitoria
27.6 KB
// tests/security.mjs — SECURITY GATE (mission SI, 2026-10-23): the authorisation matrix of every face / API / page, injection,// header, cookie, upload and limit checks of the security audit (reports/SI-sec.md). HTTP only, no Chrome.// Checks marked [fix] FAIL on the code before the audit; the others are regression checks of what was already right.// Own servers (.scratch/security-gate, wiped at start; SECURITY_GATE_PORT = P0, default 8725; uses P0..P0+2, the fixture app origin never listens):// main P0 http, caps lowered (IDENT_MAX_APPS=3, IDENT_MAX_IDENTITIES=3), per-IP limits off// https P0+1 IDENT_PUBLIC_URL=https://ident.test (the cookie must be Secure + __Host-)// limit P0+2 default limits (per address 3 / 10 min, per IP 10 / 10 min)import { spawn } from 'node:child_process';import { readFileSync, writeFileSync, rmSync, mkdirSync, existsSync } from 'node:fs';import net from 'node:net';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';const APP = join(dirname(fileURLToPath(import.meta.url)), '..');const G = join(APP, '.scratch/security-gate');const BIN = join(APP, 'bin/hybriel');const P0 = Number(process.env.SECURITY_GATE_PORT || 8725);const MAIN = 'http://127.0.0.1:' + P0, HTTPS = 'http://127.0.0.1:' + (P0 + 1), LIMIT = 'http://127.0.0.1:' + (P0 + 2);const AO = 'http://127.0.0.1:' + (P0 + 5); // the fixture app's origin (never listens)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) : '')); } };const note = (s) => console.log(' note ' + s);rmSync(G, { recursive: true, force: true });for (const n of ['main', 'https', 'limit']) mkdirSync(join(G, n + '-sess'), { recursive: true });const procs = [];function start(name, port, env) {let out = '';const p = spawn(BIN, ['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(port), IDENT_STORAGE: join(G, name + '-store'), IDENT_SESSIONS: join(G, name + '-sess'), IDENT_MAIL_SINK: join(G, name + '-mail.txt'), ...env }, stdio: ['ignore', 'pipe', 'pipe'] });p.stdout.on('data', (d) => { out += d; }); p.stderr.on('data', (d) => { out += d; });p.on('exit', () => writeFileSync(join(G, name + '.log'), out));procs.push(p);}const stopAll = () => { for (const p of procs) { try { p.kill('SIGTERM'); } catch {} } };process.on('exit', stopAll);start('main', P0, { IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000', IDENT_MAX_APPS: '3', IDENT_MAX_IDENTITIES: '3', IDENT_PUBLIC_URL: MAIN });start('https', P0 + 1, { IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000', IDENT_PUBLIC_URL: 'https://ident.test' });start('limit', P0 + 2, {});for (const u of [MAIN, HTTPS, LIMIT]) { let up = false; for (let i = 0; i < 480 && !up; i++) { try { await fetch(u + '/api/online'); up = true; } catch { await sleep(250); } } if (!up) { console.log('FAIL server ' + u + ' did not start'); process.exit(1); } }// ---- helpers ---------------------------------------------------------------------------------const sinkOf = (base) => join(G, (base === MAIN ? 'main' : base === HTTPS ? 'https' : 'limit') + '-mail.txt');async function emit(base, cookie, event, payload, headers = {}) {const r = await fetch(base + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}), ...headers }, 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 { status: r.status, v: j && j.value !== undefined ? j.value : j, cookie: sc ? sc.split(';')[0] : null, setCookie: sc };}async function post(base, path, body, headers = {}) {const r = await fetch(base + path, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: typeof body === 'string' ? body : J(body) });const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}return { status: r.status, j, t, h: r.headers };}async function get(base, path, cookie, headers = {}) {const r = await fetch(base + path, { redirect: 'manual', headers: { ...(cookie ? { cookie } : {}), ...headers } });return { status: r.status, t: await r.text(), h: r.headers };}async function signIn(base, email) {const sink = sinkOf(base);const count = () => existsSync(sink) ? readFileSync(sink, 'utf8').split('\n').filter((x) => x.startsWith(email + ' ')).length : 0;const before = count();await post(base, '/api/code', { email });let code = null;for (let i = 0; i < 50; i++) { if (count() > before) { code = readFileSync(sink, 'utf8').split('\n').filter((x) => x.startsWith(email + ' ')).at(-1).split(' ')[1]; break; } await sleep(100); }const r = await emit(base, null, 'verifyCode', [email, code, 'UTC']);return { cookie: r.cookie, setCookie: r.setCookie, account: r.v && r.v.account, identities: r.v && r.v.identities };}const errOf = (v) => v != null && v.error != null;// ================================================================================================console.log('# 1. authorisation: every face, signed out and as another user (the owner data must not move)');const alice = await signIn(MAIN, '[email protected]'), bob = await signIn(MAIN, '[email protected]');const aid = alice.identities[0].id;const app = (await emit(MAIN, alice.cookie, 'appCreate', [{ name: 'AliceApp', origins: [AO] }])).v;const key = app.app.apiKey, secret = app.secret, appId = app.app.id;const lr = await get(MAIN, '/login?key=' + key + '&return=' + encodeURIComponent(AO + '/cb'));const rid = lr.h.get('location').split('/').pop();const ch = (await emit(MAIN, alice.cookie, 'chooseIdentity', [rid, aid])).v;const ex = await post(MAIN, '/api/exchange', { key, secret, code: ch.url.split('ident_code=')[1] });const short = ex.j && ex.j.identity;check('setup: alice has an app, a connection and a short id', short != null && ex.status === 200, J(ex.j));const nf = await post(MAIN, '/api/notify', { key, secret, identity: short, name: 'Hello', text: 'hi there' });const nid = nf.j && nf.j.id;const idp = (await get(MAIN, '/identity/' + aid, alice.cookie)).t;const connId = (idp.match(/\/inbox\/([a-z0-9]{8,})/) || [])[1];check('setup: a notification and a connection id', nid != null && connId != null, J(nf.j) + connId);const faces = [['editIdentity', [aid, { identityName: 'pwned' }]], ['dropIdentity', [aid]], ['chooseIdentity', [rid, aid]],['appUpdate', [appId, { name: 'pwned', origins: ['http://evil.example'] }]], ['appNewSecret', [appId]], ['appDelete', [appId]],['inboxMark', [nid, true]], ['inboxSwitch', [connId, 'Hello', 'email', false]], ['inboxOverride', [connId, 'active', true]], ['inboxDisconnect', [connId]],];const signedOutOnly = [['addIdentity', [{ identityName: 'x' }]], ['changeTimeZone', ['Asia/Tokyo']], ['appCreate', [{ name: 'X', origins: ['http://a.example'] }]], ['shellSignOutAllNow', []]];for (const [who, cookie, list] of [['signed out', null, [...faces, ...signedOutOnly]], ['another user', bob.cookie, faces]]) {const bad = [];for (const [ev, pl] of list) { const r = await emit(MAIN, cookie, ev, pl); if (!errOf(r.v)) bad.push(ev + ' → ' + J(r.v).slice(0, 80)); }check(`${who}: all ${list.length} faces refuse (no data of alice reachable)`, bad.length === 0, bad.join(' | '));}const still = await emit(MAIN, alice.cookie, 'editIdentity', [aid, { identityName: 'AliceName' }]);check('alice\'s identity, app and connection survived every attack', !errOf(still.v) && (await get(MAIN, '/apps', alice.cookie)).t.includes('AliceApp') && !(await get(MAIN, '/apps', alice.cookie)).t.includes('evil.example') && (await post(MAIN, '/api/notify', { key, secret, identity: short, name: 'Hello', text: 'again' })).status === 200);// pagesconst leaks = [];for (const p of ['/', '/apps', '/inbox', '/inbox/' + connId, '/identity/' + aid, '/code']) {for (const [who, cookie] of [['signed out', null], ['bob', bob.cookie]]) {const t = (await get(MAIN, p, cookie)).t;for (const s of ['[email protected]', 'AliceApp', 'AliceName', short, 'hi there', key]) { if (t.includes(s)) leaks.push(`${p} as ${who} holds ${s === short ? '<short id>' : s}`); }}}check('no page leaks alice\'s email, names, app, short id, notification or key to a signed-out visitor or to bob', leaks.length === 0, leaks.join(' | '));// the app APIconst bobApp = (await emit(MAIN, bob.cookie, 'appCreate', [{ name: 'BobApp', origins: [AO.replace(String(P0 + 5), String(P0 + 6))] }])).v;const wrong = [];for (const [path, body] of [['/api/exchange', { key, secret: bobApp.secret, code: 'x' }], ['/api/migrate-ids', { key, secret: bobApp.secret }], ['/api/kinds', { key, secret: bobApp.secret, kinds: [] }], ['/api/notify', { key, secret: bobApp.secret, identity: short, name: 'n', text: 't' }], ['/api/invites', { key, secret: bobApp.secret, project: 'p', role: 'r', return: AO + '/x' }], ['/api/invites/list', { key, secret: bobApp.secret }], ['/api/exchange', { key: 'pk_nope', secret, code: 'x' }]]) {const r = await post(MAIN, path, body); if (r.status !== 401) wrong.push(path + ' → ' + r.status);}check('another app\'s secret (or an unknown key) is 401 on every key + secret route', wrong.length === 0, wrong.join(' | '));const spam = await post(MAIN, '/api/notify', { key: bobApp.app.apiKey, secret: bobApp.secret, identity: short, name: 'n', text: 'spam' });check('an app cannot notify an identity that is not connected to it (404)', spam.status === 404, spam.status);const inv = await post(MAIN, '/api/invites', { key, secret, project: 'p', role: 'r', return: AO + '/x' });const o = { key: bobApp.app.apiKey, secret: bobApp.secret };check('another app cannot get, revoke or list alice\'s invite', (await post(MAIN, '/api/invites/get', { ...o, id: inv.j.id })).status === 404 && (await post(MAIN, '/api/invites/revoke', { ...o, id: inv.j.id })).status === 404 && (await post(MAIN, '/api/invites/list', o)).j.invites.length === 0);check('every /api/* route answers GET with 405/400, never data', (await Promise.all(['/api/exchange', '/api/migrate-ids', '/api/kinds', '/api/notify', '/api/invites', '/api/invites/list', '/api/invites/get', '/api/invites/revoke', '/api/code'].map((p) => get(MAIN, p)))).every((r) => r.status === 405));// the selector (CORS + cookie)const sel = async (origin, k, cookie, method = 'GET', body) => { const r = await fetch(MAIN + '/api/selector/' + (method === 'GET' ? 'identities' : 'choose') + '?key=' + k, { method, headers: { ...(origin ? { origin } : {}), ...(cookie ? { cookie } : {}), 'content-type': 'application/json' }, body }); return { status: r.status, acao: r.headers.get('access-control-allow-origin'), t: await r.text(), nosniff: r.headers.get('x-content-type-options') }; };const s1 = await sel(null, key, alice.cookie), s2 = await sel('http://evil.example', key, alice.cookie), s3 = await sel(AO, key, bob.cookie), s4 = await sel(AO, key, alice.cookie);check('selector: no Origin and an unregistered Origin are 403 without CORS headers', s1.status === 403 && s1.acao == null && s2.status === 403 && s2.acao == null);check('selector: bob\'s cookie sees none of alice\'s identities; alice\'s sees hers, only for the registered origin', !s3.t.includes('AliceName') && !s3.t.includes(JSON.parse(s4.t).identities[0].id) && s4.status === 200 && s4.acao === AO && s4.t.includes('AliceName'), J([s3, s4]));const pick = JSON.parse(s4.t).identities[0].id;check('selector choose: evil origin 403, no cookie 401, bob with alice\'s pick 400, alice 200', (await sel('http://evil.example', key, alice.cookie, 'POST', J({ identity: pick }))).status === 403 && (await sel(AO, key, null, 'POST', J({ identity: pick }))).status === 401 && (await sel(AO, key, bob.cookie, 'POST', J({ identity: pick }))).status === 400 && (await sel(AO, key, alice.cookie, 'POST', J({ identity: pick }))).status === 200, J(pick));check('[fix] selector answers carry X-Content-Type-Options: nosniff', s4.nosniff === 'nosniff' && s2.nosniff === 'nosniff', J([s4.nosniff, s2.nosniff]));// a forged session argument (hybriel#16)const forged = await emit(MAIN, bob.cookie, 'editIdentity', [aid, { identityName: 'pwned' }, { user: { id: alice.account.id } }]);const after = (await get(MAIN, '/identity/' + aid, alice.cookie)).t;check('a forged trailing `session` argument changes nothing (refused by hl:web, hybriel#16)', !after.includes('pwned'), J(forged.v));console.log('# 2. injection, redirects, paths');const X = '</script><script>window.PWNED=1</script><img src=x onerror=alert(1)>"\'&';const inj = await signIn(MAIN, '[email protected]');await emit(MAIN, inj.cookie, 'editIdentity', [inj.identities[0].id, { identityName: X.slice(0, 60), nickname: '</ScRiPt >', firstname: '<!--' }]);const iapp = (await emit(MAIN, inj.cookie, 'appCreate', [{ name: X.slice(0, 60), origins: [AO] }])).v;const l2 = await get(MAIN, '/login?key=' + iapp.app.apiKey + '&return=' + encodeURIComponent(AO + '/cb')); const rid2 = l2.h.get('location').split('/').pop();const c2 = (await emit(MAIN, inj.cookie, 'chooseIdentity', [rid2, inj.identities[0].id])).v;const sh2 = (await post(MAIN, '/api/exchange', { key: iapp.app.apiKey, secret: iapp.secret, code: c2.url.split('ident_code=')[1] })).j.identity;await post(MAIN, '/api/notify', { key: iapp.app.apiKey, secret: iapp.secret, identity: sh2, name: X.slice(0, 60), text: X, link: 'https://example.com/a?b=1&c=(2)' });const l3 = await get(MAIN, '/login?key=' + iapp.app.apiKey + '&return=' + encodeURIComponent(AO + '/cb')); const rid3 = l3.h.get('location').split('/').pop();const bad = [];for (const p of ['/', '/apps', '/inbox', '/identity/' + inj.identities[0].id, '/signin/' + rid3]) {const t = (await get(MAIN, p, inj.cookie)).t;if (t.includes('</script><script>window.PWNED') || t.includes('<script>window.PWNED') || /<img src=x onerror/i.test(t)) bad.push(p);if ((t.match(/<script[ >]/g) || []).length !== (t.match(/<\/script>/gi) || []).length) bad.push(p + ' (unbalanced script tags)');}check('user text (names, app name, notification, markup like </script>) is escaped in every page and seed', bad.length === 0, bad.join(' | '));const errs = [(await get(MAIN, '/login?key=' + encodeURIComponent('<b>x</b>') + '&return=x')).t, (await get(MAIN, '/login?key=' + key + '&return=' + encodeURIComponent(AO + '"><script>x</script>'))).t, (await get(MAIN, '/invite/' + encodeURIComponent('<script>'))).t];// Hybriel #349 adds its early-submit holder to framework error pages too.// Exclude only that exact script from a clean page; injected scripts still fail.const frameworkSubmit = ((await get(MAIN, '/')).t.match(/<script>\{const q=\[\];document\.__hlSubmits=q;[\s\S]*?<\/script>/) || [])[0] || '';const errorMarkupSafe = (t) => {const markup = frameworkSubmit ? t.replace(frameworkSubmit, '') : t;return !markup.includes('<b>x</b>') && !markup.includes('<script>x') && !markup.includes('<script>');};check('the HTML error pages escape what the request sent', errs.every(errorMarkupSafe) && !errorMarkupSafe(frameworkSubmit + '<script>x</script>'));const ret = [];for (const ru of ['http://evil.example/x', AO + '@evil.example/', AO + '.evil.example/', 'javascript:alert(1)', AO + '\\@evil.example', '//evil.example', AO + '/#x', 'data:text/html,x']) {const r = await get(MAIN, '/login?key=' + key + '&return=' + encodeURIComponent(ru)); if (r.status !== 400) ret.push(ru + ' → ' + r.status + ' ' + r.h.get('location'));}check('a return URL outside the app\'s origins (userinfo, suffix, backslash, scheme, protocol-relative, fragment) is an error page, never a redirect', ret.length === 0, ret.join(' | '));const nl = [];for (const [f, v] of [['link', 'javascript:alert(1)'], ['link', 'JaVaScRiPt:alert(1)'], ['icon', 'data:text/html,<script>alert(1)</script>'], ['link', 'https://x.example/"onmouseover="alert(1)']]) {const r = await post(MAIN, '/api/notify', { key, secret, identity: short, name: 'n', text: 't', [f]: v }); if (r.status !== 400) nl.push(f + ' ' + v + ' → ' + r.status);}check('a notification link / icon is http(s) only, no quotes', nl.length === 0, nl.join(' | '));const av = [];for (const a of ['data:image/svg+xml;base64,PHN2Zz4=', 'data:text/html;base64,PHNjcmlwdD4=', 'javascript:alert(1)', 'data:image/png;base64,iVBORw0KGgo"onerror="x', 'data:image/png;base64,AAAA']) { const r = await emit(MAIN, inj.cookie, 'editIdentity', [inj.identities[0].id, { avatar: a }]); if (!errOf(r.v)) av.push(a.slice(0, 30)); }check('an avatar must be a real png / jpeg / webp data URL (no svg, html, quotes)', av.length === 0, av.join(' | '));const trav = [];for (const p of ['/.env', '/icons/../.env', '/icons/%2e%2e/.env', '/icons/..%2f.env', '/project.hl', '/lib/api.hl', '/storage/mpackdb/accounts.db', '/.sessions/', '/server.log', '/%2e%2e/%2e%2e/etc/passwd', '/README.md']) {const r = await new Promise((res) => { const s = net.connect(P0, '127.0.0.1', () => s.write(`GET ${p} HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n`)); let d = ''; s.on('data', (c) => { d += c; }); s.on('close', () => res(d)); });if (!/^HTTP\/1.1 404/.test(r) || /root:|SMTP_|PASSWORD/.test(r)) trav.push(p + ' → ' + r.split('\r\n')[0]);}check('no file outside the route table is served (.env, sources, storage, sessions, ../ and %2e%2e forms: 404)', trav.length === 0, trav.join(' | '));const hdr = await post(MAIN, '/api/code', { email: '[email protected]\r\nBcc: [email protected]' });check('an address with CR/LF is refused (no header injection into the mail)', hdr.status === 400, hdr.status);console.log('# 3. headers');const hs = {};for (const [n, p] of [['json', '/api/kinds'], ['err', '/login'], ['redirect', '/login?key=' + key + '&return=' + encodeURIComponent(AO + '/cb')], ['404', '/nothing-here'], ['js', '/selector.js'], ['ico', '/favicon.ico'], ['svg', '/icons/icon.svg'], ['online', '/api/online']]) hs[n] = await get(MAIN, p);check('[fix] function-route answers (JSON, error page, redirect, 204) carry X-Content-Type-Options: nosniff', ['json', 'err', 'redirect', 'online'].every((n) => hs[n].h.get('x-content-type-options') === 'nosniff'), J(['json', 'err', 'redirect', 'online'].map((n) => hs[n].h.get('x-content-type-options'))));check('[fix] static files (selector.js, favicon, icons) carry nosniff', ['js', 'ico', 'svg'].every((n) => hs[n].h.get('x-content-type-options') === 'nosniff'));check('[fix] JSON answers: Referrer-Policy no-referrer, X-Frame-Options DENY, CSP default-src none + frame-ancestors none', hs.json.h.get('referrer-policy') === 'no-referrer' && hs.json.h.get('x-frame-options') === 'DENY' && /default-src 'none'/.test(hs.json.h.get('content-security-policy') || '') && /frame-ancestors 'none'/.test(hs.json.h.get('content-security-policy') || ''));check('[fix] the HTML error page: CSP without script, X-Frame-Options DENY', hs.err.h.get('x-frame-options') === 'DENY' && /default-src 'none'/.test(hs.err.h.get('content-security-policy') || '') && !/script-src/.test(hs.err.h.get('content-security-policy') || ''));check('[fix] the 404 page (srv.page): nosniff, X-Frame-Options DENY, frame-ancestors none, Referrer-Policy', hs['404'].status === 404 && hs['404'].h.get('x-content-type-options') === 'nosniff' && hs['404'].h.get('x-frame-options') === 'DENY' && /frame-ancestors 'none'/.test(hs['404'].h.get('content-security-policy') || '') && hs['404'].h.get('referrer-policy') === 'same-origin');const home = (await get(MAIN, '/')).t;// (the attribute order of a <meta> tag is not part of the contract: Hybriel prints http-equiv first now, it printed content first before)const metaTags = home.match(/<meta [^>]*>/g) || [];const cspMeta = metaTags.find((m) => /http-equiv="Content-Security-Policy"/.test(m)) || '';check('[fix] every page head carries the CSP meta (no <base>, no object, forms to self, no frames) and the referrer meta', /content="[^"]*object-src 'none'[^"]*base-uri 'none'[^"]*form-action 'self'[^"]*"/.test(cspMeta) && metaTags.some((m) => /name="referrer"/.test(m) && /content="same-origin"/.test(m)));note('KNOWN GAP (hl:web, reports/SI-sec.md): component pages carry no X-Content-Type-Options / X-Frame-Options / frame-ancestors / Cache-Control header — hl:web has no setting; nginx must add them');const ph = await get(MAIN, '/'); note('page header X-Frame-Options now: ' + ph.h.get('x-frame-options') + ' | Cache-Control: ' + ph.h.get('cache-control'));console.log('# 4. cookies and sessions');// Hybriel W124: a page request makes no session and sets no cookie any more; the cookie comes with the first face that stores something in the session (rememberPending, after a code was asked)const cookieHeaderOf = async (base, email) => { await post(base, '/api/code', { email }); await sleep(300); const r = await fetch(base + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: 1, event: 'rememberPending', payload: [email] }) }); return r.headers.get('set-cookie') || ''; };check('a plain page request sets no cookie (sessions are lazy)', !((await fetch(MAIN + '/')).headers.get('set-cookie')));const plain = await cookieHeaderOf(MAIN, '[email protected]');check('http (dev): cookie identsid, HttpOnly, SameSite=Lax, a Max-Age', /^identsid=[0-9a-f]{32};/.test(plain) && /HttpOnly/.test(plain) && /SameSite=Lax/.test(plain) && /Max-Age=\d+/.test(plain), plain);const sec = await cookieHeaderOf(HTTPS, '[email protected]');check('[fix] behind https (IDENT_PUBLIC_URL=https://…): the cookie is Secure, HttpOnly, SameSite=Lax and named __Host-identsid (Path=/, no Domain)', /^__Host-identsid=[0-9a-f]{32};/.test(sec) && /; Secure/.test(sec) && /HttpOnly/.test(sec) && /SameSite=Lax/.test(sec) && /Path=\//.test(sec) && !/Domain=/i.test(sec), sec);const lo = await signIn(MAIN, '[email protected]');check('signed in: a face works', !errOf((await emit(MAIN, lo.cookie, 'addIdentity', [{}])).v));await emit(MAIN, lo.cookie, 'shellSignOutNow', []);check('logout: the same cookie is signed out at once (face and page)', errOf((await emit(MAIN, lo.cookie, 'addIdentity', [{}])).v) && !(await get(MAIN, '/apps', lo.cookie)).t.includes('[email protected]'));const lo2 = await signIn(MAIN, '[email protected]'); await emit(MAIN, lo2.cookie, 'shellSignOutNow', []);check('logout from the shell menu ends the session too', errOf((await emit(MAIN, lo2.cookie, 'addIdentity', [{}])).v));const planted = 'ab'.repeat(16);await post(MAIN, '/api/code', { email: '[email protected]' });await sleep(300);const pcode = readFileSync(sinkOf(MAIN), 'utf8').split('\n').filter((x) => x.startsWith('[email protected] ')).at(-1).split(' ')[1];const pv = await emit(MAIN, 'identsid=' + planted, 'verifyCode', ['[email protected]', pcode, 'UTC']);check('a session id the server never issued is not adopted at sign-in (no fixation with an invented id)', pv.cookie != null && pv.cookie !== 'identsid=' + planted && errOf((await emit(MAIN, 'identsid=' + planted, 'addIdentity', [{}])).v));await post(MAIN, '/api/code', { email: '[email protected]' }); await sleep(300);// Hybriel W124: a page request no longer mints a session; the session that exists BEFORE the sign-in is one a face made (rememberPending stores the address in it)const pre = await fetch(MAIN + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: 1, event: 'rememberPending', payload: ['[email protected]'] }) });const own = pre.headers.get('set-cookie').split(';')[0];const fcode = readFileSync(sinkOf(MAIN), 'utf8').split('\n').filter((x) => x.startsWith('[email protected] ')).at(-1).split(' ')[1];await get(MAIN, '/', own);const fv = await emit(MAIN, own, 'verifyCode', ['[email protected]', fcode, 'UTC']);const kept = fv.cookie == null && !errOf((await emit(MAIN, own, 'addIdentity', [{}])).v);note('KNOWN GAP (hl:web): the session id is NOT rotated at sign-in — a cookie planted before login (' + (kept ? 'still' : 'no longer') + ' valid after it) is what the __Host- prefix keeps siblings from planting; repro .scratch/fixation-repro.mjs');const wsHs = (origin) => new Promise((res) => { const s = net.connect(P0, '127.0.0.1', () => s.write(['GET /__hl/socket HTTP/1.1', 'Host: 127.0.0.1:' + P0, 'Upgrade: websocket', 'Connection: Upgrade', 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==', 'Sec-WebSocket-Version: 13', 'Origin: ' + origin, 'Cookie: ' + alice.cookie, '', ''].join('\r\n'))); let d = ''; s.on('data', (c) => { d += c; if (d.includes('\r\n\r\n')) { s.destroy(); res(d.split('\r\n')[0]); } }); setTimeout(() => { s.destroy(); res(d.split('\r\n')[0] || 'timeout'); }, 3000); });const w = await wsHs('http://evil.example');const cs = await fetch(MAIN + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'text/plain', origin: 'http://evil.example', cookie: alice.cookie }, body: J({ t: 'emit', i: 1, event: 'changeTimeZone', payload: ['Asia/Tokyo'] }) });note('KNOWN GAP (hl:web): the socket handshake answers "' + w + '" and POST /__hl/emit answers ' + cs.status + ' to a foreign Origin — no Origin check; only SameSite=Lax stands between a same-site sibling and the faces');console.log('# 5. uploads and limits');const up = await fetch(MAIN + '/__hl/upload', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ name: 'x.bin', type: 'text/html', size: 1000 }) });check('[fix] a signed-out visitor cannot start an upload (/__hl/upload, uploadMax 0 — ident takes no file in any emit): 413', up.status === 413, up.status);const up2 = await fetch(MAIN + '/__hl/upload', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ name: 'x.bin', type: 'text/html', size: 1073741824 }) });check('[fix] …and not a 1 GiB one either', up2.status === 413, up2.status);const capper = await signIn(MAIN, '[email protected]');const made = []; for (let i = 0; i < 4; i++) made.push((await emit(MAIN, capper.cookie, 'appCreate', [{ name: 'App' + i, origins: ['http://127.0.0.1:' + (9000 + i)] }])).v);check('[fix] an account can make 3 apps (the gate\'s IDENT_MAX_APPS) and the 4th is refused with a message', made.slice(0, 3).every((v) => !errOf(v)) && errOf(made[3]) && /at most 3 apps/.test(made[3].error), J(made.map((v) => v.error || 'ok')));const idm = []; for (let i = 0; i < 3; i++) idm.push((await emit(MAIN, capper.cookie, 'addIdentity', [{ identityName: 'i' + i }])).v);check('[fix] an account can have 3 identities (IDENT_MAX_IDENTITIES, the default one counts) and the next is refused', !errOf(idm[0]) && !errOf(idm[1]) && errOf(idm[2]) && /at most 3 identities/.test(idm[2].error), J(idm.map((v) => v.error || 'ok')));const codes = []; for (let i = 0; i < 5; i++) codes.push((await post(LIMIT, '/api/code', { email: '[email protected]' }, { 'x-client-ip': '1.1.1.1' })).status);check('login: 3 codes per address per 10 minutes, then 429', codes.join(' ') === '200 200 200 429 429', codes.join(' '));const ips = []; for (let i = 0; i < 12; i++) ips.push((await post(LIMIT, '/api/code', { email: 'ip' + i + '@example.com' }, { 'x-client-ip': '2.2.2.2', 'x-forwarded-for': '9.9.9.' + i, 'cf-connecting-ip': '8.8.8.' + i })).status);check('login: 10 codes per client IP per 10 minutes, then 429; X-Forwarded-For / CF-Connecting-IP are not trusted', ips.slice(0, 10).every((s) => s === 200) && ips.slice(10).every((s) => s === 429), ips.join(' '));await post(LIMIT, '/api/code', { email: '[email protected]' }, { 'x-client-ip': '4.4.4.4' });const tries = []; for (let i = 0; i < 6; i++) tries.push((await emit(LIMIT, null, 'verifyCode', ['[email protected]', '00000' + i, 'UTC'])).v.error);check('login: 5 wrong codes kill the code; the 6th try finds none waiting', /too many wrong codes/.test(tries[4]) && /no code is waiting/.test(tries[5]), J(tries));note('exchange: no rate limit — key (128 bit), secret (192 bit) and code (192 bit, 60 s, single use) are not guessable; a per-IP limit would throttle the app server itself');console.log(`security: ${passed} passed, ${failed} failed`);stopAll();await sleep(500);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