gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain0f6d1592Merge branch 'f18b-shell-session' into mainIdentmain/tests/signin.mjs

25.6 KB

  1. // tests/signin.mjs — THE GATE OF ident#31: signing in to ident INSIDE the identity selector's panel. Real headless Chrome (tests/cdp.mjs).
  2. // A signed-out visitor opens the selector on an app's page: the panel holds ident's /embed/signin in an iframe (email → code → identity,
  3. // "This signs you in to ident."); choosing an identity takes the whole page to the app's return URL with ident_code and the app logs
  4. // the user in. A NEW address is sent on to ident in the same tab (/signin/<rid>/welcome), names/picks its identity there and is sent back.
  5. // Framing is allowed for the app's registered origins only. Own servers (NEVER the dev server, NEVER real mail):
  6. // ident :8700 (IDENT_MAIL_SINK), test app A :8701 (registered), an unregistered origin :8702 that frames the sign-in page
  7. // Chrome debug ports 8710-8719. Storage .scratch/signin-gate (wiped at start). Shots .scratch/signin-*.png (390 and 1280 px).
  8. // Run: node tests/signin.mjs (SIGNIN_GATE_APP=<other checkout> runs the same checks against that code, e.g. main: they must fail)
  9. import { spawn } from 'node:child_process';
  10. import { createServer } from 'node:http';
  11. import { readFileSync, writeFileSync, rmSync, mkdirSync, existsSync } from 'node:fs';
  12. import { dirname, join } from 'node:path';
  13. import { fileURLToPath } from 'node:url';
  14. import { launchBrowser, sleep } from './cdp.mjs';
  15. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  16. const APP = process.env.SIGNIN_GATE_APP || join(dirname(fileURLToPath(import.meta.url)), '..');
  17. const G = join(APP, '.scratch/signin-gate');
  18. const SHOTS = process.env.SIGNIN_SHOTS || join(APP, '.scratch');
  19. mkdirSync(SHOTS, { recursive: true });
  20. const P0 = Number(process.env.SIGNIN_GATE_PORT || 8700);
  21. const ID = 'http://127.0.0.1:' + P0, TA = 'http://127.0.0.1:' + (P0 + 1), EVIL = 'http://127.0.0.1:' + (P0 + 2);
  22. const CHROME_PORTS = (process.env.SIGNIN_GATE_CHROME || '8710-8719').split('-').map(Number);
  23. const J = JSON.stringify;
  24. let passed = 0, failed = 0;
  25. const check = (name, ok, detail = '') => { if (ok) { passed++; console.log(' ok ' + name); } else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); } };
  26. const procs = [];
  27. function start(cwd, env, log) {
  28. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd, env: { ...process.env, SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', ...env }, stdio: ['ignore', 'pipe', 'pipe'] });
  29. let out = ''; p.stdout.on('data', d => { out += d; }); p.stderr.on('data', d => { out += d; });
  30. p.on('exit', () => writeFileSync(join(G, log), out));
  31. p.getOut = () => out; p.logName = log;
  32. procs.push(p); return p;
  33. }
  34. async function up(url) {
  35. 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); }
  36. throw new Error('server did not come up: ' + url);
  37. }
  38. rmSync(G, { recursive: true, force: true });
  39. mkdirSync(join(G, 'main'), { recursive: true });
  40. start(APP, { IDENT_PORT: String(P0), IDENT_STORAGE: join(G, 'main', 'ident'), IDENT_SESSIONS: join(G, 'main', 'sess') + '/', IDENT_MAIL_SINK: join(G, 'main', 'mail.txt'), IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000' }, 'ident.log');
  41. start(join(APP, 'testapp'), { TESTAPP_PORT: String(P0 + 1), TESTAPP_URL: TA, IDENT_URL: ID, TESTAPP_STORE: join(G, 'testapp-a.json') }, 'testapp.log');
  42. let evilKey = '';
  43. const evil = createServer((req, res) => {
  44. res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
  45. res.end(`<!doctype html><html><head><meta charset="utf-8"><title>not registered</title></head><body style="background:#222"><iframe id="f" width="360" height="400" src="${ID}/embed/signin?key=${evilKey}&return=${encodeURIComponent(TA + '/callback')}"></iframe></body></html>`);
  46. });
  47. await new Promise(r => evil.listen(P0 + 2, '127.0.0.1', r));
  48. await Promise.all([up(ID), up(TA)]);
  49. const lastCode = (email) => {
  50. const lines = readFileSync(join(G, 'main', 'mail.txt'), 'utf8').trim().split('\n').filter(l => l.startsWith(email + ' '));
  51. return lines.length ? lines[lines.length - 1].split(' ')[1] : null;
  52. };
  53. const sh = (hostSel, expr) => `(() => { const h = document.querySelector(${J(hostSel)}); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;
  54. async function ready(p) { await p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated' }); }
  55. async function viewport(p, w) { await p.send('Emulation.setDeviceMetricsOverride', { width: w, height: w < 500 ? 844 : 900, deviceScaleFactor: 1, mobile: w < 500 }); }
  56. // ---- driving the IFRAME: its JS worlds come from Runtime.executionContextCreated, its pointer input is the top page's -------------
  57. const worlds = new Map(); // sessionId → Map(frameId → contextId of the page's main world)
  58. function trackWorlds(p) {
  59. const m = new Map(); worlds.set(p, m);
  60. p.conn.onEvent((msg) => {
  61. if (msg.sessionId !== p.sessionId) return;
  62. const c = msg.params && msg.params.context;
  63. if (msg.method === 'Runtime.executionContextCreated' && c && c.auxData && c.auxData.isDefault) m.set(c.auxData.frameId, c.id);
  64. if (msg.method === 'Runtime.executionContextDestroyed') for (const [f, id] of m) if (id === msg.params.executionContextId) m.delete(f);
  65. if (msg.method === 'Runtime.executionContextsCleared') m.clear();
  66. });
  67. return p.send('Runtime.enable');
  68. }
  69. async function childFrame(p) {
  70. const t = await p.send('Page.getFrameTree');
  71. const c = (t.frameTree.childFrames || [])[0];
  72. return c ? c.frame : null;
  73. }
  74. async function fEval(p, expr) {
  75. const f = await childFrame(p);
  76. if (!f) throw new Error('no frame');
  77. const id = worlds.get(p).get(f.id);
  78. if (!id) throw new Error('no context for the frame');
  79. const r = await p.send('Runtime.evaluate', { contextId: id, expression: expr, returnByValue: true, awaitPromise: true });
  80. if (r.exceptionDetails) throw new Error('frame evaluate threw: ' + ((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || r.exceptionDetails.text));
  81. return r.result.value;
  82. }
  83. async function fWait(p, expr, { timeout = 15000, label = '' } = {}) {
  84. const end = Date.now() + timeout; let last;
  85. while (Date.now() < end) { try { last = await fEval(p, expr); if (last) return last; } catch (e) { last = e.message; } await sleep(80); }
  86. let t = ''; try { t = await fEval(p, "document.body.innerText + ' || code=' + ((document.querySelector('#code') || {}).value)"); } catch {}
  87. throw new Error('frame waitFor timed out: ' + (label || expr.slice(0, 100)) + ' (' + last + ') frame text: ' + t);
  88. }
  89. const fReady = async (p) => {
  90. try { return await fWait(p, `!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, { label: 'frame hydrated' }); }
  91. catch (e) { throw new Error(e.message + ' :: ' + await fEval(p, `location.href + ' | ' + typeof window.__hl + ' | ' + (window.__hl && window.__hl.socket && window.__hl.socket.readyState) + ' | ' + [...document.scripts].map(s => s.type + ':' + (s.src || s.text.length)).join(',') + ' | seed ' + !!document.getElementById('hl-seed') + ' | ' + document.body.innerHTML.slice(-200)`)); }
  92. };
  93. async function frameOffset(p) { // the iframe's top-left in the top viewport
  94. return p.evaluate(sh('#selector', `(() => { const b = r.querySelector('iframe#signin').getBoundingClientRect(); return { x: b.left, y: b.top, w: b.width, h: b.height }; })()`));
  95. }
  96. async function fBox(p, sel) {
  97. const b = await fEval(p, `(() => { const el = document.querySelector(${J(sel)}); if (!el) return null; el.scrollIntoView({ block: 'center' }); const r = el.getBoundingClientRect(); return r.width ? { x: r.left + r.width / 2, y: r.top + r.height / 2, w: r.width, h: r.height } : null; })()`);
  98. if (!b) throw new Error('no box for ' + sel);
  99. return b;
  100. }
  101. async function fClick(p, sel) {
  102. await fWait(p, `!!document.querySelector(${J(sel)})`, { label: sel });
  103. const b = await fBox(p, sel), o = await frameOffset(p);
  104. const base = { x: Math.round(o.x + b.x), y: Math.round(o.y + b.y), button: 'left', clickCount: 1 };
  105. await p.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...base, buttons: 0 });
  106. await p.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...base, buttons: 1 });
  107. await p.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...base, buttons: 0 });
  108. }
  109. async function fType(p, sel, text) {
  110. await fClick(p, sel);
  111. for (const ch of text) {
  112. await p.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  113. await p.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  114. }
  115. }
  116. async function shClick(p, inner) {
  117. const box = await p.waitFor(sh('#selector', `(() => { const el = r.querySelector(${J(inner)}); if (!el) return null; el.scrollIntoView({ block: 'center' }); const b = el.getBoundingClientRect(); return b.width ? { x: b.left + b.width / 2, y: b.top + b.height / 2 } : null; })()`), { label: 'shadow ' + inner });
  118. const base = { x: Math.round(box.x), y: Math.round(box.y), button: 'left', clickCount: 1 };
  119. await p.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...base, buttons: 0 });
  120. await p.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...base, buttons: 1 });
  121. await p.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...base, buttons: 0 });
  122. }
  123. async function shot(p, name) {
  124. for (const w of [390, 1280]) {
  125. await viewport(p, w); await sleep(300);
  126. const over = await p.evaluate('document.documentElement.scrollWidth > window.innerWidth');
  127. check(`${name} @${w}px: the page does not overflow sideways`, !over);
  128. const { data } = await p.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  129. writeFileSync(join(SHOTS, `signin-${name}-${w}.png`), Buffer.from(data, 'base64'));
  130. }
  131. await viewport(p, 1280);
  132. }
  133. // every control of the frame: at least 44 px tall (taps) and inside the frame's width
  134. async function controlsOk(p, label) {
  135. const rows = await fEval(p, `[...document.querySelectorAll('input, button, a.button, #chooselist a')].filter(e => e.getBoundingClientRect().width).map(e => { const r = e.getBoundingClientRect(); return { id: e.id || e.className || e.tagName, h: Math.round(r.height), w: Math.round(r.width), right: Math.round(r.right), vw: innerWidth }; })`);
  136. const bad = rows.filter(r => r.h < 44 || r.right > r.vw);
  137. check(`${label}: every control is at least 44 px tall and inside the frame`, rows.length > 0 && bad.length === 0, J(bad.length ? bad : rows));
  138. }
  139. // the frame is exactly as tall as the current step (ident#31 follow-up SC): the page reports its height to the selector (postMessage), the
  140. // selector sets the frame height. At each width every step's content height is recorded together with the frame's height;
  141. // fitCheck() compares them per step after the last one (content + the card's own 8 px padding, no empty space below)
  142. const FIT = { 390: [], 1280: [] };
  143. async function fitRecord(p, label) {
  144. const w0 = await p.evaluate('innerWidth');
  145. for (const w of [390, 1280]) {
  146. await viewport(p, w); await sleep(1600);
  147. const content = await fEval(p, `Math.ceil(Math.max(...[...document.querySelectorAll('main *')].filter(e => e.getBoundingClientRect().height && e.tagName !== 'EMBED-CARD' && e.tagName !== 'MAIN' && e.id !== 'message').map(e => e.getBoundingClientRect().bottom)) + scrollY)`);
  148. const frame = await p.evaluate(sh('#selector', `r.querySelector('iframe').offsetHeight`));
  149. FIT[w].push({ label, content, frame });
  150. }
  151. await viewport(p, w0 > 500 ? 1280 : 390);
  152. }
  153. function fitCheck() {
  154. for (const w of [390, 1280]) {
  155. for (const r of FIT[w]) check(`@${w}px ${r.label} step: the frame (${r.frame} px) is as tall as its content (${r.content} px) plus the 8 px card padding, no empty space below`, r.frame >= r.content && r.frame <= r.content + 12, J(r));
  156. }
  157. }
  158. let browser1, browser2, browser3, browser4;
  159. const pages = [];
  160. try {
  161. for (const k of [1, 2, 3, 4]) {
  162. const b = await launchBrowser({ debugPortRange: CHROME_PORTS });
  163. if (k === 1) browser1 = b; if (k === 2) browser2 = b; if (k === 3) browser3 = b; if (k === 4) browser4 = b;
  164. }
  165. const mk = async (b) => { const pg = await b.newPage(); pages.push(pg); await trackWorlds(pg); await viewport(pg, 1280); return pg; };
  166. const p = await mk(browser1);
  167. // ==== setup: alice's account (signed in on ident), the app, the test app =============
  168. console.log('# setup');
  169. const ALICE = '[email protected]', BOB = '[email protected]';
  170. await p.goto(ID + '/'); await p.waitForSelector('#email'); await ready(p);
  171. await p.type('#email', ALICE); await p.click('#sendcode');
  172. await p.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")'); await ready(p);
  173. await p.type('#code', lastCode(ALICE)); await p.click('#verify');
  174. await p.waitForSelector('#skip'); await p.click('#skip');
  175. await p.waitFor('!document.querySelector("#identityform")');
  176. await p.click('#newidentity'); await p.waitForSelector('#identityform');
  177. await p.type('#fidentityname', 'Work'); await p.click('#saveidentity');
  178. await p.waitFor('document.querySelectorAll("#identities li").length === 2');
  179. await p.goto(ID + '/apps'); await p.waitForSelector('#newapp'); await ready(p);
  180. await p.click('#newapp'); await p.waitForSelector('#appform');
  181. await p.type('#fappname', 'Signin app'); await p.type('#forigins', TA);
  182. await p.click('#saveapp'); await p.waitForSelector('#secret');
  183. const secret = (await p.text('#secret')).trim();
  184. const key = await p.evaluate('[...document.querySelectorAll("#apps app-key code")].map(e => e.textContent.trim()).pop()');
  185. await p.click('#secretdone');
  186. check('app registered', /^pk_[0-9a-f]{32}$/.test(key), key);
  187. evilKey = key;
  188. await p.goto(TA + '/');
  189. await p.type('#key', key, { clear: true }); await p.type('#secret', secret, { clear: true });
  190. await p.evaluate('window.__old = 1'); await p.click('#savesetup');
  191. await p.waitFor('!window.__old && document.readyState === "complete" && !!document.querySelector("#setupkey")');
  192. // ==== the headers of the frame page ====================================================
  193. console.log('# who may frame the page');
  194. const ret = encodeURIComponent(TA + '/callback');
  195. const fr = await fetch(`${ID}/embed/signin?key=${key}&return=${ret}`);
  196. const csp = fr.headers.get('content-security-policy') || '';
  197. check('/embed/signin answers 200 and may be framed by the app\'s origin only', fr.status === 200 && new RegExp('frame-ancestors http://127\\.0\\.0\\.1:' + (P0 + 1) + '(;|$)').test(csp) && !fr.headers.get('x-frame-options'), `${fr.status} ${csp} xfo=${fr.headers.get('x-frame-options')}`);
  198. const badRet = await fetch(`${ID}/embed/signin?key=${key}&return=${encodeURIComponent(EVIL + '/x')}`);
  199. check('a return URL outside the app\'s origins: 400 error page, never framed', badRet.status === 400 && /frame-ancestors 'none'/.test(badRet.headers.get('content-security-policy') || ''), String(badRet.status));
  200. const badKey = await fetch(`${ID}/embed/signin?key=pk_${'0'.repeat(32)}&return=${ret}`);
  201. check('an unknown key: 400', badKey.status === 400);
  202. const post = await fetch(`${ID}/embed/signin?key=${key}&return=${ret}`, { method: 'POST' });
  203. check('POST: 405', post.status === 405);
  204. // ==== the scripts reach browsers at once after a deploy: revalidate every load, 304 when unchanged ====
  205. console.log('# cache headers of the widget script');
  206. for (const path of ['/selector.js']) {
  207. const r1 = await fetch(ID + path);
  208. const cc = r1.headers.get('cache-control') || '', et = r1.headers.get('etag') || r1.headers.get('last-modified') || '';
  209. check(`${path}: Cache-Control has no-cache (and no max-age) and there is a validator`, /no-cache/.test(cc) && !/max-age=[1-9]/.test(cc) && et !== '', cc + ' | ' + et);
  210. const r2 = await fetch(ID + path, { headers: r1.headers.get('etag') ? { 'If-None-Match': r1.headers.get('etag') } : { 'If-Modified-Since': r1.headers.get('last-modified') || '' } });
  211. check(`${path}: a repeat request with the validator answers 304 with no body`, r2.status === 304 && (await r2.text()) === '', String(r2.status));
  212. }
  213. const avatarScript = await fetch(ID + '/avatar.js');
  214. check('avatar script was removed: /avatar.js answers 404', avatarScript.status === 404);
  215. const homeHtml = await (await fetch(ID + '/')).text();
  216. check('the shell loads no hand-written avatar script', !homeHtml.includes('/avatar.js'));
  217. // ==== A. a known address, signed out: email → code → identity → signed in on the app ======
  218. console.log('# A: known address, all in the selector panel');
  219. const q = await mk(browser2);
  220. await q.goto(TA + '/');
  221. await q.waitFor('!!customElements.get("ident-selector") && !!document.querySelector("#selector").shadowRoot');
  222. await shClick(q, '#choose');
  223. await q.waitFor(sh('#selector', `!!r.querySelector('iframe#signin') || !!r.querySelector('#message')`), { label: 'the signed-out panel' });
  224. await sleep(1500);
  225. await shot(q, 'step0-panel');
  226. check('signed out: the panel holds ident\'s sign-in frame and no new-tab link', await q.evaluate(sh('#selector', `!r.querySelector('a[target=_blank]') && r.querySelector('iframe#signin').src.startsWith(${J(ID + '/embed/signin?key=' + key)})`)));
  227. await fReady(q); await fWait(q, '!!document.querySelector("#email")');
  228. check('the frame says it signs the user in to ident', /This signs you in to ident\./.test(await fEval(q, 'document.body.innerText')));
  229. await shot(q, 'step1-email');
  230. await controlsOk(q, 'email step');
  231. await fitRecord(q, 'email');
  232. const h0 = await q.evaluate(sh('#selector', `r.querySelector('iframe').offsetHeight`));
  233. await q.evaluate(`postMessage({ identFrameHeight: 2500 }, '*')`); await sleep(500);
  234. check('a height message from another window (not ident\'s frame) is ignored', (await q.evaluate(sh('#selector', `r.querySelector('iframe').offsetHeight`))) === h0, String(h0));
  235. await fType(q, '#email', ALICE);
  236. await fClick(q, '#sendcode');
  237. await fWait(q, '!!document.querySelector("#code")', { label: 'code field' });
  238. check('code step: the same page, the address shown', /alice@example\.org/.test(await fEval(q, 'document.body.innerText')));
  239. await shot(q, 'step2-code');
  240. await controlsOk(q, 'code step');
  241. await fitRecord(q, 'code');
  242. await fType(q, '#code', lastCode(ALICE));
  243. await fClick(q, '#verify');
  244. await fWait(q, 'document.querySelectorAll("#chooselist li").length === 2 || /wrong|expired|error|refused/.test(document.body.innerText)', { label: 'identity list in the frame' });
  245. check('the right code lists both identities', (await fEval(q, 'document.querySelectorAll("#chooselist li").length')) === 2, await fEval(q, 'document.body.innerText'));
  246. const labels = await fEval(q, '[...document.querySelectorAll("#chooselist :is(a, button)")].map(a => a.tagName + "|" + a.target + "|" + a.querySelectorAll("identity-label").length).join(",")');
  247. check('identity step: each identity is one plain target=_top link holding its own label, no extra button (C31, ident#47)', labels === 'A|_top|1,A|_top|1', labels);
  248. check('identity step: no "Continue" anywhere in the frame (C31, ident#47)', !/continue/i.test(await fEval(q, 'document.body.innerText')), await fEval(q, 'document.body.innerText'));
  249. await shot(q, 'step3-identity');
  250. await controlsOk(q, 'identity step');
  251. await fitRecord(q, 'identity');
  252. await q.evaluate('window.__still = 1');
  253. check('app tests hook: every identity in the frame has #chooselist li .choose (ident#34, docs/IDENT.md)', (await fEval(q, 'document.querySelectorAll("#chooselist li .choose").length')) === 2);
  254. await fClick(q, '#chooselist li:nth-child(2) .choose');
  255. await q.waitFor(`location.href.startsWith(${J(TA + '/callback')}) && !!document.querySelector("#identity")`, { label: 'back on the app, signed in' });
  256. check('the whole app page went to its return URL and the app logged the user in', /^[2-9a-hj-km-np-z]{5}$/.test((await q.text('#identity')).trim()) && (await q.text('#userstate')) === 'new user');
  257. const idWork = (await q.text('#identity')).trim();
  258. check('the cookie of ident was set by the frame (a second visit lists the identities in the selector, no frame)', await (async () => {
  259. await q.goto(TA + '/');
  260. await q.waitFor('!!customElements.get("ident-selector") && !!document.querySelector("#selector").shadowRoot');
  261. await q.evaluate('document.querySelector("#selector").loggedIn = false; document.querySelector("#logout") && document.querySelector("#logout").click()');
  262. await q.goto(TA + '/');
  263. await q.waitFor('!!customElements.get("ident-selector") && !!document.querySelector("#selector").shadowRoot');
  264. await shClick(q, '#choose');
  265. return q.waitFor(sh('#selector', `r.querySelectorAll('[part~="identity"]').length === 2 && !r.querySelector('iframe')`), { label: 'list' });
  266. })());
  267. // a wrong code stays in the frame
  268. console.log('# wrong code, other address');
  269. const w = await mk(browser3);
  270. await w.goto(TA + '/'); await w.waitFor('!!customElements.get("ident-selector") && !!document.querySelector("#selector").shadowRoot');
  271. await shClick(w, '#choose'); await w.waitFor(sh('#selector', `!!r.querySelector('iframe#signin')`));
  272. await fReady(w); await fWait(w, '!!document.querySelector("#email")');
  273. await fType(w, '#email', ALICE); await fClick(w, '#sendcode'); await fWait(w, '!!document.querySelector("#code")');
  274. await fType(w, '#code', '000000'); await fClick(w, '#verify');
  275. await fWait(w, '/wrong code/.test(document.querySelector("#message").textContent)', { label: 'wrong code message' });
  276. check('a wrong code: the message in the frame, still signed out', true);
  277. await fClick(w, '#back');
  278. await fWait(w, '!!document.querySelector("#email")', { label: 'back to the email step' });
  279. check('"Other address" goes back to the email field in the frame', true);
  280. // ==== B. an unknown address: sent to ident in the same tab, back on the app ================
  281. console.log('# B: unknown address → ident → back signed in');
  282. const b = await mk(browser4);
  283. await b.goto(TA + '/'); await b.waitFor('!!customElements.get("ident-selector") && !!document.querySelector("#selector").shadowRoot');
  284. await shClick(b, '#choose'); await b.waitFor(sh('#selector', `!!r.querySelector('iframe#signin')`));
  285. await fReady(b); await fWait(b, '!!document.querySelector("#email")');
  286. await fType(b, '#email', BOB); await fClick(b, '#sendcode'); await fWait(b, '!!document.querySelector("#code")');
  287. await fType(b, '#code', lastCode(BOB)); await fClick(b, '#verify');
  288. await fWait(b, '!!document.querySelector("#gonew")', { label: 'new-address step' });
  289. check('a new address: the frame says it needs an identity on ident and links the top window there', (await fEval(b, 'document.querySelector("#gonew").target + "|" + document.querySelector("#gonew").getAttribute("href")')).startsWith('_top|/signin/'));
  290. await shot(b, 'step3-new');
  291. await controlsOk(b, 'new-address step');
  292. await fitRecord(b, 'new');
  293. await fClick(b, '#gonew');
  294. await b.waitFor(`location.origin === ${J(ID)} && /\\/signin\\/[0-9a-f]{32}\\/welcome$/.test(location.pathname) && !!document.querySelector("#identityform")`, { label: 'ident welcome form in the top window' });
  295. await ready(b);
  296. check('the same tab is on ident, the default identity\'s name form is open', await b.evaluate('!!document.querySelector("#welcome") && !!document.querySelector("#skip")'));
  297. await b.type('#fidentityname', 'Bob');
  298. await b.click('#saveidentity');
  299. await b.waitForSelector('#chooselist');
  300. check('then the identity choice for the app', (await b.text('#appname')).trim() === 'Signin app' && (await b.evaluate('document.querySelectorAll("#chooselist li").length')) === 1);
  301. check('app tests hook: the identity choice on ident has #chooselist li .choose (ident#34, docs/IDENT.md)', (await b.evaluate('document.querySelectorAll("#chooselist li .choose").length')) === 1);
  302. await b.click('#chooselist li .choose');
  303. await b.waitFor(`location.href.startsWith(${J(TA + '/callback')}) && !!document.querySelector("#identity")`, { label: 'back on the app' });
  304. check('sent back to the app, signed in as a new user', (await b.text('#userstate')) === 'new user' && /^[2-9a-hj-km-np-z]{5}$/.test((await b.text('#identity')).trim()));
  305. // ==== C. a page of an unregistered origin cannot frame it ===================================
  306. console.log('# C: unregistered origin');
  307. const e = await mk(browser3);
  308. await e.goto(EVIL + '/');
  309. await sleep(1500);
  310. const ef = await childFrame(e);
  311. const loaded = ef ? await (async () => { try { const id = worlds.get(e).get(ef.id); if (!id) return false; const r = await e.send('Runtime.evaluate', { contextId: id, expression: '!!document.querySelector("#email")', returnByValue: true }); return r.result.value === true; } catch { return false; } })() : false;
  312. check('the framed sign-in page does not load on an unregistered origin (no email field, the browser blocks it)', !loaded, ef ? ef.url : 'no frame');
  313. await sleep(100);
  314. const log = e.messages.map(m => m.text).join('\n');
  315. check('the browser reported the frame-ancestors refusal', /frame-ancestors|Refused to frame/.test(log) || ef == null || /chrome-error/.test(ef.url || ''), log.slice(0, 200));
  316. // ==== D. console ==========================================================================
  317. const probs = pages.flatMap(pg => pg.problems().map(m => m.text)).filter(t => !/Refused to frame|frame-ancestors|ERR_BLOCKED|Failed to load resource/.test(t));
  318. check('no console errors', probs.length === 0, probs.slice(0, 3).join(' | '));
  319. } catch (err) {
  320. failed++; console.log(' FAIL gate crashed — ' + (err && err.stack || err));
  321. for (const pg of pages) console.log(' console: ' + pg.messages.map(m => m.level + ' ' + m.text).join(' || ').slice(0, 1500));
  322. } finally {
  323. for (const b of [browser1, browser2, browser3, browser4]) { try { await b.close(); } catch {} }
  324. for (const p of procs) { try { writeFileSync(join(G, p.logName), p.getOut()); p.kill(); } catch {} }
  325. evil.close();
  326. }
  327. fitCheck();
  328. console.log(`\n${passed} passed, ${failed} failed`);
  329. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • 0f6d1592Merge branch 'f18b-shell-session' into mainIdent
  • 19868218|||PR ident#39 shell reads its session member instead of a cross-file emitmre
  • 5d1b3fedMerge branch 'v61-day61' into mainIdent
  • 83faeb15|||PR ident: vendor Hybriel day61mre
  • b2572b34Merge branch 'v59-day59' into mainIdent
  • 67cf016d|||PR ident: vendor Hybriel day59mre
  • 600c043dMerge branch 'v58-day58' into mainIdent
  • 365f8c80|||PR ident: vendor Hybriel day58mre
  • 585126e5Merge branch 'f16-setf' into mainIdent
  • 953bf03a|||PR ident setF mirror dropped (hybriel#370)mre
  • a1419d9cMerge branch 'f15-navigate' into mainIdent
  • 3b3e451f|||PR ident#36 navigate to the app instead of location.assignmre
  • e36f4516Merge branch 'f14-online' into mainIdent
  • 2c5eac91|||PR ident#38 online state without probe timermre
  • bf1980f2Merge branch 'v56-day56' into mainIdent
  • 62ae0adf|||PR ident: vendor Hybriel day56mre
  • 0d18abc4Merge branch 'f13-avatar' into mainIdent
  • 2a99730a|||PR ident#37 avatar in hlmre
  • fa4ed25bMerge branch 'f11-upsert' into mainIdent
  • 8f3d9bc9|||PR ident#42 keyed upsert and removemre