gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit6d4f996e6d4f996esessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre6d4f996e/tests/selector.mjs

34.0 KB

  1. // tests/selector.mjs — THE GATE OF PIECE 3 (ticket #26): the identity selector. Real
  2. // headless Chrome (tests/cdp.mjs, --disable-gpu): signed in to ident on the ident origin →
  3. // the test app's page on its own origin shows <ident-selector> with the right identities →
  4. // select → one-time code → the test app's server exchanges it → the page switches to
  5. // logged in WITHOUT A RELOAD → `logged-in` → host logout resets the selector. Plus the
  6. // negatives (unregistered origin, wrong key, signed out, forged sessions #31, code reuse,
  7. // strict API) and a host restyle that must change the look.
  8. //
  9. // Own servers only, NEVER the dev server and NEVER real mail:
  10. // ident :8390 (IDENT_MAIL_SINK), test app A :8391, test app B :8392 (both against :8390),
  11. // a plain node page on :8393 = an origin NOT registered for any app.
  12. // Own storage: .scratch/selector-gate/ (wiped at start). Chrome debug ports 8690-8699.
  13. // Screenshots: .scratch/selector-*.png (390 and 1280 px) — look at them.
  14. //
  15. // Run: node tests/selector.mjs (exit 0 = all passed)
  16. import { spawn } from 'node:child_process';
  17. import { createServer } from 'node:http';
  18. import { readFileSync, writeFileSync, rmSync, mkdirSync, existsSync } from 'node:fs';
  19. import { dirname, join } from 'node:path';
  20. import { fileURLToPath } from 'node:url';
  21. import { launchBrowser, sleep } from './cdp.mjs';
  22. // H2: a server-rendered page can be clicked before the client mounted — the click is lost (or a native form GET). Every goto() on a Hybriel
  23. // page (the SSR HTML carries #hl-seed) therefore waits until the page is live (socket open) before the test touches it.
  24. function live(page) {
  25. const goto = page.goto.bind(page);
  26. page.goto = async (url, o) => {
  27. const r = await goto(url, o);
  28. await page.waitFor("!document.getElementById('hl-seed') || (!!window.__hl && !!window.__hl.socket && window.__hl.socket.readyState === 1)", { label: 'page hydrated ' + url });
  29. return r;
  30. };
  31. return page;
  32. }
  33. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  34. const APP = join(dirname(fileURLToPath(import.meta.url)), '..');
  35. const G = join(APP, '.scratch/selector-gate');
  36. const SHOTS = join(APP, '.scratch');
  37. const P0 = Number(process.env.SELECTOR_GATE_PORT || 8390); // ident = P0, test app A = P0+1, test app B = P0+2, the unregistered origin = P0+3; Chrome SELECTOR_GATE_CHROME (default 8690-8699)
  38. const ID = 'http://127.0.0.1:' + P0;
  39. const TA = 'http://127.0.0.1:' + (P0 + 1), TB = 'http://127.0.0.1:' + (P0 + 2), EVIL = 'http://127.0.0.1:' + (P0 + 3);
  40. const CHROME_PORTS = (process.env.SELECTOR_GATE_CHROME || '8690-8699').split('-').map(Number);
  41. const J = JSON.stringify;
  42. let passed = 0, failed = 0;
  43. const check = (name, ok, detail = '') => {
  44. if (ok) { passed++; console.log(' ok ' + name); }
  45. else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); }
  46. };
  47. // ---- servers ----------------------------------------------------------------------------
  48. const procs = [];
  49. function start(cwd, env, log) {
  50. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], {
  51. cwd, env: { ...process.env, SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', ...env },
  52. stdio: ['ignore', 'pipe', 'pipe'],
  53. });
  54. let out = '';
  55. p.stdout.on('data', d => { out += d; }); p.stderr.on('data', d => { out += d; });
  56. p.on('exit', () => writeFileSync(join(G, log), out));
  57. procs.push({ p, log });
  58. return p;
  59. }
  60. async function up(url) {
  61. for (const end = Date.now() + Number(process.env.IDENT_COLD_MS || 120000); Date.now() < end;) { try { await fetch(url + "/", { redirect: "manual" }); return; } catch {} await sleep(250); }
  62. throw new Error('server did not come up: ' + url);
  63. }
  64. rmSync(G, { recursive: true, force: true });
  65. mkdirSync(join(G, 'main'), { recursive: true });
  66. start(APP, {
  67. IDENT_PORT: String(P0), IDENT_STORAGE: join(G, 'main', 'ident'), IDENT_SESSIONS: join(G, 'main', 'sess') + '/',
  68. IDENT_MAIL_SINK: join(G, 'main', 'mail.txt'), IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000',
  69. }, 'ident.log');
  70. const testapp = (port, file) => start(join(APP, 'testapp'), {
  71. TESTAPP_PORT: String(port), TESTAPP_URL: 'http://127.0.0.1:' + port, IDENT_URL: ID, TESTAPP_STORE: join(G, file),
  72. }, 'testapp-' + port + '.log');
  73. testapp(P0 + 1, 'testapp-a.json'); testapp(P0 + 2, 'testapp-b.json');
  74. // the UNREGISTERED ORIGIN: a page that includes the selector with app A's key
  75. let evilKey = '';
  76. const evil = createServer((req, res) => {
  77. res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
  78. res.end(`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>not registered</title></head><body style="background:#222;color:#ccc;font:16px system-ui"><p>an origin not registered in ident</p><ident-selector id="selector" key="${evilKey}"></ident-selector><script src="${ID}/selector.js"></script></body></html>`);
  79. });
  80. await new Promise(r => evil.listen(P0 + 3, '127.0.0.1', r));
  81. await Promise.all([up(ID), up(TA), up(TB)]);
  82. // ---- helpers ----------------------------------------------------------------------------
  83. const lastCode = (email) => {
  84. const lines = readFileSync(join(G, 'main', 'mail.txt'), 'utf8').trim().split('\n').filter(l => l.startsWith(email + ' '));
  85. return lines.length ? lines[lines.length - 1].split(' ')[1] : null;
  86. };
  87. let emitI = 0;
  88. // hybriel#16 (mission 036): hl:web itself refuses an emit with one argument too many — the ack is
  89. // ok:false "… the `session` parameter is filled by the server, never by the peer"; the face never runs.
  90. const framework_refused = (raw) => { try { const j = JSON.parse(raw); return j.ok === false && /the `session` parameter is filled by the server/.test(j.error || ''); } catch { return false; } };
  91. async function emit(event, payload, cookie) {
  92. const r = await fetch(ID + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++emitI, event, payload }) });
  93. const t = await r.text();
  94. let j = null; try { j = JSON.parse(t); } catch {}
  95. return { status: r.status, value: j && j.value, raw: t };
  96. }
  97. // a request to ident as a browser on `origin` would send it (node may set Origin)
  98. async function call(method, path, { origin, cookie, body, headers = {} } = {}) {
  99. const h = { ...headers };
  100. if (origin) h.origin = origin;
  101. if (cookie) h.cookie = cookie;
  102. if (body !== undefined && !h['content-type']) h['content-type'] = 'application/json';
  103. const r = await fetch(ID + path, { method, headers: h, body: body === undefined ? undefined : (typeof body === 'string' ? body : J(body)), redirect: 'manual' });
  104. const t = await r.text();
  105. let j = null; try { j = JSON.parse(t); } catch {}
  106. return { status: r.status, j, t, h: r.headers };
  107. }
  108. async function exchange(body) {
  109. const r = await fetch(ID + '/api/exchange', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J(body) });
  110. return { status: r.status, j: await r.json().catch(() => null) };
  111. }
  112. const pages = [];
  113. async function ready(p) { await p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated' }); }
  114. async function viewport(p, w) {
  115. await p.send('Emulation.setDeviceMetricsOverride', { width: w, height: w < 500 ? 844 : 900, deviceScaleFactor: 1, mobile: w < 500 });
  116. }
  117. async function shot(p, name) {
  118. for (const w of [390, 1280]) {
  119. await viewport(p, w);
  120. await sleep(200);
  121. const over = await p.evaluate('document.documentElement.scrollWidth > window.innerWidth');
  122. check(`${name} @${w}px: no horizontal overflow`, !over);
  123. const { data } = await p.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  124. writeFileSync(join(SHOTS, `selector-${name}-${w}.png`), Buffer.from(data, 'base64'));
  125. }
  126. await viewport(p, 1280);
  127. }
  128. const txt = (p, sel) => p.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || ''`);
  129. // INSIDE THE SELECTOR'S SHADOW ROOT
  130. const sh = (hostSel, expr) => `(() => { const h = document.querySelector(${J(hostSel)}); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;
  131. const shText = (p, inner, host = '#selector') => p.evaluate(sh(host, `(r.querySelector(${J(inner)}) || {}).textContent || ''`));
  132. const shNames = (p, host = '#selector') => p.evaluate(sh(host, `[...r.querySelectorAll('[part~="identity"]')].map(b => b.textContent)`));
  133. // a REAL click (Input domain) on an element inside the shadow root; `name` picks an
  134. // identity button by its text
  135. async function shClick(p, inner, { host = '#selector', name = null, timeout = 8000 } = {}) {
  136. const find = `(() => { const h = document.querySelector(${J(host)}); const r = h && h.shadowRoot; if (!r) return null; ` +
  137. `const el = ${name === null ? `r.querySelector(${J(inner)})` : `[...r.querySelectorAll(${J(inner)})].find(b => b.textContent === ${J(name)})`}; ` +
  138. `if (!el) return null; el.scrollIntoView({ block: 'center' }); const b = el.getBoundingClientRect(); if (!b.width) return null; return { x: b.left + b.width / 2, y: b.top + b.height / 2 }; })()`;
  139. const box = await p.waitFor(find, { timeout, label: `shadow ${host} ${inner} ${name || ''}` });
  140. const base = { x: Math.round(box.x), y: Math.round(box.y), button: 'left', clickCount: 1 };
  141. await p.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...base, buttons: 0 });
  142. await p.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...base, buttons: 1 });
  143. await p.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...base, buttons: 0 });
  144. }
  145. const waitList = (p, host = '#selector') => p.waitFor(sh(host, `r.querySelectorAll('[part~="identity"]').length > 0`), { label: 'identity list in ' + host });
  146. const waitMsg = (p, re, host = '#selector') => p.waitFor(sh(host, `/${re}/.test((r.querySelector('#message') || {}).textContent || '')`), { label: 'selector message ' + re });
  147. const shStyle = (p, inner, prop) => p.evaluate(sh('#selector', `getComputedStyle(r.querySelector(${J(inner)}))[${J(prop)}]`));
  148. let browser1, browser2;
  149. try {
  150. browser1 = await launchBrowser({ debugPortRange: CHROME_PORTS });
  151. browser2 = await launchBrowser({ debugPortRange: CHROME_PORTS });
  152. const p = live(await browser1.newPage()); pages.push(p);
  153. await viewport(p, 1280);
  154. // ==== 1. sign in to ident (on ident's origin), two identities, two apps ================
  155. console.log('# setup: ident account, identities, apps, test apps');
  156. const ALICE = '[email protected]';
  157. await p.goto(ID + '/');
  158. await p.waitForSelector('#email'); await ready(p);
  159. await p.type('#email', ALICE);
  160. await p.click('#sendcode');
  161. await p.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'code page' });
  162. await ready(p); // ident#20: the code step is its own page (/code) — wait for it to hydrate
  163. await p.type('#code', lastCode(ALICE));
  164. await p.click('#verify');
  165. await p.waitForSelector('#skip');
  166. await p.click('#skip');
  167. await p.waitFor('!document.querySelector("#identityform")');
  168. await p.click('#newidentity');
  169. await p.waitForSelector('#identityform');
  170. await p.type('#fidentityname', 'Work');
  171. await p.click('#saveidentity');
  172. await p.waitFor('document.querySelectorAll("#identities li").length === 2');
  173. const register = async (name, origins) => {
  174. await p.goto(ID + '/apps'); await p.waitForSelector('#newapp'); await ready(p);
  175. await p.click('#newapp');
  176. await p.waitForSelector('#appform');
  177. await p.type('#fappname', name);
  178. await p.type('#forigins', origins);
  179. await p.click('#saveapp');
  180. await p.waitForSelector('#secret');
  181. const secret = (await txt(p, '#secret')).trim();
  182. const keys = await p.evaluate('[...document.querySelectorAll("#apps .apikey")].map(e => e.textContent.trim())');
  183. await p.click('#secretdone');
  184. return { key: keys[keys.length - 1], secret };
  185. };
  186. const A = await register('Selector app A', TA);
  187. const B = await register('Selector app B', TB);
  188. check('two apps registered', /^pk_[0-9a-f]{32}$/.test(A.key) && /^pk_[0-9a-f]{32}$/.test(B.key) && A.key !== B.key, J([A.key, B.key]));
  189. evilKey = A.key;
  190. const setupApp = async (base, key, secret) => {
  191. await p.goto(base + '/');
  192. await p.type('#key', key, { clear: true });
  193. await p.type('#secret', secret, { clear: true });
  194. await p.evaluate('window.__old = 1');
  195. await p.click('#savesetup');
  196. await p.waitFor('!window.__old && document.readyState === "complete" && !!document.querySelector("#setupkey")', { label: 'setup saved' });
  197. check('test app ' + base + ' set up', (await txt(p, '#setupkey')) === key);
  198. };
  199. await setupApp(TA, A.key, A.secret);
  200. await setupApp(TB, B.key, B.secret);
  201. const aliceCookie = (await p.cookies([ID])).filter(c => c.name === 'identsid').map(c => 'identsid=' + c.value)[0];
  202. check('browser holds the ident session cookie (identsid)', !!aliceCookie);
  203. // ==== 2. the selector on the test app's page: closed, open, identities ================
  204. console.log('# selector: shown, opened, identities');
  205. await p.goto(TA + '/');
  206. await p.waitFor('!!customElements.get("ident-selector") && !!document.querySelector("#selector").shadowRoot', { label: 'selector defined' });
  207. check('the page includes ident\'s script', await p.evaluate(`!![...document.scripts].find(s => s.src === ${J(ID + '/selector.js')})`));
  208. check('selector is configured with the app\'s API key', (await p.evaluate('document.querySelector("#selector").getAttribute("key")')) === A.key);
  209. check('selector first says "choose ident"', (await shText(p, '#choose')).replace(/[▼▲]/g, '').trim() === 'choose ident', await shText(p, '#choose'));
  210. check('not logged in: no logged-in attribute', !(await p.evaluate('document.querySelector("#selector").hasAttribute("logged-in")')));
  211. check('shadow DOM in ident\'s design (accent #ce9178)', (await shStyle(p, '#choose', 'backgroundColor')) === 'rgb(206, 145, 120)', await shStyle(p, '#choose', 'backgroundColor'));
  212. await shot(p, 'closed');
  213. await shClick(p, '#choose');
  214. await waitList(p);
  215. const names = await shNames(p);
  216. check('open: the signed-in user\'s identities (identity names)', J(names) === J(['Default', 'Work']), J(names));
  217. await shot(p, 'open');
  218. // what ident answered (read by the page itself, as the script does)
  219. const listA = await p.evaluate(`fetch(${J(ID + '/api/selector/identities?key=' + A.key)}, { credentials: 'include' }).then(r => r.json())`);
  220. check('answer: only { signedIn, identities: [{ id, name }] }', listA.signedIn === true && listA.identities.every(i => J(Object.keys(i)) === '["id","name"]'), J(listA));
  221. check('list ids are opaque (32 hex, not ident\'s identity ids)', listA.identities.every(i => /^[0-9a-f]{32}$/.test(i.id)), J(listA));
  222. const noEmail = !J(listA).includes('alice');
  223. check('no email in the answer', noEmail);
  224. const toggleClosed = async () => { await shClick(p, '#choose'); await p.waitFor(sh('#selector', `!r.querySelector('#panel')`)); };
  225. await toggleClosed();
  226. check('clicking again closes it', true);
  227. // ==== 3. select = login, without a reload ============================================
  228. console.log('# select → code → host exchange → logged in without reload');
  229. await p.evaluate('window.__noReload = 1; window.__codes = []; document.querySelector("#selector").addEventListener("ident-login", e => window.__codes.push(e.detail.code))');
  230. const cookiesBefore = (await p.cookies([TA])).map(c => c.name).sort();
  231. await shClick(p, '#choose');
  232. await waitList(p);
  233. await shClick(p, '[part~="identity"]', { name: 'Work' });
  234. await p.waitFor('/Logged in/.test(document.querySelector("#loginstate").textContent) && !!document.querySelector("#identity")', { label: 'logged in via selector' });
  235. check('no reload happened', (await p.evaluate('window.__noReload')) === 1);
  236. const codes = await p.evaluate('window.__codes');
  237. check('ident-login event carried a one-time code (48 hex)', codes.length === 1 && /^[0-9a-f]{48}$/.test(codes[0]), J(codes));
  238. const idWork = (await txt(p, '#identity')).trim();
  239. check('host exchanged it: the identity\'s short id', /^[2-9a-hj-km-np-z]{5}$/.test(idWork), idWork);
  240. check('test app: new user', (await txt(p, '#userstate')) === 'new user');
  241. check('host set logged-in', await p.evaluate('document.querySelector("#selector").hasAttribute("logged-in") && document.querySelector("#selector").loggedIn === true'));
  242. const status = await shText(p, '#status');
  243. check('selector shows the logged-in state with the identity', /logged in with ident/.test(status) && /Work/.test(status) && !(await p.evaluate(sh('#selector', `!!r.querySelector('#choose')`))), status);
  244. check('logout offered', !(await p.evaluate('document.querySelector("#logout").hidden')));
  245. const cookiesAfter = (await p.cookies([TA])).map(c => c.name).sort();
  246. check('the selector set no cookie (only the test app\'s own session cookie is new)', J(cookiesAfter.filter(n => !cookiesBefore.includes(n))) === J(['testapp' + (P0 + 1) + 'sid']), J([cookiesBefore, cookiesAfter]));
  247. await shot(p, 'loggedin');
  248. const reuse = await exchange({ key: A.key, secret: A.secret, code: codes[0] });
  249. check('code reuse: the selector\'s code a second time → 400', reuse.status === 400 && /already used/.test(reuse.j.error), J(reuse));
  250. // the host knows its session: after a reload it renders logged-in itself
  251. await p.goto(TA + '/');
  252. await p.waitFor('!!customElements.get("ident-selector")');
  253. check('reload: host renders <ident-selector logged-in>', await p.evaluate('document.querySelector("#selector").hasAttribute("logged-in")'));
  254. check('reload: still logged in in the test app', /Logged in/.test(await txt(p, '#loginstate')));
  255. // ==== 4. host logout resets the selector =============================================
  256. console.log('# host logout');
  257. await p.evaluate('window.__noReload = 1');
  258. await p.click('#logout');
  259. await p.waitFor('/Not logged in/.test(document.querySelector("#loginstate").textContent)');
  260. check('logout: no reload', (await p.evaluate('window.__noReload')) === 1);
  261. check('logout: selector reset (no logged-in, says "choose ident" again)', !(await p.evaluate('document.querySelector("#selector").hasAttribute("logged-in")')) && /choose/.test(await shText(p, '#choose')));
  262. await p.goto(TA + '/');
  263. await p.waitFor('!!customElements.get("ident-selector")');
  264. check('after logout + reload: not logged in', !(await p.evaluate('document.querySelector("#selector").hasAttribute("logged-in")')) && /Not logged in/.test(await txt(p, '#loginstate')));
  265. // ==== 5. the other identity, and the same one via the login button ===================
  266. console.log('# ids: per identity, same as the button flow');
  267. await shClick(p, '#choose');
  268. await waitList(p);
  269. await shClick(p, '[part~="identity"]', { name: 'Default' });
  270. await p.waitFor('!!document.querySelector("#identity")');
  271. const idDefault = (await txt(p, '#identity')).trim();
  272. check('other identity → other id, new user', /^[2-9a-hj-km-np-z]{5}$/.test(idDefault) && idDefault !== idWork && (await txt(p, '#userstate')) === 'new user', J([idDefault, idWork]));
  273. await p.click('#logout');
  274. await p.waitFor('/Not logged in/.test(document.querySelector("#loginstate").textContent)');
  275. await p.click('#login');
  276. await p.waitForSelector('#chooselist'); await ready(p);
  277. await p.click('#chooselist li:nth-child(2) .choose');
  278. await p.waitFor(`location.href.startsWith(${J(TA + '/callback')}) && !!document.querySelector("#identity")`);
  279. check('login button with Work → the same id as the selector gave', (await txt(p, '#identity')).trim() === idWork && (await txt(p, '#userstate')) === 'welcome back');
  280. // app B: the same identity gets the same id there
  281. await p.goto(TB + '/');
  282. await shClick(p, '#choose');
  283. await waitList(p);
  284. const listB = await p.evaluate(`fetch(${J(ID + '/api/selector/identities?key=' + B.key)}, { credentials: 'include' }).then(r => r.json())`);
  285. check('list ids differ per app', listB.identities.every((x, i) => x.id !== listA.identities[i].id), J([listA, listB]));
  286. await shClick(p, '[part~="identity"]', { name: 'Work' });
  287. await p.waitFor('!!document.querySelector("#identity")');
  288. const idWorkB = (await txt(p, '#identity')).trim();
  289. check('same identity, app B → the SAME id', idWorkB === idWork);
  290. // ==== 6. restyle by the host =========================================================
  291. console.log('# restyle by the host');
  292. await p.goto(TA + '/');
  293. await p.waitFor('!!customElements.get("ident-selector")');
  294. // the login button above logged this browser in to the test app: log out first
  295. if (await p.evaluate('!document.querySelector("#logout").hidden')) {
  296. await p.click('#logout');
  297. await p.waitFor(sh('#selector', `!!r.querySelector('#choose')`), { label: 'selector reset' });
  298. }
  299. const before = { bg: await shStyle(p, '#choose', 'backgroundColor'), radius: await shStyle(p, '#choose', 'borderTopLeftRadius'), tt: await shStyle(p, '#choose', 'textTransform') };
  300. await p.evaluate(`document.head.insertAdjacentHTML('beforeend', '<style id="restyle">#selector { --ident-accent: rgb(86, 155, 212); --ident-radius: 0px; } #selector::part(button) { text-transform: uppercase; } #selector::part(identity) { font-style: italic; }</style>')`);
  301. const after = { bg: await shStyle(p, '#choose', 'backgroundColor'), radius: await shStyle(p, '#choose', 'borderTopLeftRadius'), tt: await shStyle(p, '#choose', 'textTransform') };
  302. check('custom property --ident-accent changes the button colour', before.bg === 'rgb(206, 145, 120)' && after.bg === 'rgb(86, 155, 212)', J([before, after]));
  303. check('custom property --ident-radius changes the corners', before.radius !== '0px' && after.radius === '0px', J([before, after]));
  304. check('::part(button) restyles from the host', before.tt === 'none' && after.tt === 'uppercase', J([before, after]));
  305. await shClick(p, '#choose');
  306. await waitList(p);
  307. check('::part(identity) restyles the list', (await p.evaluate(sh('#selector', `getComputedStyle(r.querySelector('[part~="identity"]')).fontStyle`))) === 'italic');
  308. await shot(p, 'restyled-open');
  309. await p.evaluate('document.querySelector("#restyle").remove()');
  310. await toggleClosed();
  311. // ==== 7. negatives in the browser ====================================================
  312. console.log('# negatives: origin, key, signed out');
  313. // (a) an origin not registered for the app — same site, so the ident cookie DOES travel;
  314. // only the Origin check stops it
  315. await p.goto(EVIL + '/');
  316. await p.waitFor('!!customElements.get("ident-selector")');
  317. await shClick(p, '#choose');
  318. await waitMsg(p, 'does not answer this site');
  319. check('unregistered origin: no identities, an explanation', (await shNames(p)).length === 0);
  320. const evilFetch = await p.evaluate(`fetch(${J(ID + '/api/selector/identities?key=' + A.key)}, { credentials: 'include' }).then(r => 'got ' + r.status, e => 'blocked: ' + e.name)`);
  321. check('unregistered origin: the browser gets nothing (CORS)', evilFetch === 'blocked: TypeError', evilFetch);
  322. const evilChoose = await p.evaluate(`fetch(${J(ID + '/api/selector/choose?key=' + A.key)}, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ identity: ${J(listA.identities[0].id)} }) }).then(r => 'got ' + r.status, e => 'blocked: ' + e.name)`);
  323. check('unregistered origin: choose blocked (preflight refused)', evilChoose === 'blocked: TypeError', evilChoose);
  324. await shot(p, 'unregistered');
  325. p.messages.splice(0); // the CORS refusals above are expected console errors
  326. // (b) wrong key on a registered origin: app B's key on app A's page, and a made-up key
  327. await p.goto(TA + '/');
  328. await p.waitFor('!!customElements.get("ident-selector")');
  329. const before2 = p.messages.length;
  330. for (const [label, key] of [["another app's key", B.key], ['an unknown key', 'pk_' + '0'.repeat(32)]]) {
  331. await p.evaluate(`document.querySelector("#other") && document.querySelector("#other").remove(); document.querySelector("#selectorbox").insertAdjacentHTML('beforeend', '<ident-selector id="other" key="${key}"></ident-selector>')`);
  332. await shClick(p, '#choose', { host: '#other' });
  333. await waitMsg(p, 'does not answer this site', '#other');
  334. check(`wrong key (${label}): no identities`, (await shNames(p, '#other')).length === 0);
  335. }
  336. p.messages.splice(before2);
  337. // (c) signed out of ident: the second browser has no ident session
  338. const q = live(await browser2.newPage()); pages.push(q);
  339. await viewport(q, 1280);
  340. await q.goto(TA + '/');
  341. await q.waitFor('!!customElements.get("ident-selector")');
  342. await shClick(q, '#choose');
  343. await waitMsg(q, 'not signed in to ident');
  344. check('signed out of ident: no identities, a link to sign in to ident', (await shNames(q)).length === 0 && (await q.evaluate(sh('#selector', `r.querySelector('#signin').href`))) === ID + '/');
  345. const outList = await q.evaluate(`fetch(${J(ID + '/api/selector/identities?key=' + A.key)}, { credentials: 'include' }).then(r => r.json())`);
  346. check('signed out: ident answers { signedIn: false, identities: [] }', outList.signedIn === false && Array.isArray(outList.identities) && outList.identities.length === 0 && Object.keys(outList).length === 2, J(outList));
  347. await shot(q, 'signedout');
  348. // ==== 8. the API directly: CORS headers, strict body, forged sessions ================
  349. console.log('# API: CORS, strict, forged sessions');
  350. let r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: TA, cookie: aliceCookie });
  351. check('registered origin + key: 200, ACAO = that exact origin, credentials true', r.status === 200 && r.h.get('access-control-allow-origin') === TA && r.h.get('access-control-allow-credentials') === 'true' && r.j.identities.length === 2, `${r.status} ${r.h.get('access-control-allow-origin')} ${r.t}`);
  352. check('Vary: Origin, no Set-Cookie from the selector API', /Origin/.test(r.h.get('vary') || '') && !r.h.get('set-cookie'));
  353. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: EVIL, cookie: aliceCookie });
  354. check('unregistered origin: 403, no CORS headers, no identities', r.status === 403 && !r.h.get('access-control-allow-origin') && !r.t.includes('Work'), `${r.status} ${r.t}`);
  355. r = await call('GET', '/api/selector/identities?key=' + B.key, { origin: TA, cookie: aliceCookie });
  356. check("another app's key on this origin: 403, no CORS headers", r.status === 403 && !r.h.get('access-control-allow-origin'), `${r.status} ${r.t}`);
  357. r = await call('GET', '/api/selector/identities', { origin: TA, cookie: aliceCookie });
  358. check('no key: 403', r.status === 403, r.t);
  359. r = await call('GET', '/api/selector/identities?key=' + A.key, { cookie: aliceCookie });
  360. check('no Origin header: 403', r.status === 403, r.t);
  361. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: 'null', cookie: aliceCookie });
  362. check('Origin null: 403', r.status === 403, r.t);
  363. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: TA + '.evil.example', cookie: aliceCookie });
  364. check('origin with the registered one as prefix: 403', r.status === 403, r.t);
  365. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: TA, cookie: 'identsid=' + 'f'.repeat(32) });
  366. check('made-up ident cookie: signed out', r.status === 200 && r.j.signedIn === false, r.t);
  367. r = await call('OPTIONS', '/api/selector/choose?key=' + A.key, { origin: TA, headers: { 'access-control-request-method': 'POST', 'access-control-request-headers': 'content-type' } });
  368. check('preflight from a registered origin: 204 + allow POST, Content-Type', r.status === 204 && r.h.get('access-control-allow-origin') === TA && /POST/.test(r.h.get('access-control-allow-methods')) && /Content-Type/i.test(r.h.get('access-control-allow-headers')), `${r.status} ${[...r.h].join(' ')}`);
  369. r = await call('OPTIONS', '/api/selector/choose?key=' + A.key, { origin: EVIL });
  370. check('preflight from an unregistered origin: 403, no CORS headers', r.status === 403 && !r.h.get('access-control-allow-origin'), `${r.status}`);
  371. const pick = listA.identities[1].id; // Work
  372. const choose = (body, opt = {}) => call('POST', '/api/selector/choose?key=' + A.key, { origin: TA, cookie: aliceCookie, body, ...opt });
  373. r = await choose({ identity: pick });
  374. check('choose: 200 { code } only', r.status === 200 && J(Object.keys(r.j)) === '["code"]' && /^[0-9a-f]{48}$/.test(r.j.code), r.t);
  375. const code1 = r.j.code;
  376. let x = await exchange({ key: A.key, secret: A.secret, code: code1 });
  377. check('exchange of a selector code → the same id as in the browser', x.status === 200 && x.j.identity === idWork, J(x));
  378. x = await exchange({ key: A.key, secret: A.secret, code: code1 });
  379. check('the same code again → 400', x.status === 400, J(x));
  380. r = await choose({ identity: pick });
  381. x = await exchange({ key: B.key, secret: B.secret, code: r.j.code });
  382. check("a selector code for app A presented by app B → 400", x.status === 400 && /not issued to this app/.test(x.j.error), J(x));
  383. x = await exchange({ key: A.key, secret: A.secret, code: r.j.code });
  384. check('…and it is spent', x.status === 400, J(x));
  385. r = await choose({ identity: pick }, { origin: EVIL });
  386. check('choose from an unregistered origin: 403, no code', r.status === 403 && !r.t.includes('code"'), r.t);
  387. r = await choose({ identity: pick }, { cookie: undefined });
  388. check('choose without an ident session: 401', r.status === 401, r.t);
  389. r = await choose({ identity: pick, session: { user: { id: 1 } } }, { cookie: undefined });
  390. check('forged session in the body: refused (unknown field)', r.status === 400 && r.j.error === 'unknown field: session', r.t);
  391. r = await choose({ identity: pick, user: { id: 1 } });
  392. check('unknown field: named', r.status === 400 && r.j.error === 'unknown field: user', r.t);
  393. r = await choose({});
  394. check('missing identity: named', r.status === 400 && r.j.error === 'missing field: identity', r.t);
  395. r = await choose({ identity: 2 });
  396. check('identity of the wrong type: named', r.status === 400 && /field identity must be a string/.test(r.j.error), r.t);
  397. r = await choose('{"identity": ');
  398. check('invalid JSON: 400', r.status === 400 && /not valid JSON/.test(r.j.error), r.t);
  399. r = await choose('["x"]');
  400. check('not an object: 400', r.status === 400, r.t);
  401. // ident's own identity ids (UUIDs since mission 009) as the SSR page renders them in the Edit buttons
  402. const ownIds = [...new Set([...(await (await fetch(ID + '/', { headers: { cookie: aliceCookie } })).text()).matchAll(/value="([0-9a-z]{12})"/g)].map(m => m[1]))];
  403. check("alice's ident identity ids read off / (2, UUIDs)", ownIds.length === 2, J(ownIds));
  404. r = await choose({ identity: ownIds[0] || 'x' });
  405. check("ident's own identity id is not accepted as a pick: 400", r.status === 400 && r.j.error === 'no such identity', r.t);
  406. r = await choose({ identity: '2' });
  407. check("an old numeric identity id is not accepted as a pick: 400", r.status === 400 && r.j.error === 'no such identity', r.t);
  408. r = await choose({ identity: listB.identities[1].id });
  409. check("app B's pick on app A: 400", r.status === 400, r.t);
  410. r = await call('GET', '/api/selector/choose?key=' + A.key, { origin: TA, cookie: aliceCookie });
  411. check('GET choose: 405', r.status === 405, r.t);
  412. r = await call('POST', '/api/selector/identities?key=' + A.key, { origin: TA, cookie: aliceCookie, body: {} });
  413. check('POST identities: 405', r.status === 405, r.t);
  414. // another account: bob's session cannot use alice's pick
  415. // (bob logs in over the emit carrier with the cookie the first frame got)
  416. // (mission 010: the code comes from POST /api/code; the verifyCode frame mints the cookie)
  417. await fetch(ID + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email: '[email protected]' }) });
  418. const vBr = await fetch(ID + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: ++emitI, event: 'verifyCode', payload: ['[email protected]', lastCode('[email protected]'), 'UTC'] }) });
  419. const bCookie = (vBr.headers.get('set-cookie') || '').split(';')[0];
  420. const vBt = await vBr.text();
  421. const vB = { value: (JSON.parse(vBt) || {}).value, raw: vBt };
  422. check('bob signed in (emit carrier)', !!(vB.value && vB.value.account), vB.raw);
  423. r = await choose({ identity: pick }, { cookie: bCookie });
  424. check("another account cannot choose alice's identity", r.status === 400 && r.j.error === 'no such identity', r.t);
  425. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: TA, cookie: bCookie });
  426. check("another account sees only its own identities", r.status === 200 && r.j.identities.length === 1 && r.j.identities[0].name === 'Default' && r.j.identities[0].id !== listA.identities[0].id, r.t);
  427. // #31: the faces still refuse a forged trailing session argument
  428. const forged = { user: { id: 1 } };
  429. for (const [ev, args] of [['addIdentity', [{ identityName: 'X' }]], ['editIdentity', [1, { identityName: 'X' }]], ['dropIdentity', [2]], ['changeTimeZone', ['UTC']], ['chooseIdentity', ['x', 1]], ['appCreate', [{ name: 'X', origins: [TA] }]], ['appNewSecret', [1]], ['appDelete', [1]]]) {
  430. const f = await emit(ev, [...args, forged]);
  431. check(`forged session argument refused (#31): ${ev}`, framework_refused(f.raw) || (f.value && /not signed in/.test(f.value.error)), f.raw);
  432. }
  433. // ident sign-out in browser 1 → the selector there gets nothing either
  434. await p.goto(ID + '/'); await ready(p);
  435. await p.click('#signout');
  436. await p.waitForSelector('#email');
  437. await p.goto(TA + '/');
  438. await p.waitFor('!!customElements.get("ident-selector")');
  439. await shClick(p, '#choose');
  440. await waitMsg(p, 'not signed in to ident');
  441. check('after signing out of ident: no identities', (await shNames(p)).length === 0);
  442. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: TA, cookie: aliceCookie });
  443. check('after signing out of ident: the old cookie gets signedIn false', r.status === 200 && r.j.signedIn === false, r.t);
  444. // ==== 9. console =====================================================================
  445. const probs = pages.flatMap(pg => pg.problems().map(m => m.text));
  446. check('no console errors or warnings (besides the expected CORS refusals)', probs.length === 0, probs.join(' | '));
  447. } catch (err) {
  448. failed++;
  449. console.log(' FAIL (aborted) ' + (err && err.stack || err));
  450. for (const pg of pages) console.log('--- console:\n' + pg.dumpConsole());
  451. } finally {
  452. for (const b of [browser1, browser2]) { if (b) { try { await b.close(); } catch {} } }
  453. for (const { p } of procs) { try { p.kill(); } catch {} }
  454. evil.close();
  455. await sleep(300);
  456. }
  457. console.log(`\n${passed} passed, ${failed} failed`);
  458. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • 6d4f996esessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • 029eb5e5deploy: security gate (tests/security.mjs)mre
  • d3c065a8security audit (SI): uploadMax 0, Secure __Host- cookie behind https, headers on function routes/files, page CSP+referrer meta, app/identity caps, tests/security.mjs, reportmre
  • 5561a0cbreport I4-mobilemre
  • 4ca2ed20404 page in the shell (viewport, status 404, way home); phone: account actions live in the user menu so the open menu covers nothing; mobile gate; signoutall waits for a cold startmre
  • 9baad745tests: browser gate waits for the reloaded document (offline reload race under CPU throttle); HL_CPU_THROTTLE knobmre
  • b96796bdtests: wait for hydration before real clicks after a navigation (H2)mre
  • 9722964fre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • c9b196c9tests/iplimit: wait for the welcome form itself after B's first login (identities list renders before it); mission 017 reportmre
  • 72e0f587ident#26: identity page with "Used in" (app, since, last use, Notif. chip, empty state); lastLogin recorded at exchange; gates + lisbeth E2E; mission 016 reportmre
  • 94576fbcident#26 WIP: identity page /identity/:iid with "Used in" (app, since, last use, Notif. chip), lastLogin recorded at exchange, "Used in…" link on the identities list; apps gate 4b, e2e-usedin.mjsmre
  • 349cb502tests/invites: wait for hydration on the code page before entering the code (native GET submit raced the welcome form); mission 015 reportmre
  • d1bf4720tests: no hard-coded ports — every gate's ports and fixture origins come from <GATE>_PORT / _CHROME env (defaults unchanged; Bob/fixture origins follow, selector cookie name too)mre
  • 6280c92fre-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • 147744bftests/migration: the fixture app origin follows MIGRATION_GATE_TESTAPP_PORT (oldstore-009 OLD_TESTAPP)mre
  • 48cd36bctests/migration: ports from env (MIGRATION_GATE_PORT, MIGRATION_GATE_TESTAPP_PORT); 8395/8396 were taken by a foreign servermre
  • 3d9b2fd8docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 19b7e3c3deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • c8a596f4re-vendor Hybriel 66c3db71 (web batch 4); e2e: main menu marked after in-place sign-in is a normal check; report 014mre
  • 8f3dc1ectests: delivery allow-list for the stopped server's network errors uses the gate port, not 8700mre