gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit94576fbc94576fbcident#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.mjsmre94576fbc/tests/selector.mjs

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

Branches

Latest commits

  • 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
  • 9cc8eddftests: notify and iplimit gate Chrome ports from env (NOTIFY_GATE_CHROME, IPLIMIT_GATE_CHROME_A/B)mre
  • d6da2d02tests: delivery and migration gate ports from env (DELIVERY_GATE_PORT, DELIVERY_GATE_CHROME, MIGRATION_GATE_CHROME) — hard-coded 8700-8719 collided with a worker during deploymre
  • 7276a008ident mission 013: re-vendor Hybriel master f9614007 (#200, #202 mpackdb copy fix); gates and e2e rerunmre
  • e13e30c3ident mission 013: report, mission, repro, LOGmre
  • eff734f3ident mission 013: in-place sign-out also closes the code step (no leftover code form); checksmre
  • b7a61546ident mission 013: e2e — in-place main-menu mark kept as a known gapmre
  • 59b43d81ident mission 013: sign out everywhere keeps this browser's own (signed-out) session so the page goes on in placemre
  • 716e14ffident mission 013: browser gate — Bob signs out everywhere (no second code request)mre
  • 5885f1c9ident mission 013 step 2: stopgap reload removed (in-place sign-in/out reach the shell via emit, notices back, route-marked main menu), gates updatedmre
  • 734ac0a9ident mission 013 step 1: re-vendor Hybriel ce6f2e0a (plugins whole; bin/ is git-ignored)mre