gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchf2-shellc3a40ff6|||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)mref2-shell/tests/selector.mjs

37.4 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. // the account's Sign out lives in the header's user menu (the home page's own buttons were dropped 2026-10-24: the same account was shown twice): a real tap on the icon, then on the entry
  115. const menuClick = async (page, id) => { await page.click('application-header user-menu > button'); await page.waitFor('document.querySelector("#user-menu").matches(":popover-open")', { label: 'user menu open' }); await page.click(id); };
  116. async function viewport(p, w) {
  117. await p.send('Emulation.setDeviceMetricsOverride', { width: w, height: w < 500 ? 844 : 900, deviceScaleFactor: 1, mobile: w < 500 });
  118. }
  119. async function shot(p, name) {
  120. for (const w of [390, 1280]) {
  121. await viewport(p, w);
  122. await sleep(200);
  123. const over = await p.evaluate('document.documentElement.scrollWidth > window.innerWidth');
  124. check(`${name} @${w}px: no horizontal overflow`, !over);
  125. const { data } = await p.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  126. writeFileSync(join(SHOTS, `selector-${name}-${w}.png`), Buffer.from(data, 'base64'));
  127. }
  128. await viewport(p, 1280);
  129. }
  130. const txt = (p, sel) => p.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || ''`);
  131. // INSIDE THE SELECTOR'S SHADOW ROOT
  132. const sh = (hostSel, expr) => `(() => { const h = document.querySelector(${J(hostSel)}); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;
  133. const shText = (p, inner, host = '#selector') => p.evaluate(sh(host, `(r.querySelector(${J(inner)}) || {}).textContent || ''`));
  134. const shNames = (p, host = '#selector') => p.evaluate(sh(host, `[...r.querySelectorAll('[part~="identity"]')].map(b => b.textContent)`));
  135. // a REAL click (Input domain) on an element inside the shadow root; `name` picks an
  136. // identity button by its text
  137. async function shClick(p, inner, { host = '#selector', name = null, timeout = 8000 } = {}) {
  138. const find = `(() => { const h = document.querySelector(${J(host)}); const r = h && h.shadowRoot; if (!r) return null; ` +
  139. `const el = ${name === null ? `r.querySelector(${J(inner)})` : `[...r.querySelectorAll(${J(inner)})].find(b => b.textContent === ${J(name)})`}; ` +
  140. `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 }; })()`;
  141. const box = await p.waitFor(find, { timeout, label: `shadow ${host} ${inner} ${name || ''}` });
  142. const base = { x: Math.round(box.x), y: Math.round(box.y), button: 'left', clickCount: 1 };
  143. await p.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...base, buttons: 0 });
  144. await p.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...base, buttons: 1 });
  145. await p.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...base, buttons: 0 });
  146. }
  147. const waitList = (p, host = '#selector') => p.waitFor(sh(host, `r.querySelectorAll('[part~="identity"]').length > 0`), { label: 'identity list in ' + host });
  148. const waitFrame = (p, host = '#selector') => p.waitFor(sh(host, `!!r.querySelector('#signin')`), { label: 'sign-in frame in ' + host });
  149. const waitMsg = (p, re, host = '#selector') => p.waitFor(sh(host, `/${re}/.test((r.querySelector('#message') || {}).textContent || '')`), { label: 'selector message ' + re });
  150. const shStyle = (p, inner, prop) => p.evaluate(sh('#selector', `getComputedStyle(r.querySelector(${J(inner)}))[${J(prop)}]`));
  151. let browser1, browser2;
  152. try {
  153. browser1 = await launchBrowser({ debugPortRange: CHROME_PORTS });
  154. browser2 = await launchBrowser({ debugPortRange: CHROME_PORTS });
  155. const p = live(await browser1.newPage()); pages.push(p);
  156. await viewport(p, 1280);
  157. // ==== 1. sign in to ident (on ident's origin), two identities, two apps ================
  158. console.log('# setup: ident account, identities, apps, test apps');
  159. const ALICE = '[email protected]';
  160. await p.goto(ID + '/');
  161. await p.waitForSelector('#email'); await ready(p);
  162. await p.type('#email', ALICE);
  163. await p.click('#sendcode');
  164. await p.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'code page' });
  165. await ready(p); // ident#20: the code step is its own page (/code) — wait for it to hydrate
  166. await p.type('#code', lastCode(ALICE));
  167. await p.click('#verify');
  168. await p.waitForSelector('#skip');
  169. await p.click('#skip');
  170. await p.waitFor('!document.querySelector("#identityform")');
  171. await p.click('#newidentity');
  172. await p.waitForSelector('#identityform');
  173. await p.type('#fidentityname', 'Work');
  174. await p.click('#saveidentity');
  175. await p.waitFor('document.querySelectorAll("#identities li").length === 2');
  176. const register = async (name, origins) => {
  177. await p.goto(ID + '/apps'); await p.waitForSelector('#newapp'); await ready(p);
  178. await p.click('#newapp');
  179. await p.waitForSelector('#appform');
  180. await p.type('#fappname', name);
  181. await p.type('#forigins', origins);
  182. await p.click('#saveapp');
  183. await p.waitForSelector('#secret');
  184. const secret = (await txt(p, '#secret')).trim();
  185. const keys = await p.evaluate('[...document.querySelectorAll("#apps .apikey")].map(e => e.textContent.trim())');
  186. await p.click('#secretdone');
  187. return { key: keys[keys.length - 1], secret };
  188. };
  189. const A = await register('Selector app A', TA);
  190. const B = await register('Selector app B', TB);
  191. 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]));
  192. evilKey = A.key;
  193. const setupApp = async (base, key, secret) => {
  194. await p.goto(base + '/');
  195. await p.type('#key', key, { clear: true });
  196. await p.type('#secret', secret, { clear: true });
  197. await p.evaluate('window.__old = 1');
  198. await p.click('#savesetup');
  199. await p.waitFor('!window.__old && document.readyState === "complete" && !!document.querySelector("#setupkey")', { label: 'setup saved' });
  200. check('test app ' + base + ' set up', (await txt(p, '#setupkey')) === key);
  201. };
  202. await setupApp(TA, A.key, A.secret);
  203. await setupApp(TB, B.key, B.secret);
  204. const aliceCookie = (await p.cookies([ID])).filter(c => c.name === 'identsid').map(c => 'identsid=' + c.value)[0];
  205. check('browser holds the ident session cookie (identsid)', !!aliceCookie);
  206. // ==== 2. the selector on the test app's page: closed, open, identities ================
  207. console.log('# selector: shown, opened, identities');
  208. await p.goto(TA + '/');
  209. await p.waitFor('!!customElements.get("ident-selector") && !!document.querySelector("#selector").shadowRoot', { label: 'selector defined' });
  210. check('the page includes ident\'s script', await p.evaluate(`!![...document.scripts].find(s => s.src === ${J(ID + '/selector.js')})`));
  211. check('selector is configured with the app\'s API key', (await p.evaluate('document.querySelector("#selector").getAttribute("key")')) === A.key);
  212. check('selector first says "choose ident"', (await shText(p, '#choose')).replace(/[▼▲]/g, '').trim() === 'choose ident', await shText(p, '#choose'));
  213. check('not logged in: no logged-in attribute', !(await p.evaluate('document.querySelector("#selector").hasAttribute("logged-in")')));
  214. check('shadow DOM in ident\'s design (accent #ce9178)', (await shStyle(p, '#choose', 'backgroundColor')) === 'rgb(206, 145, 120)', await shStyle(p, '#choose', 'backgroundColor'));
  215. await shot(p, 'closed');
  216. await shClick(p, '#choose');
  217. await waitList(p);
  218. const names = await shNames(p);
  219. check('open: the signed-in user\'s identities (identity names)', J(names) === J(['Default', 'Work']), J(names));
  220. await shot(p, 'open');
  221. // what ident answered (read by the page itself, as the script does)
  222. const listA = await p.evaluate(`fetch(${J(ID + '/api/selector/identities?key=' + A.key)}, { credentials: 'include' }).then(r => r.json())`);
  223. check('answer: only { signedIn, identities: [{ id, name }] }', listA.signedIn === true && listA.identities.every(i => J(Object.keys(i)) === '["id","name"]'), J(listA));
  224. 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));
  225. const noEmail = !J(listA).includes('alice');
  226. check('no email in the answer', noEmail);
  227. const toggleClosed = async () => { await shClick(p, '#choose'); await p.waitFor(sh('#selector', `!r.querySelector('#panel')`)); };
  228. await toggleClosed();
  229. check('clicking again closes it', true);
  230. // ==== 3. select = login, without a reload ============================================
  231. console.log('# select → code → host exchange → logged in without reload');
  232. await p.evaluate('window.__noReload = 1; window.__codes = []; document.querySelector("#selector").addEventListener("ident-login", e => window.__codes.push(e.detail.code))');
  233. const cookiesBefore = (await p.cookies([TA])).map(c => c.name).sort();
  234. await shClick(p, '#choose');
  235. await waitList(p);
  236. await shClick(p, '[part~="identity"]', { name: 'Work' });
  237. await p.waitFor('/Logged in/.test(document.querySelector("#loginstate").textContent) && !!document.querySelector("#identity")', { label: 'logged in via selector' });
  238. check('no reload happened', (await p.evaluate('window.__noReload')) === 1);
  239. const codes = await p.evaluate('window.__codes');
  240. check('ident-login event carried a one-time code (48 hex)', codes.length === 1 && /^[0-9a-f]{48}$/.test(codes[0]), J(codes));
  241. const idWork = (await txt(p, '#identity')).trim();
  242. check('host exchanged it: the identity\'s short id', /^[2-9a-hj-km-np-z]{5}$/.test(idWork), idWork);
  243. check('test app: new user', (await txt(p, '#userstate')) === 'new user');
  244. check('host set logged-in', await p.evaluate('document.querySelector("#selector").hasAttribute("logged-in") && document.querySelector("#selector").loggedIn === true'));
  245. const status = await shText(p, '#status');
  246. 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);
  247. check('logout offered', !(await p.evaluate('document.querySelector("#logout").hidden')));
  248. const cookiesAfter = (await p.cookies([TA])).map(c => c.name).sort();
  249. 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]));
  250. await shot(p, 'loggedin');
  251. const reuse = await exchange({ key: A.key, secret: A.secret, code: codes[0] });
  252. check('code reuse: the selector\'s code a second time → 400', reuse.status === 400 && /already used/.test(reuse.j.error), J(reuse));
  253. // the host knows its session: after a reload it renders logged-in itself
  254. await p.goto(TA + '/');
  255. await p.waitFor('!!customElements.get("ident-selector")');
  256. check('reload: host renders <ident-selector logged-in>', await p.evaluate('document.querySelector("#selector").hasAttribute("logged-in")'));
  257. check('reload: still logged in in the test app', /Logged in/.test(await txt(p, '#loginstate')));
  258. // ==== 4. host logout resets the selector =============================================
  259. console.log('# host logout');
  260. await p.evaluate('window.__noReload = 1');
  261. await p.click('#logout');
  262. await p.waitFor('/Not logged in/.test(document.querySelector("#loginstate").textContent)');
  263. check('logout: no reload', (await p.evaluate('window.__noReload')) === 1);
  264. 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')));
  265. await p.goto(TA + '/');
  266. await p.waitFor('!!customElements.get("ident-selector")');
  267. check('after logout + reload: not logged in', !(await p.evaluate('document.querySelector("#selector").hasAttribute("logged-in")')) && /Not logged in/.test(await txt(p, '#loginstate')));
  268. // ==== 5. the other identity, and the same one via the login button ===================
  269. console.log('# ids: per identity, same as the button flow');
  270. await shClick(p, '#choose');
  271. await waitList(p);
  272. await shClick(p, '[part~="identity"]', { name: 'Default' });
  273. await p.waitFor('!!document.querySelector("#identity")');
  274. const idDefault = (await txt(p, '#identity')).trim();
  275. 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]));
  276. await p.click('#logout');
  277. await p.waitFor('/Not logged in/.test(document.querySelector("#loginstate").textContent)');
  278. await p.click('#login');
  279. await p.waitForSelector('#chooselist'); await ready(p);
  280. await p.click('#chooselist li:nth-child(2) .choose');
  281. await p.waitFor(`location.href.startsWith(${J(TA + '/callback')}) && !!document.querySelector("#identity")`);
  282. check('login button with Work → the same id as the selector gave', (await txt(p, '#identity')).trim() === idWork && (await txt(p, '#userstate')) === 'welcome back');
  283. // app B: the same identity gets the same id there
  284. await p.goto(TB + '/');
  285. await shClick(p, '#choose');
  286. await waitList(p);
  287. const listB = await p.evaluate(`fetch(${J(ID + '/api/selector/identities?key=' + B.key)}, { credentials: 'include' }).then(r => r.json())`);
  288. check('list ids differ per app', listB.identities.every((x, i) => x.id !== listA.identities[i].id), J([listA, listB]));
  289. await shClick(p, '[part~="identity"]', { name: 'Work' });
  290. await p.waitFor('!!document.querySelector("#identity")');
  291. const idWorkB = (await txt(p, '#identity')).trim();
  292. check('same identity, app B → the SAME id', idWorkB === idWork);
  293. // ==== 6. restyle by the host =========================================================
  294. console.log('# restyle by the host');
  295. await p.goto(TA + '/');
  296. await p.waitFor('!!customElements.get("ident-selector")');
  297. // the login button above logged this browser in to the test app: log out first
  298. if (await p.evaluate('!document.querySelector("#logout").hidden')) {
  299. await p.click('#logout');
  300. await p.waitFor(sh('#selector', `!!r.querySelector('#choose')`), { label: 'selector reset' });
  301. }
  302. const before = { bg: await shStyle(p, '#choose', 'backgroundColor'), radius: await shStyle(p, '#choose', 'borderTopLeftRadius'), tt: await shStyle(p, '#choose', 'textTransform') };
  303. 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>')`);
  304. const after = { bg: await shStyle(p, '#choose', 'backgroundColor'), radius: await shStyle(p, '#choose', 'borderTopLeftRadius'), tt: await shStyle(p, '#choose', 'textTransform') };
  305. check('custom property --ident-accent changes the button colour', before.bg === 'rgb(206, 145, 120)' && after.bg === 'rgb(86, 155, 212)', J([before, after]));
  306. check('custom property --ident-radius changes the corners', before.radius !== '0px' && after.radius === '0px', J([before, after]));
  307. check('::part(button) restyles from the host', before.tt === 'none' && after.tt === 'uppercase', J([before, after]));
  308. await shClick(p, '#choose');
  309. await waitList(p);
  310. check('::part(identity) restyles the list', (await p.evaluate(sh('#selector', `getComputedStyle(r.querySelector('[part~="identity"]')).fontStyle`))) === 'italic');
  311. await shot(p, 'restyled-open');
  312. await p.evaluate('document.querySelector("#restyle").remove()');
  313. await toggleClosed();
  314. // ==== 7. negatives in the browser ====================================================
  315. console.log('# negatives: origin, key, signed out');
  316. // (a) an origin not registered for the app — same site, so the ident cookie DOES travel;
  317. // only the Origin check stops it
  318. await p.goto(EVIL + '/');
  319. await p.waitFor('!!customElements.get("ident-selector")');
  320. await shClick(p, '#choose');
  321. await waitMsg(p, 'does not answer this site');
  322. check('unregistered origin: no identities, an explanation', (await shNames(p)).length === 0);
  323. 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)`);
  324. check('unregistered origin: the browser gets nothing (CORS)', evilFetch === 'blocked: TypeError', evilFetch);
  325. 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)`);
  326. check('unregistered origin: choose blocked (preflight refused)', evilChoose === 'blocked: TypeError', evilChoose);
  327. await shot(p, 'unregistered');
  328. p.messages.splice(0); // the CORS refusals above are expected console errors
  329. // (b) wrong key on a registered origin: app B's key on app A's page, and a made-up key
  330. await p.goto(TA + '/');
  331. await p.waitFor('!!customElements.get("ident-selector")');
  332. const before2 = p.messages.length;
  333. for (const [label, key] of [["another app's key", B.key], ['an unknown key', 'pk_' + '0'.repeat(32)]]) {
  334. await p.evaluate(`document.querySelector("#other") && document.querySelector("#other").remove(); document.querySelector("#selectorbox").insertAdjacentHTML('beforeend', '<ident-selector id="other" key="${key}"></ident-selector>')`);
  335. await shClick(p, '#choose', { host: '#other' });
  336. await waitMsg(p, 'does not answer this site', '#other');
  337. check(`wrong key (${label}): no identities`, (await shNames(p, '#other')).length === 0);
  338. }
  339. p.messages.splice(before2);
  340. // (c) signed out of ident: the second browser has no ident session
  341. const q = live(await browser2.newPage()); pages.push(q);
  342. await viewport(q, 1280);
  343. await q.goto(TA + '/');
  344. await q.waitFor('!!customElements.get("ident-selector")');
  345. await shClick(q, '#choose');
  346. await waitFrame(q);
  347. check('signed out of ident: no identities, no new-tab link, ident\'s sign-in frame instead (ident#31)', (await shNames(q)).length === 0 && (await q.evaluate(sh('#selector', `!r.querySelector('a') && r.querySelector('iframe#signin').src.startsWith(${J(ID + '/embed/signin?key=' + A.key)})`))));
  348. const outList = await q.evaluate(`fetch(${J(ID + '/api/selector/identities?key=' + A.key)}, { credentials: 'include' }).then(r => r.json())`);
  349. 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));
  350. await shot(q, 'signedout');
  351. // ==== 8. the API directly: CORS headers, strict body, forged sessions ================
  352. console.log('# API: CORS, strict, forged sessions');
  353. let r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: TA, cookie: aliceCookie });
  354. 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}`);
  355. check('Vary: Origin, no Set-Cookie from the selector API', /Origin/.test(r.h.get('vary') || '') && !r.h.get('set-cookie'));
  356. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: EVIL, cookie: aliceCookie });
  357. 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}`);
  358. r = await call('GET', '/api/selector/identities?key=' + B.key, { origin: TA, cookie: aliceCookie });
  359. 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}`);
  360. r = await call('GET', '/api/selector/identities', { origin: TA, cookie: aliceCookie });
  361. check('no key: 403', r.status === 403, r.t);
  362. r = await call('GET', '/api/selector/identities?key=' + A.key, { cookie: aliceCookie });
  363. check('no Origin header: 403', r.status === 403, r.t);
  364. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: 'null', cookie: aliceCookie });
  365. check('Origin null: 403', r.status === 403, r.t);
  366. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: TA + '.evil.example', cookie: aliceCookie });
  367. check('origin with the registered one as prefix: 403', r.status === 403, r.t);
  368. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: TA, cookie: 'identsid=' + 'f'.repeat(32) });
  369. check('made-up ident cookie: signed out', r.status === 200 && r.j.signedIn === false, r.t);
  370. // IW (creator 2026-10-24): an app that runs on many addresses (gitoria: <repo>.gitoria.worldapi.org) registers ONE wildcard origin
  371. // `scheme://*.domain[:port]`; the selector then answers each ONE-label subdomain and nothing that only looks like one
  372. const WILD = 'http://*.wild.example:9999';
  373. const W = await register('Selector wildcard app', WILD);
  374. check('a wildcard origin can be registered (' + WILD + ')', /^pk_[0-9a-f]{32}$/.test(W.key), J(W));
  375. for (const [origin, want, why] of [['http://repo.wild.example:9999', 200, 'a one-label subdomain'], ['http://a-b-1.wild.example:9999', 200, 'a label with digits and hyphens'],
  376. ['http://a.b.wild.example:9999', 403, 'two labels'], ['http://wild.example:9999', 403, 'the bare domain'], ['http://evil-wild.example:9999', 403, 'a lookalike domain'],
  377. ['http://repo.wild.example:9998', 403, 'another port'], ['https://repo.wild.example:9999', 403, 'another scheme'], ['http://repo.wild.example:9999.evil.example', 403, 'the domain as a prefix'],
  378. ['http://.wild.example:9999', 403, 'an empty label'], ['http://-x.wild.example:9999', 403, 'a label starting with a hyphen'], ['http://re po.wild.example:9999', 403, 'a label with a space'], ['http://re.po.wild.example:9999', 403, 'a dot in the label']]) {
  379. r = await call('GET', '/api/selector/identities?key=' + W.key, { origin, cookie: aliceCookie });
  380. const okAcao = want === 200 ? r.h.get('access-control-allow-origin') === origin && r.h.get('access-control-allow-credentials') === 'true' : !r.h.get('access-control-allow-origin');
  381. check(`wildcard ${WILD}: ${why} (${origin}) → ${want}${want === 200 ? ' with ACAO = that exact origin' : ', no CORS headers'}`, r.status === want && okAcao, `${r.status} ${r.t}`);
  382. }
  383. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: 'http://repo.wild.example:9999', cookie: aliceCookie });
  384. check("the wildcard belongs to ITS app: another app's key from that origin: 403", r.status === 403 && !r.h.get('access-control-allow-origin'), `${r.status}`);
  385. r = await call('OPTIONS', '/api/selector/choose?key=' + W.key, { origin: 'http://repo.wild.example:9999', headers: { 'access-control-request-method': 'POST', 'access-control-request-headers': 'content-type' } });
  386. check('wildcard preflight from a subdomain: 204 + the exact origin', r.status === 204 && r.h.get('access-control-allow-origin') === 'http://repo.wild.example:9999', `${r.status}`);
  387. for (const bad of ['http://*.com', 'http://*.*.example.org', 'http://a.*.example.org', 'http://*example.org', 'http://*.', 'https://*.:443']) {
  388. const e = await emit('appCreate', [{ name: 'Wild refused', origins: [bad] }], aliceCookie);
  389. check(`a malformed wildcard origin is refused when an app is registered: ${bad}`, !!(e.value && e.value.error), e.raw);
  390. }
  391. r = await call('OPTIONS', '/api/selector/choose?key=' + A.key, { origin: TA, headers: { 'access-control-request-method': 'POST', 'access-control-request-headers': 'content-type' } });
  392. 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(' ')}`);
  393. r = await call('OPTIONS', '/api/selector/choose?key=' + A.key, { origin: EVIL });
  394. check('preflight from an unregistered origin: 403, no CORS headers', r.status === 403 && !r.h.get('access-control-allow-origin'), `${r.status}`);
  395. const pick = listA.identities[1].id; // Work
  396. const choose = (body, opt = {}) => call('POST', '/api/selector/choose?key=' + A.key, { origin: TA, cookie: aliceCookie, body, ...opt });
  397. r = await choose({ identity: pick });
  398. check('choose: 200 { code } only', r.status === 200 && J(Object.keys(r.j)) === '["code"]' && /^[0-9a-f]{48}$/.test(r.j.code), r.t);
  399. const code1 = r.j.code;
  400. let x = await exchange({ key: A.key, secret: A.secret, code: code1 });
  401. check('exchange of a selector code → the same id as in the browser', x.status === 200 && x.j.identity === idWork, J(x));
  402. x = await exchange({ key: A.key, secret: A.secret, code: code1 });
  403. check('the same code again → 400', x.status === 400, J(x));
  404. r = await choose({ identity: pick });
  405. x = await exchange({ key: B.key, secret: B.secret, code: r.j.code });
  406. 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));
  407. x = await exchange({ key: A.key, secret: A.secret, code: r.j.code });
  408. check('…and it is spent', x.status === 400, J(x));
  409. r = await choose({ identity: pick }, { origin: EVIL });
  410. check('choose from an unregistered origin: 403, no code', r.status === 403 && !r.t.includes('code"'), r.t);
  411. r = await choose({ identity: pick }, { cookie: undefined });
  412. check('choose without an ident session: 401', r.status === 401, r.t);
  413. r = await choose({ identity: pick, session: { user: { id: 1 } } }, { cookie: undefined });
  414. check('forged session in the body: refused (unknown field)', r.status === 400 && r.j.error === 'unknown field: session', r.t);
  415. r = await choose({ identity: pick, user: { id: 1 } });
  416. check('unknown field: named', r.status === 400 && r.j.error === 'unknown field: user', r.t);
  417. r = await choose({});
  418. check('missing identity: named', r.status === 400 && r.j.error === 'missing field: identity', r.t);
  419. r = await choose({ identity: 2 });
  420. check('identity of the wrong type: named', r.status === 400 && /field identity must be a string/.test(r.j.error), r.t);
  421. r = await choose('{"identity": ');
  422. check('invalid JSON: 400', r.status === 400 && /not valid JSON/.test(r.j.error), r.t);
  423. r = await choose('["x"]');
  424. check('not an object: 400', r.status === 400, r.t);
  425. // ident's own identity ids (UUIDs since mission 009) as the SSR page renders them in the Edit buttons
  426. const ownIds = [...new Set([...(await (await fetch(ID + '/', { headers: { cookie: aliceCookie } })).text()).matchAll(/value="([0-9a-z]{12})"/g)].map(m => m[1]))];
  427. check("alice's ident identity ids read off / (2, UUIDs)", ownIds.length === 2, J(ownIds));
  428. r = await choose({ identity: ownIds[0] || 'x' });
  429. check("ident's own identity id is not accepted as a pick: 400", r.status === 400 && r.j.error === 'no such identity', r.t);
  430. r = await choose({ identity: '2' });
  431. check("an old numeric identity id is not accepted as a pick: 400", r.status === 400 && r.j.error === 'no such identity', r.t);
  432. r = await choose({ identity: listB.identities[1].id });
  433. check("app B's pick on app A: 400", r.status === 400, r.t);
  434. r = await call('GET', '/api/selector/choose?key=' + A.key, { origin: TA, cookie: aliceCookie });
  435. check('GET choose: 405', r.status === 405, r.t);
  436. r = await call('POST', '/api/selector/identities?key=' + A.key, { origin: TA, cookie: aliceCookie, body: {} });
  437. check('POST identities: 405', r.status === 405, r.t);
  438. // another account: bob's session cannot use alice's pick
  439. // (bob logs in over the emit carrier with the cookie the first frame got)
  440. // (mission 010: the code comes from POST /api/code; the verifyCode frame mints the cookie)
  441. await fetch(ID + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email: '[email protected]' }) });
  442. 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'] }) });
  443. const bCookie = (vBr.headers.get('set-cookie') || '').split(';')[0];
  444. const vBt = await vBr.text();
  445. const vB = { value: (JSON.parse(vBt) || {}).value, raw: vBt };
  446. check('bob signed in (emit carrier)', !!(vB.value && vB.value.account), vB.raw);
  447. r = await choose({ identity: pick }, { cookie: bCookie });
  448. check("another account cannot choose alice's identity", r.status === 400 && r.j.error === 'no such identity', r.t);
  449. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: TA, cookie: bCookie });
  450. 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);
  451. // #31: the faces still refuse a forged trailing session argument
  452. const forged = { user: { id: 1 } };
  453. 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]]]) {
  454. const f = await emit(ev, [...args, forged]);
  455. check(`forged session argument refused (#31): ${ev}`, framework_refused(f.raw) || (f.value && /not signed in/.test(f.value.error)), f.raw);
  456. }
  457. // ident sign-out in browser 1 → the selector there gets nothing either
  458. await p.goto(ID + '/'); await ready(p);
  459. await menuClick(p, '#menusignout');
  460. await p.waitForSelector('#email');
  461. await p.goto(TA + '/');
  462. await p.waitFor('!!customElements.get("ident-selector")');
  463. await shClick(p, '#choose');
  464. await waitFrame(p);
  465. check('after signing out of ident: no identities', (await shNames(p)).length === 0);
  466. r = await call('GET', '/api/selector/identities?key=' + A.key, { origin: TA, cookie: aliceCookie });
  467. check('after signing out of ident: the old cookie gets signedIn false', r.status === 200 && r.j.signedIn === false, r.t);
  468. // ==== 9. console =====================================================================
  469. const probs = pages.flatMap(pg => pg.problems().map(m => m.text));
  470. check('no console errors or warnings (besides the expected CORS refusals)', probs.length === 0, probs.join(' | '));
  471. } catch (err) {
  472. failed++;
  473. console.log(' FAIL (aborted) ' + (err && err.stack || err));
  474. for (const pg of pages) console.log('--- console:\n' + pg.dumpConsole());
  475. } finally {
  476. for (const b of [browser1, browser2]) { if (b) { try { await b.close(); } catch {} } }
  477. for (const { p } of procs) { try { p.kill(); } catch {} }
  478. evil.close();
  479. await sleep(300);
  480. }
  481. console.log(`\n${passed} passed, ${failed} failed`);
  482. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • 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
  • ec6aad35Merge branch 'a28g-amp-callsites' into d45-docsmre
  • 6bfbd3f2ident#45: docs/IDENT.md, what ident is and how it works; CONCEPT.md marks one id per app as droppedmre