gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb96796bdb96796bdtests: wait for hydration before real clicks after a navigation (H2)mreb96796bd/tests/browser.mjs

62.4 KB

  1. // tests/browser.mjs — THE GATE of ident.worldapi.org (piece 1 of 6, ticket #24: account,
  2. // identities, time zone). Starts its OWN servers on their own storage (never touches the
  3. // dev server on :8351 or its data):
  4. // ident :8356 (IDENT_STORAGE .scratch/gate-store/main, mail sink main-mail.txt)
  5. // ident short :8357 (OTP TTL 3 s — the expiry case)
  6. // and TWO real headless Chromes (debug ports 8640-8649 / 8650-8659, --disable-gpu, killed
  7. // by PID at the end). Every login is typed and clicked in the browser; the one-time code
  8. // is read from the mail sink file like a person reads their mail. Each browser runs in an
  9. // emulated time zone (A: Pacific/Auckland, B: Asia/Tokyo) so "the browser's
  10. // time zone at first use" is observable.
  11. //
  12. // node tests/browser.mjs
  13. // IDENT_GATE_PORT=8732 IDENT_GATE_SHORT_PORT=8733 IDENT_GATE_CHROME=8734-8739 node tests/browser.mjs
  14. // (other ports: the two servers, and the Chromes' debug ports split in two halves A/B)
  15. //
  16. // Screenshots at 390px and 1280px land in .scratch/gate-*.png — LOOK at them. Server
  17. // logs: .scratch/gate-{main,short}.log. The face negatives go over the framework's REST
  18. // carrier (POST /__hl/emit, the same frame the page sends) with and without a cookie.
  19. import { spawn } from 'node:child_process';
  20. import { rmSync, mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
  21. import { dirname, join, resolve } from 'node:path';
  22. import { fileURLToPath } from 'node:url';
  23. import { deflateSync } from 'node:zlib';
  24. import { launchBrowser } from './cdp.mjs';
  25. // 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
  26. // page (the SSR HTML carries #hl-seed) therefore waits until the page is live (socket open) before the test touches it.
  27. function live(page) {
  28. const goto = page.goto.bind(page);
  29. page.goto = async (url, o) => {
  30. const r = await goto(url, o);
  31. await page.waitFor("!document.getElementById('hl-seed') || (!!window.__hl && !!window.__hl.socket && window.__hl.socket.readyState === 1)", { label: 'page hydrated ' + url });
  32. return r;
  33. };
  34. return page;
  35. }
  36. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  37. const HERE = dirname(fileURLToPath(import.meta.url));
  38. const APP = resolve(HERE, '..');
  39. const BIN = join(APP, 'bin/hybriel');
  40. const SCRATCH = join(APP, '.scratch');
  41. const STORE = join(SCRATCH, 'gate-store');
  42. rmSync(STORE, { recursive: true, force: true });
  43. mkdirSync(STORE, { recursive: true });
  44. const P_MAIN = Number(process.env.IDENT_GATE_PORT || 8356), P_SHORT = Number(process.env.IDENT_GATE_SHORT_PORT || 8357);
  45. const CHROME = (process.env.IDENT_GATE_CHROME || '8640-8659').split('-').map(Number);
  46. const CHROME_MID = Math.floor((CHROME[0] + CHROME[1]) / 2);
  47. const IDENT = `http://127.0.0.1:${P_MAIN}`;
  48. const SHORT = `http://localhost:${P_SHORT}`;
  49. const SINK_MAIN = join(STORE, 'main-mail.txt');
  50. const SINK_SHORT = join(STORE, 'short-mail.txt');
  51. const TZ_A = 'Pacific/Auckland', TZ_B = 'Asia/Tokyo';
  52. let failures = 0, passes = 0;
  53. function check(label, ok, detail = '') {
  54. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  55. if (ok) passes++; else failures++;
  56. }
  57. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  58. const J = JSON.stringify;
  59. // ---- the servers ------------------------------------------------------------------------
  60. const procs = [];
  61. function start(name, env) {
  62. let log = '';
  63. const p = spawn(BIN, ['project.hl'], { cwd: APP, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] });
  64. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d);
  65. p.on('exit', () => writeFileSync(join(SCRATCH, `gate-${name}.log`), log));
  66. procs.push({ name, p, log: () => log });
  67. return p;
  68. }
  69. start('main', { IDENT_PORT: String(P_MAIN), IDENT_STORAGE: join(STORE, 'main'), IDENT_SESSIONS: join(STORE, 'main-sessions'), IDENT_MAIL_SINK: SINK_MAIN, IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000' });
  70. start('short', { IDENT_PORT: String(P_SHORT), IDENT_STORAGE: join(STORE, 'short'), IDENT_SESSIONS: join(STORE, 'short-sessions'), IDENT_MAIL_SINK: SINK_SHORT, IDENT_OTP_TTL_MS: '3000', IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000' });
  71. // the latest code the sink holds for an address (one "<address> <code>" line per mail)
  72. function mails(sink, email) {
  73. if (!existsSync(sink)) return [];
  74. return readFileSync(sink, 'utf8').split('\n').filter(l => l.startsWith(email + ' ')).map(l => l.split(' ')[1]);
  75. }
  76. const lastCode = (sink, email) => mails(sink, email).at(-1);
  77. const req = async (method, url, { raw, headers = {} } = {}) => {
  78. const r = await fetch(url, { method, redirect: 'manual', headers, body: raw });
  79. const text = await r.text();
  80. let json = null; try { json = JSON.parse(text); } catch {}
  81. return { status: r.status, json, text, location: r.headers.get('location') };
  82. };
  83. // A FACE CALL over the framework's REST carrier: the frame the page itself sends
  84. let frameNo = 0;
  85. // hybriel#16 (mission 036): hl:web itself refuses an emit with one argument too many — the ack is
  86. // ok:false "… the `session` parameter is filled by the server, never by the peer"; the face never runs.
  87. 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; } };
  88. async function face(event, payload, cookie) {
  89. const r = await req('POST', IDENT + '/__hl/emit', { raw: J({ t: 'emit', i: ++frameNo, event, payload }), headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) } });
  90. return r.json && r.json.ok ? r.json.value : { transport: r.status, text: r.text.slice(0, 300), refused: framework_refused(r.text) };
  91. }
  92. const connected = (page, label) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label });
  93. async function viewport(page, width, height) {
  94. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  95. await sleep(250);
  96. }
  97. async function shot(page, name) {
  98. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  99. writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));
  100. }
  101. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  102. async function bothWidths(page, name) {
  103. await viewport(page, 390, 844); await shot(page, 'phone-' + name);
  104. check(`layout: 390px ${name} has no horizontal overflow`, await noOverflow(page));
  105. await viewport(page, 1280, 900); await shot(page, 'desktop-' + name);
  106. check(`layout: 1280px ${name} has no horizontal overflow`, await noOverflow(page));
  107. }
  108. const msg = (page) => page.text('#message');
  109. const waitMsg = (page, re, label) => page.waitFor(`/${re}/.test((document.querySelector('#message') || {}).textContent || '')`, { label });
  110. const waitNotice = (page, re, label) => page.waitFor(`/${re}/.test((document.querySelector('#notice') || {}).textContent || '')`, { label });
  111. // the identity list as the page shows it: [{ label, details, isDefault, edit, del }]
  112. const listed = (page) => page.evaluate(`[...document.querySelectorAll('#identities li')].map(li => ({ label: li.querySelector('identity-label').textContent, details: li.querySelector('identity-details').textContent, isDefault: !!li.querySelector('default-badge'), edit: !!li.querySelector('button.edit'), del: !!li.querySelector('button.delete') }))`);
  113. const labels = async (page) => (await listed(page)).map(r => r.label);
  114. // click a row's button by the row's label
  115. async function rowButton(page, label, cls) {
  116. const sel = await page.evaluate(`(() => { const li = [...document.querySelectorAll('#identities li')].find(li => li.querySelector('identity-label').textContent === ${J(label)}); if (!li) return null; const b = li.querySelector('button.${cls}'); if (!b) return null; b.id = 'gate-target'; return '#gate-target'; })()`);
  117. if (!sel) throw new Error(`no ${cls} button for ${label}`);
  118. await page.click(sel);
  119. await page.evaluate(`document.querySelector('#gate-target') && document.querySelector('#gate-target').removeAttribute('id')`);
  120. }
  121. // window.confirm: answer the NEXT dialog of this page with `accept`
  122. function dialogs(page) {
  123. page.dialogAnswer = true;
  124. page.dialogTexts = [];
  125. page.conn.onEvent(m => {
  126. if (m.method === 'Page.javascriptDialogOpening' && m.sessionId === page.sessionId) {
  127. page.dialogTexts.push(m.params.message);
  128. page.send('Page.handleJavaScriptDialog', { accept: page.dialogAnswer }).catch(() => {});
  129. }
  130. });
  131. }
  132. // THE LOGIN AS A PERSON DOES IT: type the address, click, read the mail, type the code
  133. async function askCode(page, email) {
  134. await page.waitForSelector('#email');
  135. await connected(page, 'socket before asking');
  136. await page.type('#email', email, { clear: true });
  137. await page.evaluate('document.querySelector("#message").textContent = ""');
  138. await page.click('#sendcode');
  139. // ident#20: a sent code NAVIGATES to the code page (/code); a refusal stays with a message
  140. await page.waitFor('(/\\/code$/.test(location.pathname) && !!document.querySelector("#code")) || /\\S/.test(document.querySelector("#message").textContent)', { label: 'code page or message after ' + email });
  141. if (await page.evaluate('/\\/code$/.test(location.pathname)')) await connected(page, 'code page hydrated');
  142. }
  143. // A REAL RELOAD (Page.reload, like a phone reloading the tab), then the hydrated socket
  144. async function reload(page) {
  145. page._loaded = false;
  146. await page.send('Page.reload', { ignoreCache: false });
  147. const deadline = Date.now() + 15000;
  148. while (!page._loaded && Date.now() < deadline) await sleep(25);
  149. if (!page._loaded) throw new Error('reload: load event never fired');
  150. await connected(page, 'socket after reload');
  151. }
  152. // what the page shows: '<path> code:<address>' | '<path> email' | '<path> signedin' | '<path> ?'
  153. const step = (page) => page.evaluate(`location.pathname + ' ' + (document.querySelector('#codeform') && !document.querySelector('#emailform') ? 'code:' + document.querySelector('#sentto strong').textContent : (document.querySelector('#emailform') && !document.querySelector('#codeform') ? 'email' : (document.querySelector('#meemail') ? 'signedin' : '?')))`);
  154. // what the SERVER answers a plain GET with this cookie (no JS, no redirect following):
  155. // '302 <location>' or '200 code:<address>' / '200 email' / '200 signedin'
  156. async function ssr(path, cookie, base = IDENT) {
  157. const r = await fetch(base + path, { redirect: 'manual', headers: cookie ? { cookie } : {} });
  158. if (r.status >= 300 && r.status < 400) return r.status + ' ' + r.headers.get('location');
  159. const t = await r.text();
  160. const m = /id="sentto"[^>]*>.*?<strong[^>]*>([^<]*)</s.exec(t);
  161. return r.status + ' ' + (t.includes('id="codeform"') && m ? 'code:' + m[1] : (t.includes('id="emailform"') ? 'email' : (t.includes('id="meemail"') ? 'signedin' : '?')));
  162. }
  163. const cookieOf = async (page, url) => (await page.cookies([url])).filter(c => c.name === 'identsid').map(c => `identsid=${c.value}`)[0];
  164. async function enterCode(page, code) {
  165. await page.evaluate('document.querySelector("#message").textContent = ""');
  166. await page.type('#code', code, { clear: true });
  167. await page.click('#verify');
  168. }
  169. async function fill(page, values) {
  170. for (const [id, v] of Object.entries(values)) await page.type('#' + id, v, { clear: true });
  171. }
  172. // a PNG 300×200 (left half red, right half blue) and a text file, for the avatar upload
  173. function makePng() {
  174. const W = 300, H = 200, raw = Buffer.alloc((W * 3 + 1) * H);
  175. for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { const o = y * (W * 3 + 1); raw[o] = 0; raw[o + 1 + x * 3] = x < W / 2 ? 255 : 0; raw[o + 2 + x * 3] = 0; raw[o + 3 + x * 3] = x < W / 2 ? 0 : 255; }
  176. const crcT = []; for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; crcT[n] = c >>> 0; }
  177. const crc = (b) => { let c = 0xffffffff; for (const x of b) c = crcT[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
  178. const chunk = (t, d) => { const len = Buffer.alloc(4); len.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); };
  179. const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(W, 0); ihdr.writeUInt32BE(H, 4); ihdr[8] = 8; ihdr[9] = 2;
  180. return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
  181. }
  182. const PNG_FILE = join(STORE, 'avatar.png'), TXT_FILE = join(STORE, 'avatar.txt');
  183. writeFileSync(PNG_FILE, makePng()); writeFileSync(TXT_FILE, 'not a picture');
  184. // pick a file in an <input type=file> like a person does (the browser's own file chooser result)
  185. async function upload(page, selector, file) {
  186. const { root } = await page.send('DOM.getDocument');
  187. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector });
  188. await page.send('DOM.setFileInputFiles', { files: [file], nodeId });
  189. }
  190. // a PASTE (one input event with the whole value), unlike page.type()'s per-character keys —
  191. // used for the avatar URL so a live `src`-bound preview does not fetch every half-typed prefix
  192. async function paste(page, selector, text) {
  193. await page.evaluate(`(() => { const el = document.querySelector(${J(selector)}); el.value = ${J(text)}; el.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  194. }
  195. let A, B, a, b;
  196. try {
  197. for (const [name, url] of [['main', IDENT + '/'], ['short', `http://127.0.0.1:${P_SHORT}/`]]) {
  198. let up = false;
  199. for (const end = Date.now() + Number(process.env.IDENT_COLD_MS || 120000); !up && Date.now() < end;) { try { const r = await fetch(url); if (r.ok) { up = true; break; } } catch {} await sleep(250); } // a compiling Hybriel starts cold in ~20-40 s: IDENT_COLD_MS (default 120 s)
  200. if (!up) throw new Error(`${name} server did not come up\n` + procs.find(p => p.name === name).log());
  201. }
  202. // ---- the mission-003 app flow is gone; piece 2 rebuilt /login and /api/exchange ------------
  203. // (ticket #37: these two checks asserted 404s from before piece 2; they now check that the
  204. // mission-003 shapes are refused by the piece-2 routes. The full piece-2 rules: tests/apps.mjs)
  205. let r = await req('POST', IDENT + '/api/exchange', { raw: '{"code":"x"}', headers: { 'content-type': 'application/json' } });
  206. check('old exchange shape (code only): 400 naming the missing key, no identity', r.status === 400 && r.json && r.json.error === 'missing field: key' && r.json.identity === undefined, J(r));
  207. r = await req('GET', IDENT + '/login?app=testclient&return=http://127.0.0.1:' + (P_MAIN + 2) + '/callback');
  208. check('old /login?app=… (no key): 400 error page, no redirect', r.status === 400 && r.location === null && /the key parameter/.test(r.text), `${r.status} ${r.location}`);
  209. r = await req('GET', IDENT + '/continue/abc');
  210. check('removed: GET /continue/<rid> is 404', r.status === 404, String(r.status));
  211. // ---- faces without a session ----------------------------------------------------------------
  212. let v = await face('addIdentity', [{ identityName: 'X' }]);
  213. check('face: addIdentity without a session → not signed in', v.error === 'you are not signed in', J(v));
  214. v = await face('changeTimeZone', ['Europe/Vienna']);
  215. check('face: changeTimeZone without a session → not signed in', v.error === 'you are not signed in', J(v));
  216. A = await launchBrowser({ debugPortRange: [CHROME[0], CHROME_MID] });
  217. B = await launchBrowser({ debugPortRange: [CHROME_MID + 1, CHROME[1]] });
  218. a = live(await A.newPage());
  219. b = live(await B.newPage());
  220. dialogs(a); dialogs(b);
  221. await a.send('Emulation.setTimezoneOverride', { timezoneId: TZ_A });
  222. await b.send('Emulation.setTimezoneOverride', { timezoneId: TZ_B });
  223. // ---- browser A: the first login creates the account --------------------------------------------
  224. await a.goto(IDENT + '/');
  225. await a.waitForSelector('#emailform');
  226. await connected(a, 'A connected');
  227. check('home: signed out shows the login (SSR), no identities', await a.evaluate('!!document.querySelector("#emailform") && !document.querySelector("#identities") && document.title === "ident | sign in"'), await a.evaluate('document.title'));
  228. check('home: the page says there is no sign-up', /no sign-up/.test(await a.text('ident-card')), await a.text('ident-card'));
  229. check('home: palette — accent orange #ce9178 (brand = the theme strong text), danger #f44747, dark background', await a.evaluate(`(() => { const cs = getComputedStyle(document.documentElement); const s = document.createElement('span'); s.style.color = 'var(--color-danger)'; document.body.append(s); const d = getComputedStyle(s).color; s.remove(); return cs.getPropertyValue('--color-accent').trim() === '#ce9178' && getComputedStyle(document.querySelector('.brand')).color === 'rgb(245, 250, 255)' && getComputedStyle(document.querySelector('#sendcode')).backgroundColor === 'rgb(206, 145, 120)' && d === 'rgb(244, 71, 71)' && getComputedStyle(document.body).backgroundColor === 'rgb(25, 30, 35)'; })()`));
  230. await bothWidths(a, 'signin');
  231. await askCode(a, 'foo@bar');
  232. check('login: an address without a dotted domain is refused', (await msg(a)) === 'that is not an email address', await msg(a));
  233. await askCode(a, ' [email protected] ');
  234. check('login: code form shows the LOWERCASED address', (await a.text('#sentto strong')) === '[email protected]', await a.text('#sentto'));
  235. check('ident#20: "Send me a code" lands on the code page /code', (await step(a)) === '/code code:[email protected]', await step(a));
  236. const aliceCode1 = lastCode(SINK_MAIN, '[email protected]');
  237. check('mail: the sink got one 6-digit code for alice', mails(SINK_MAIN, '[email protected]').length === 1 && /^\d{6}$/.test(aliceCode1), readFileSync(SINK_MAIN, 'utf8'));
  238. await bothWidths(a, 'code');
  239. await enterCode(a, aliceCode1 === '000000' ? '111111' : '000000');
  240. await waitMsg(a, 'wrong code', 'wrong code message');
  241. check('login: a wrong code says so and counts down', (await msg(a)) === 'wrong code (4 tries left)', await msg(a));
  242. await enterCode(a, aliceCode1);
  243. await a.waitForSelector('#identityform');
  244. check('first login: the account exists at once — the default identity is listed', J(await listed(a)) === J([{ label: 'Default', details: 'no names', isDefault: true, edit: true, del: false }]), J(await listed(a)));
  245. check('first login: the name fields are shown and say they are OPTIONAL', /optional/i.test(await a.text('#welcome')) && (await a.evaluate('["#fidentityname","#fnickname","#ffirstname","#flastname"].every(s => !!document.querySelector(s) && !document.querySelector(s).required)')) && (await a.evaluate('!!document.querySelector("#skip")')), await a.text('#identityform'));
  246. check('first login: the fields are the default identity\'s (identity name "Default", names empty)', J(await a.evaluate('["#fidentityname","#fnickname","#ffirstname","#flastname"].map(s => document.querySelector(s).value)')) === J(['Default', '', '', '']));
  247. check('time zone: the browser\'s (emulated ' + TZ_A + ') was stored at first use', (await a.text('#timezone')) === TZ_A, await a.text('#timezone'));
  248. await bothWidths(a, 'welcome');
  249. // SKIPPED: the form closes, the default identity stays as it is
  250. await a.click('#skip');
  251. await a.waitFor('!document.querySelector("#identityform")', { label: 'welcome closed' });
  252. check('skip: the form closes, the default identity stays unnamed', J(await listed(a)) === J([{ label: 'Default', details: 'no names', isDefault: true, edit: true, del: false }]), J(await listed(a)));
  253. await a.goto(IDENT + '/');
  254. await a.waitForSelector('#identities');
  255. check('reload: still signed in (SSR), identities and time zone read back, no welcome again', (await a.text('#meemail')) === '[email protected]' && J(await labels(a)) === J(['Default']) && (await a.text('#timezone')) === TZ_A && !(await a.evaluate('!!document.querySelector("#identityform")')), await a.text('ident-card'));
  256. check('title: signed in', (await a.evaluate('document.title')) === 'ident | your identities', await a.evaluate('document.title'));
  257. check('cookie: ident uses its own cookie name (identsid), httpOnly', await a.cookies([IDENT]).then(cs => cs.some(c => c.name === 'identsid' && c.httpOnly) && !cs.some(c => c.name === 'hlsid')), J(await a.cookies([IDENT])));
  258. const aliceCookie = (await a.cookies([IDENT])).filter(c => c.name === 'identsid').map(c => `identsid=${c.value}`)[0];
  259. // EDIT the default identity: all four fields
  260. await connected(a, 'A before edit');
  261. await rowButton(a, 'Default', 'edit');
  262. await a.waitForSelector('#identityform');
  263. check('edit: the form is headed with the identity and has Cancel, not Skip', (await a.text('#formheading')) === 'Edit Default' && (await a.evaluate('!!document.querySelector("#cancel") && !document.querySelector("#skip") && !document.querySelector("#welcome")')), await a.text('#identityform'));
  264. await fill(a, { fidentityname: 'Private', fnickname: 'Ali', ffirstname: 'Alice', flastname: 'Example' });
  265. await upload(a, '#favatarfile', TXT_FILE);
  266. await a.waitFor(`document.querySelector('#avatarnote').textContent.length > 0`, { label: 'avatar: text file refused' });
  267. check('avatar: a text file is refused with a message, nothing is set', (await a.text('#avatarnote')).startsWith('That is not a picture') && (await a.evaluate(`document.querySelector('#favatar').value`)) === '', await a.text('#avatarnote'));
  268. await upload(a, '#favatarfile', PNG_FILE);
  269. await a.waitFor(`document.querySelector('#favatar').value.startsWith('data:image/')`, { label: 'avatar: picture scaled' });
  270. check('avatar: an uploaded picture is scaled to 128×128 and previewed before saving', await a.evaluate(`(async () => { const p = document.querySelector('#avatarpreview'); await new Promise(r => p.complete ? r() : (p.onload = r)); return p.naturalWidth === 128 && p.naturalHeight === 128 && p.src === document.querySelector('#favatar').value && !p.classList.contains('hidden') && document.querySelector('#favatar').value.length < 60000; })()`), await a.evaluate(`document.querySelector('#favatar').value.slice(0, 40)`));
  271. check('avatar: the centre-cropped, scaled picture keeps its colours (red left, blue right)', await a.evaluate(`(async () => { const p = document.querySelector('#avatarpreview'); const c = document.createElement('canvas'); c.width = c.height = 128; const x = c.getContext('2d', { willReadFrequently: true }); x.drawImage(p, 0, 0); const l = x.getImageData(10, 64, 1, 1).data, r = x.getImageData(118, 64, 1, 1).data; return l[0] > 200 && l[2] < 60 && r[2] > 200 && r[0] < 60; })()`));
  272. await bothWidths(a, 'edit');
  273. await a.click('#saveidentity');
  274. await waitNotice(a, 'Identity saved', 'saved notice');
  275. check('edit: saved — label and names shown', J(await listed(a)) === J([{ label: 'Private', details: '“Ali” · Alice Example', isDefault: true, edit: true, del: false }]), J(await listed(a)));
  276. check('avatar: the identity list shows a round avatar image with the saved picture', await a.evaluate(`(() => { const img = document.querySelector('#identities li img.avatar'); return !!img && img.src.startsWith('data:image/') && img.naturalWidth === 128; })()`), await a.evaluate(`document.querySelector('#identities').innerHTML`));
  277. // reopening the edit form shows the saved avatar again, and typing focus survives (ticket #15
  278. // regression: an `if` next to the text inputs in the SAME view made hl:webex recreate the
  279. // form on every keystroke, losing focus after one character — hybriel #32)
  280. await rowButton(a, 'Private', 'edit');
  281. await a.waitForSelector('#identityform');
  282. check('avatar: reopening edit shows the saved picture and preview', (await a.evaluate(`document.querySelector('#favatar').value`)).startsWith('data:image/') && await a.evaluate(`!document.querySelector('#avatarpreview').classList.contains('hidden')`));
  283. await a.focus('#fnickname');
  284. await a.send('Input.dispatchKeyEvent', { type: 'keyDown', text: 'z', unmodifiedText: 'z', key: 'z' });
  285. await a.send('Input.dispatchKeyEvent', { type: 'keyDown', text: 'z', unmodifiedText: 'z', key: 'z' });
  286. check('avatar: typing two characters in a row keeps focus (no per-keystroke re-render)', (await a.evaluate(`document.querySelector('#fnickname').value`)) === 'Alizz' && (await a.evaluate('document.activeElement && document.activeElement.id')) === 'fnickname');
  287. await a.click('#avatarremove');
  288. check('avatar: "Remove picture" hides the preview again', await a.evaluate(`document.querySelector('#avatarpreview').classList.contains('hidden')`));
  289. await a.click('#cancel');
  290. await a.waitFor('!document.querySelector("#identityform")', { label: 'avatar-check cancel closes' });
  291. // A SECOND identity, then a third with NO fields at all
  292. await a.click('#newidentity');
  293. await a.waitForSelector('#identityform');
  294. check('new: an empty form headed "New identity"', (await a.text('#formheading')) === 'New identity' && J(await a.evaluate('["#fidentityname","#fnickname","#ffirstname","#flastname"].map(s => document.querySelector(s).value)')) === J(['', '', '', '']));
  295. await fill(a, { fidentityname: 'Work', ffirstname: 'Alice', flastname: 'Example-Work' });
  296. await a.click('#saveidentity');
  297. await waitNotice(a, 'Identity created', 'created notice');
  298. check('new: the second identity is listed; now both can be deleted, the first stays default', J(await listed(a)) === J([
  299. { label: 'Private', details: '“Ali” · Alice Example', isDefault: true, edit: true, del: true },
  300. { label: 'Work', details: 'Alice Example-Work', isDefault: false, edit: true, del: true }]), J(await listed(a)));
  301. // hybriel#121 (mission 048): a face taking the session syncs the session-derived list back — a row added on top would show twice
  302. check('new: the created identity is listed ONCE (no session-sync double row)', (await labels(a)).filter(l => l === 'Work').length === 1 && (await a.evaluate('document.querySelectorAll("#identities li").length')) === 2, J(await labels(a)));
  303. await a.click('#newidentity');
  304. await a.waitForSelector('#identityform');
  305. await a.click('#saveidentity');
  306. await waitNotice(a, 'Identity created', 'created notice 3');
  307. check('new: an identity with no fields at all is fine (shown as "Identity 3")', J(await labels(a)) === J(['Private', 'Work', 'Identity 3']), J(await labels(a)));
  308. // cancel does not save
  309. await rowButton(a, 'Work', 'edit');
  310. await a.waitForSelector('#identityform');
  311. await fill(a, { fnickname: 'SHOULD-NOT-SAVE' });
  312. await a.click('#cancel');
  313. await a.waitFor('!document.querySelector("#identityform")', { label: 'cancel closes' });
  314. // edit the second one
  315. await rowButton(a, 'Work', 'edit');
  316. await a.waitForSelector('#identityform');
  317. check('edit: the form holds the stored values (the cancelled change is gone)', J(await a.evaluate('["#fidentityname","#fnickname","#ffirstname","#flastname"].map(s => document.querySelector(s).value)')) === J(['Work', '', 'Alice', 'Example-Work']), J(await a.evaluate('["#fidentityname","#fnickname","#ffirstname","#flastname"].map(s => document.querySelector(s).value)')));
  318. await fill(a, { fnickname: 'AE' });
  319. await a.click('#saveidentity');
  320. await waitNotice(a, 'Identity saved', 'saved notice 2');
  321. await a.goto(IDENT + '/');
  322. await a.waitForSelector('#identities');
  323. check('reload: three identities as saved', J(await listed(a)) === J([
  324. { label: 'Private', details: '“Ali” · Alice Example', isDefault: true, edit: true, del: true },
  325. { label: 'Work', details: '“AE” · Alice Example-Work', isDefault: false, edit: true, del: true },
  326. { label: 'Identity 3', details: 'no names', isDefault: false, edit: true, del: true }]), J(await listed(a)));
  327. await bothWidths(a, 'identities');
  328. // DELETE: a dismissed confirm keeps it; accepted removes it; the last one cannot go
  329. await connected(a, 'A before delete');
  330. a.dialogAnswer = false;
  331. await rowButton(a, 'Identity 3', 'delete');
  332. await sleep(500);
  333. check('delete: a dismissed confirm keeps the identity', a.dialogTexts.at(-1) === 'Delete the identity “Identity 3”?' && J(await labels(a)) === J(['Private', 'Work', 'Identity 3']), J(a.dialogTexts) + J(await labels(a)));
  334. a.dialogAnswer = true;
  335. await rowButton(a, 'Identity 3', 'delete');
  336. await waitNotice(a, 'Identity deleted', 'deleted notice');
  337. check('delete: accepted → gone', J(await labels(a)) === J(['Private', 'Work']), J(await labels(a)));
  338. await rowButton(a, 'Private', 'delete');
  339. await a.waitFor(`document.querySelectorAll('#identities li').length === 1`, { label: 'default deleted' });
  340. check('delete: the default one may go while another exists; the remaining one becomes default and has no Delete', J(await listed(a)) === J([{ label: 'Work', details: '“AE” · Alice Example-Work', isDefault: true, edit: true, del: false }]), J(await listed(a)));
  341. // ids are mpackdb UUIDs (mission 009): read Alice's remaining identity's id off its Edit button
  342. const aliceWorkId = await a.evaluate('document.querySelector("#identities li .edit").value');
  343. check('ids: an identity id is a 12-char mpackdb UUID (not a number)', /^[0-9a-z]{12}$/.test(aliceWorkId), J(aliceWorkId));
  344. v = await face('dropIdentity', [aliceWorkId], aliceCookie);
  345. check('face: deleting the LAST identity is refused', v.error === 'this is your only identity — an account always keeps one', J(v));
  346. await a.goto(IDENT + '/');
  347. await a.waitForSelector('#identities');
  348. check('reload: the last identity is still there', J(await labels(a)) === J(['Work']), J(await labels(a)));
  349. // TIME ZONE: change, browser button, unknown name refused in the page
  350. await connected(a, 'A before tz');
  351. await a.type('#tzinput', 'Mars/Olympus_Mons', { clear: true });
  352. await a.click('#savetz');
  353. await waitMsg(a, 'does not know', 'unknown zone');
  354. check('time zone: a name the browser does not know is refused, nothing saved', (await msg(a)) === 'this browser does not know the time zone “Mars/Olympus_Mons”' && (await a.text('#timezone')) === TZ_A, await msg(a));
  355. await a.type('#tzinput', 'Europe/Vienna', { clear: true });
  356. await a.click('#savetz');
  357. await waitNotice(a, 'Time zone saved', 'tz saved');
  358. check('time zone: changed to Europe/Vienna', (await a.text('#timezone')) === 'Europe/Vienna', await a.text('#timezone'));
  359. await a.click('#browsertz');
  360. await a.waitFor(`document.querySelector('#tzinput').value === ${J(TZ_A)}`, { label: 'browser tz button' });
  361. check('time zone: "Use this browser\'s" fills in the browser\'s zone (not saved yet)', (await a.text('#timezone')) === 'Europe/Vienna');
  362. await a.goto(IDENT + '/');
  363. await a.waitForSelector('#timezone');
  364. check('reload: the time zone reads back Europe/Vienna', (await a.text('#timezone')) === 'Europe/Vienna' && (await a.evaluate('document.querySelector("#tzinput").value')) === 'Europe/Vienna');
  365. // SIGN OUT, then a known address signs in: no welcome, the time zone is NOT reset
  366. await connected(a, 'A before sign out');
  367. await a.evaluate('window.__m = 1');
  368. await a.click('#signout');
  369. await a.waitForSelector('#emailform');
  370. check('sign out (in place, no reload): the header has no user menu and no main menu any more', await a.evaluate('window.__m === 1 && !document.querySelector("application-header button.user-toggle") && !document.querySelector("application-header main-menu") && !document.querySelector("#code") && !!document.querySelector("#email")'), await a.evaluate('String(window.__m) + document.querySelector("application-header").innerText'));
  371. await a.goto(IDENT + '/');
  372. await a.waitForSelector('#emailform');
  373. check('sign out: the reload is signed out', !(await a.evaluate('!!document.querySelector("#identities")')));
  374. v = await face('addIdentity', [{ identityName: 'after sign out' }], aliceCookie);
  375. check('face: the signed-out cookie cannot add an identity', v.error === 'you are not signed in', J(v));
  376. await askCode(a, '[email protected]');
  377. await enterCode(a, lastCode(SINK_MAIN, '[email protected]'));
  378. await a.waitForSelector('#identities');
  379. await sleep(300);
  380. check('login again: no welcome form, same identity, time zone kept (not the browser\'s)', !(await a.evaluate('!!document.querySelector("#identityform")')) && J(await labels(a)) === J(['Work']) && (await a.text('#timezone')) === 'Europe/Vienna', await a.text('ident-card'));
  381. await enterCode(a, lastCode(SINK_MAIN, '[email protected]')).catch(() => {});
  382. const aliceCookie2 = (await a.cookies([IDENT])).filter(c => c.name === 'identsid').map(c => `identsid=${c.value}`)[0];
  383. // ---- browser B: first login, names FILLED at the welcome; wrong codes; rate limit ----------------
  384. await b.goto(IDENT + '/');
  385. await askCode(b, '[email protected]');
  386. await b.evaluate('window.__m = 1');
  387. await enterCode(b, lastCode(SINK_MAIN, '[email protected]'));
  388. await b.waitForSelector('#identityform');
  389. check('B first login: time zone ' + TZ_B + ' from this browser', (await b.text('#timezone')) === TZ_B, await b.text('#timezone'));
  390. await fill(b, { fidentityname: 'Bob', fnickname: 'Bobby', ffirstname: 'Bob', flastname: 'Builder' });
  391. // mission 013 (hybriel#193): the page's emit reaches the shell — no reload anywhere in this flow. `__m` survives only without one.
  392. check('B first login (in place, no reload yet): the header already has the user menu with the address', await b.evaluate('window.__m === 1 && !!document.querySelector("application-header button.user-toggle") && document.querySelector("#whoami").textContent === "[email protected]"'), await b.evaluate('String(window.__m) + document.querySelector("application-header").innerText'));
  393. await b.click('#saveidentity');
  394. await b.waitFor('!document.querySelector("#identityform") && /Identity saved/.test(document.querySelector("#notice").textContent)', { label: 'B saved: the "Identity saved." notice' });
  395. check('B welcome save: notice "Identity saved." shown, no reload, header keeps the user menu', await b.evaluate('window.__m === 1 && document.querySelector("#notice").textContent === "Identity saved." && !!document.querySelector("application-header button.user-toggle")'), await b.text('#notice'));
  396. check('B welcome FILLED: the default identity carries the names', J(await listed(b)) === J([{ label: 'Bob', details: '“Bobby” · Bob Builder', isDefault: true, edit: true, del: false }]), J(await listed(b)));
  397. const bobCookie = (await b.cookies([IDENT])).filter(c => c.name === 'identsid').map(c => `identsid=${c.value}`)[0];
  398. // FACE NEGATIVES (Bob's cookie): strict fields, other accounts' identities, time zone shapes
  399. const neg = [
  400. ['unknown field', ['addIdentity', [{ identityName: 'x', email: '[email protected]' }]], { error: 'unknown field: email', field: 'email' }],
  401. ['wrong type', ['addIdentity', [{ nickname: 5 }]], { error: 'field nickname must be a string', field: 'nickname' }],
  402. ['null value', ['addIdentity', [{ nickname: null }]], { error: 'field nickname must be a string', field: 'nickname' }],
  403. ['fields a list', ['addIdentity', [['x']]], { error: 'the identity fields must be an object', field: '' }],
  404. ['fields a string', ['addIdentity', ['x']], { error: 'the identity fields must be an object', field: '' }],
  405. ['61 characters', ['addIdentity', [{ lastname: 'x'.repeat(61) }]], { error: 'field lastname is longer than 60 characters', field: 'lastname' }],
  406. ['control character', ['addIdentity', [{ firstname: 'a\u0007b' }]], { error: 'field firstname contains a control character', field: 'firstname' }],
  407. ['avatar: a link is not a picture', ['addIdentity', [{ avatar: 'https://example.org/pic.png' }]], { error: 'field avatar must be an uploaded PNG, JPEG or WebP picture', field: 'avatar' }],
  408. ['avatar: svg refused', ['addIdentity', [{ avatar: 'data:image/svg+xml;base64,PHN2Zz4=' }]], { error: 'field avatar must be an uploaded PNG, JPEG or WebP picture', field: 'avatar' }],
  409. ['avatar: wrong bytes for the type', ['addIdentity', [{ avatar: 'data:image/png;base64,AAAAAAAAAAAA' }]], { error: 'field avatar is not a valid picture', field: 'avatar' }],
  410. ['avatar: not base64', ['addIdentity', [{ avatar: 'data:image/png;base64,iVBORw0KGgo<script>' }]], { error: 'field avatar is not valid base64', field: 'avatar' }],
  411. ['avatar: too long', ['addIdentity', [{ avatar: 'data:image/png;base64,iVBORw0KGgo' + 'A'.repeat(60000) }]], { error: 'field avatar is longer than 60000 characters', field: 'avatar' }],
  412. ['avatar: wrong type', ['addIdentity', [{ avatar: 5 }]], { error: 'field avatar must be a string', field: 'avatar' }],
  413. ['edit: another account\'s identity', ['editIdentity', [aliceWorkId, { nickname: 'hacked' }]], { error: 'no such identity', field: 'id' }],
  414. ['edit: id as a number (the old numeric ids)', ['editIdentity', [2, { nickname: 'x' }]], { error: 'no such identity', field: 'id' }],
  415. ['edit: unknown id', ['editIdentity', ['0zzzzzzzzzzz', {}]], { error: 'no such identity', field: 'id' }],
  416. ['delete: another account\'s identity', ['dropIdentity', [aliceWorkId]], { error: 'no such identity' }],
  417. ['delete: an old numeric id', ['dropIdentity', [2]], { error: 'no such identity' }],
  418. ['delete: own last identity', ['dropIdentity', ['(Bob\'s)']], { error: 'this is your only identity — an account always keeps one' }],
  419. ['time zone: bad characters', ['changeTimeZone', ['Europe/Vienna; x']], { error: 'that is not a time zone name (like Europe/Vienna)' }],
  420. ['time zone: a number', ['changeTimeZone', [5]], { error: 'the time zone must be a string' }],
  421. ['time zone: empty', ['changeTimeZone', [' ']], { error: 'the time zone is empty' }],
  422. ];
  423. const bobIds = await face('addIdentity', [{}], bobCookie); // a 2nd identity: learn Bob's ids
  424. const bobRows = bobIds.identities || [];
  425. check('face: Bob can add an identity with an empty object', bobRows.length === 2, J(bobIds));
  426. await face('dropIdentity', [bobRows[1] && bobRows[1].id], bobCookie);
  427. for (const [label, [ev, payload], want] of neg) {
  428. // `own last identity` must name Bob's id
  429. const p = label === 'delete: own last identity' ? [bobRows[0].id] : payload;
  430. v = await face(ev, p, bobCookie);
  431. check(`face negative: ${label}`, J(v) === J(want), J(v));
  432. }
  433. // IMPERSONATION: a hand-made frame with one argument too many puts ITS object where the
  434. // session goes (hybriel: positional trailing session); ident only takes a real session
  435. v = await face('addIdentity', [{ identityName: 'forged' }, { user: { id: 1 }, data: {} }]);
  436. check('face: a forged session object (extra argument, no cookie) is refused', v.refused === true || v.error === 'you are not signed in', J(v));
  437. v = await face('dropIdentity', [aliceWorkId, { user: { id: 1 }, data: {} }], bobCookie);
  438. check('face: a forged session with Bob\'s cookie cannot delete Alice\'s identity', v.refused === true || v.error === 'you are not signed in' || v.error === 'no such identity', J(v));
  439. await a.goto(IDENT + '/');
  440. await a.waitForSelector('#identities');
  441. check('Alice\'s identities are untouched by all of the above', J(await listed(a)) === J([{ label: 'Work', details: '“AE” · Alice Example-Work', isDefault: true, edit: true, del: false }]), J(await listed(a)));
  442. v = await face('changeTimeZone', ['UTC'], aliceCookie2);
  443. check('face: UTC is a valid zone', v.timeZone === 'UTC', J(v));
  444. // mission 013 (hybriel#193): "Sign out everywhere" in place — its notice is back, the header drops the user menu, no reload;
  445. // and the main menu marks the page from the route (the in-place sign-in is checked at Bob's first login above and in e2e-theme.mjs)
  446. await b.goto(IDENT + '/');
  447. await b.waitForSelector('#signoutall');
  448. await connected(b, 'B before sign out everywhere');
  449. check('main menu marks Identities from the route (server-rendered: aria-current on /)', await b.evaluate('document.querySelector("application-header main-menu a[href=\\"/\\"]").getAttribute("aria-current") === "page" && document.querySelector("application-header main-menu a[href=\\"/apps\\"]").getAttribute("aria-current") === "false"'));
  450. await b.evaluate('window.__m = 1');
  451. await b.click('#signoutall');
  452. await b.waitFor('!!document.querySelector("#emailform") && /Signed out on every device/.test(document.querySelector("#notice").textContent)', { label: 'B signed out everywhere: the notice' });
  453. check('sign out everywhere (in place, no reload): notice "Signed out on every device.", the header has no user menu', await b.evaluate('window.__m === 1 && document.querySelector("#notice").textContent === "Signed out on every device." && !document.querySelector("application-header button.user-toggle") && !document.querySelector("#code")'), await b.text('#notice'));
  454. // OTP RULES (kept from mission 003): 5 wrong codes, rate limit (Bob is signed out everywhere by now)
  455. await b.waitForSelector('#emailform');
  456. await askCode(b, '[email protected]');
  457. const carolCode = lastCode(SINK_MAIN, '[email protected]');
  458. const wrong = carolCode === '123456' ? '654321' : '123456';
  459. const seen = [];
  460. for (let i = 0; i < 5; i++) {
  461. await enterCode(b, wrong);
  462. await b.waitFor('/\\S/.test(document.querySelector("#message").textContent)', { label: 'wrong try ' + (i + 1) });
  463. seen.push(await msg(b));
  464. }
  465. check('otp: five wrong codes count down and then kill the code', J(seen) === J(['wrong code (4 tries left)', 'wrong code (3 tries left)', 'wrong code (2 tries left)', 'wrong code (1 tries left)', 'too many wrong codes — ask for a new one']), J(seen));
  466. await enterCode(b, carolCode);
  467. await b.waitFor('/\\S/.test(document.querySelector("#message").textContent)', { label: 'right code after kill' });
  468. check('otp: after 5 wrong tries even the RIGHT code is refused, and no account exists', (await msg(b)) === 'no code is waiting for this address — ask for a new one' && !(await b.evaluate('!!document.querySelector("#identities")')), await msg(b));
  469. await b.click('#back');
  470. await askCode(b, '[email protected]');
  471. const carolOld = lastCode(SINK_MAIN, '[email protected]');
  472. await b.click('#back');
  473. await askCode(b, '[email protected]');
  474. check('rate limit: the 3rd code in 10 minutes is still sent', mails(SINK_MAIN, '[email protected]').length === 3, J(mails(SINK_MAIN, '[email protected]')));
  475. await enterCode(b, carolOld === lastCode(SINK_MAIN, '[email protected]') ? '000001' : carolOld);
  476. await waitMsg(b, 'wrong code', 'old code refused');
  477. check('otp: a replaced (older) code no longer works', /^wrong code/.test(await msg(b)), await msg(b));
  478. await b.click('#back');
  479. await askCode(b, '[email protected]');
  480. check('rate limit: the 4th is refused and not mailed', /too many codes were sent/.test(await msg(b)) && mails(SINK_MAIN, '[email protected]').length === 3, await msg(b));
  481. v = await face('verifyCode', ['[email protected]', lastCode(SINK_MAIN, '[email protected]'), 'UTC', { user: { id: 1 }, data: {} }]);
  482. check('face: verifyCode with a forged trailing session is refused (no sign-in, code not spent)', v.refused === true || v.error === 'no session — reload the page', J(v));
  483. v = await face('verifyCode', ['[email protected]', 123456, 'UTC']);
  484. check('face: verifyCode with a numeric code → refused', v.error === 'email and code must be strings', J(v));
  485. // single use: the code that signed Bob in does not work twice (fresh session, REST)
  486. const bobFirst = mails(SINK_MAIN, '[email protected]')[0];
  487. const fr = await fetch(IDENT + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: 901, event: 'signOut', payload: [] }) });
  488. const freshCookie = fr.headers.get('set-cookie').split(';')[0];
  489. v = await face('verifyCode', ['[email protected]', bobFirst, 'UTC'], freshCookie);
  490. check('otp: a code that was used once is refused the second time', v.error === 'no code is waiting for this address — ask for a new one', J(v));
  491. // ---- ident#20 (mission 032): THE CODE PAGE /code SURVIVES A RELOAD --------------------------
  492. // "Send me a code" records the address in the session (face rememberPending) and goes to
  493. // /code; /code shows the code form while that code is waiting, else 302 back to the form.
  494. await b.goto(IDENT + '/');
  495. await connected(b, 'B before ident#20');
  496. const bCookie = await cookieOf(b, IDENT);
  497. check('ident#20: after "Other address" the browser is on the email form', (await step(b)) === '/ email', await step(b));
  498. check('ident#20: GET /code with nothing pending → 302 to /', (await ssr('/code', bCookie)) === '302 /', await ssr('/code', bCookie));
  499. check('ident#20: GET /code without any cookie → 302 to /', (await ssr('/code')) === '302 /', await ssr('/code'));
  500. await askCode(b, '[email protected]');
  501. check('ident#20: "Send me a code" → /code shows the code form for dave', (await step(b)) === '/code code:[email protected]', await step(b));
  502. check('ident#20: the server renders /code for this session (SSR, plain GET: 200 + code form + address)', (await ssr('/code', bCookie)) === '200 code:[email protected]', await ssr('/code', bCookie));
  503. await reload(b);
  504. check('ident#20: RELOAD of /code → still the code form, code field there, address named, no email form', (await step(b)) === '/code code:[email protected]' && await b.evaluate('!!document.querySelector("#code") && !document.querySelector("#email") && document.title === "ident | sign in"'), await step(b));
  505. await bothWidths(b, 'code-reloaded');
  506. const b2 = live(await B.newPage());
  507. await b2.goto(IDENT + '/code');
  508. await b2.waitForSelector('ident-card');
  509. check('ident#20: a SECOND TAB of the same browser opens /code with the code form too', (await step(b2)) === '/code code:[email protected]', await step(b2));
  510. await b2.close();
  511. const daveCode = lastCode(SINK_MAIN, '[email protected]');
  512. await enterCode(b, daveCode === '000000' ? '111111' : '000000');
  513. await waitMsg(b, 'wrong code', 'dave wrong code');
  514. await reload(b);
  515. check('ident#20: a WRONG code keeps it (reload → code form)', (await step(b)) === '/code code:[email protected]', await step(b));
  516. check('ident#20: one mail for dave — the reloads re-sent nothing', mails(SINK_MAIN, '[email protected]').length === 1, J(mails(SINK_MAIN, '[email protected]')));
  517. await enterCode(b, daveCode);
  518. await b.waitForSelector('#identityform');
  519. check('ident#20: the code entered after the reloads signs in (first login: welcome form), address bar back on /', (await b.text('#meemail')) === '[email protected]' && /optional/i.test(await b.text('#welcome')) && (await b.evaluate('location.pathname')) === '/', (await b.evaluate('location.pathname')) + ' ' + await b.text('ident-card'));
  520. await b.click('#skip');
  521. await b.waitFor('!document.querySelector("#identityform")', { label: 'dave skip' });
  522. await reload(b);
  523. check('ident#20: signed in → reload shows the account', (await step(b)) === '/ signedin' && (await b.text('#meemail')) === '[email protected]', await step(b));
  524. check('ident#20: signed in → GET /code is 302 to / (the sign-in cleared it)', (await ssr('/code', bCookie)) === '302 /', await ssr('/code', bCookie));
  525. await b.click('#signout');
  526. await b.waitForSelector('#emailform');
  527. await b.goto(IDENT + '/code');
  528. await b.waitForSelector('#emailform');
  529. check('ident#20: signed out again → /code in the browser lands on the email form at /', (await step(b)) === '/ email', await step(b));
  530. // "Other address" forgets it
  531. await connected(b, 'B before frank');
  532. await askCode(b, '[email protected]');
  533. check('ident#20: frank on /code', (await step(b)) === '/code code:[email protected]', await step(b));
  534. await b.click('#back');
  535. await b.waitFor('location.pathname === "/" && !!document.querySelector("#emailform")', { label: 'back to /' });
  536. check('ident#20: "Other address" → the email form at /', (await step(b)) === '/ email', await step(b));
  537. check('ident#20: "Other address" → the server forgot it (GET /code is 302 to /)', (await ssr('/code', bCookie)) === '302 /', await ssr('/code', bCookie));
  538. await reload(b);
  539. check('ident#20: "Other address" → RELOAD shows the email form', (await step(b)) === '/ email', await step(b));
  540. // a code killed by 5 wrong tries is no longer waiting → /code sends the browser back
  541. await askCode(b, '[email protected]');
  542. const ginaWrong = lastCode(SINK_MAIN, '[email protected]') === '123456' ? '654321' : '123456';
  543. for (let i = 0; i < 5; i++) {
  544. await enterCode(b, ginaWrong);
  545. await b.waitFor('/\\S/.test(document.querySelector("#message").textContent)', { label: 'gina wrong ' + (i + 1) });
  546. }
  547. check('ident#20: five wrong codes kill gina\'s code', (await msg(b)) === 'too many wrong codes — ask for a new one', await msg(b));
  548. await reload(b);
  549. check('ident#20: a killed code → reload of /code lands on the email form at /', (await step(b)) === '/ email', await step(b));
  550. // THE FACE is honest: it records only an address a code is really waiting for
  551. v = await face('rememberPending', ['[email protected]'], bCookie);
  552. check('ident#20 face: rememberPending without a waiting code → refused', v.error === 'no code is waiting for this address', J(v));
  553. check('ident#20 face: … and /code still sends this browser back (302 /)', (await ssr('/code', bCookie)) === '302 /', await ssr('/code', bCookie));
  554. v = await face('rememberPending', [5], bCookie);
  555. check('ident#20 face: rememberPending with a number → refused', v.error === 'field email must be a string', J(v));
  556. const hq = await req('POST', IDENT + '/api/code', { raw: J({ email: '[email protected]' }), headers: { 'content-type': 'application/json' } });
  557. v = await face('rememberPending', ['[email protected]', { user: null, data: {} }], bCookie);
  558. check('ident#20 face: a forged trailing session is refused', hq.status === 200 && (v.refused === true || v.error === 'no session — reload the page'), J(v));
  559. check('ident#20 face: … and nothing was recorded (302 /)', (await ssr('/code', bCookie)) === '302 /', await ssr('/code', bCookie));
  560. v = await face('rememberPending', [' [email protected] '], bCookie);
  561. check('ident#20 face: an address with a waiting code is accepted, normalised', v.email === '[email protected]', J(v));
  562. check('ident#20: … /code now shows it for THIS session only (other cookie / none → 302)', (await ssr('/code', bCookie)) === '200 code:[email protected]' && (await ssr('/code')) === '302 /' && (await ssr('/code', aliceCookie2)) === '302 /', [await ssr('/code', bCookie), await ssr('/code'), await ssr('/code', aliceCookie2)].join(' | '));
  563. v = await face('forgetPending', [], bCookie);
  564. check('ident#20 face: forgetPending → /code is 302 to / again', v === true && (await ssr('/code', bCookie)) === '302 /', J(v) + ' ' + await ssr('/code', bCookie));
  565. check('ident#20: /signin/<not a request id>/code (xyz, a CR/LF try) → 302 to / (the rid never reaches the Location header)', (await ssr('/signin/%0d%0aX:y/code', bCookie)) === '302 /' && (await ssr('/signin/xyz/code', bCookie)) === '302 /', await ssr('/signin/%0d%0aX:y/code', bCookie));
  566. check('ident#20: /signin/<rid>/code with nothing pending → 302 to /signin/<rid>', (await ssr('/signin/0123456789abcdef0123456789abcdef/code', bCookie)) === '302 /signin/0123456789abcdef0123456789abcdef', await ssr('/signin/0123456789abcdef0123456789abcdef/code', bCookie));
  567. // ---- expiry (the short-clock server) ---------------------------------------------------------
  568. await a.goto(SHORT + '/');
  569. await askCode(a, '[email protected]');
  570. const erinCode = lastCode(SINK_SHORT, '[email protected]');
  571. await reload(a);
  572. check('ident#20: short server — reload right after asking → the code form', (await step(a)) === '/code code:[email protected]', await step(a));
  573. await sleep(3500);
  574. await enterCode(a, erinCode);
  575. await waitMsg(a, 'expired', 'expired otp');
  576. check('otp: an expired code (TTL 3 s on this server) is refused', (await msg(a)) === 'the code expired — ask for a new one', await msg(a));
  577. await reload(a);
  578. check('ident#20: an EXPIRED code → reload of /code lands on the email form at /', (await step(a)) === '/ email', await step(a));
  579. await askCode(a, '[email protected]');
  580. check('ident#20: short server — ivy on /code', (await step(a)) === '/code code:[email protected]', await step(a));
  581. await sleep(3500);
  582. await reload(a);
  583. check('ident#20: expiry alone (no try) → reload of /code lands on the email form', (await step(a)) === '/ email', await step(a));
  584. // mission 010: the code request is a fetch to /api/code; its refusals (invalid address 400,
  585. // rate limit 429) make Chrome log "Failed to load resource … 400/429" — expected, shown on the page
  586. const expected = /favicon|status of (400|429) .*\/api\/code$/;
  587. const problems = [...a.problems(), ...b.problems()].filter(m => !expected.test(m.text));
  588. check('browsers: no console errors or warnings', problems.length === 0, J(problems.slice(0, 5)));
  589. // ---- mission 046: THE INSTALLABLE APP (manifest, icons, service worker) and the offline shell ------------
  590. const head = await (await fetch(IDENT + '/')).text();
  591. const link = (rel) => { const m = new RegExp(`<link rel="${rel}" href="([^"]+)"`).exec(head); return m ? m[1] : null; };
  592. const mhref = link('manifest');
  593. check('pwa: the head links the manifest, the apple-touch-icon, the favicon and the theme colour (the header colour, token darker)', mhref === '/__hl/manifest.webmanifest' && link('apple-touch-icon') === '/icons/apple-touch-icon.png' && link('icon') === '/favicon.ico' && /<meta name="theme-color" content="rgb\(15, 20, 25\)">/.test(head), J([mhref, link('apple-touch-icon'), link('icon')]));
  594. const mres = await fetch(IDENT + (mhref || '/__hl/manifest.webmanifest'));
  595. const man = await mres.json();
  596. check('pwa: manifest served as manifest JSON: name ident, start_url /start (the data-free start page), standalone, theme = header (darker), background dark', /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'ident' && man.start_url === '/start' && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', J(man));
  597. const pngOk = async (src, size) => { const r = await fetch(IDENT + src); const bb = Buffer.from(await r.arrayBuffer()); return r.ok && bb.readUInt32BE(0) === 0x89504e47 && bb.readUInt32BE(16) === size && bb.readUInt32BE(20) === size; };
  598. const iconOks = [];
  599. for (const ic of man.icons) iconOks.push(ic.type === 'image/png' && await pngOk(ic.src, Number(ic.sizes.split('x')[0])));
  600. check('pwa: every manifest icon is a real PNG of its declared size (192 + 512, any + maskable)', iconOks.length === 4 && iconOks.every(Boolean) && ['any', 'maskable'].every(pu => ['192x192', '512x512'].every(sz => man.icons.some(i => i.purpose === pu && i.sizes === sz))), J(man.icons));
  601. const fav = await fetch(IDENT + '/favicon.ico'); const favB = Buffer.from(await fav.arrayBuffer());
  602. check('pwa: apple-touch-icon is a 180 px PNG, /favicon.ico a real ICO', (await pngOk('/icons/apple-touch-icon.png', 180)) && fav.ok && favB.readUInt32BE(0) === 0x00000100, String(fav.status));
  603. r = await req('GET', IDENT + '/api/online');
  604. check('pwa: /api/online (the shell\'s network probe) answers 204, not cached', r.status === 204 && r.text === '', String(r.status));
  605. // THE OFFLINE COPY HOLDS NO PERSONAL DATA (ident is the identity provider; shared devices): browser A
  606. // is signed in; with the network gone neither `/` nor `/start`, nor anything in the worker's caches
  607. // or hl:web's IndexedDB, may contain the account's address or an identity name
  608. const w = live(await A.newPage());
  609. await viewport(w, 390, 844);
  610. await w.goto(IDENT + '/');
  611. await w.waitForSelector('#meemail');
  612. await connected(w, 'pwa page');
  613. const myEmail = (await w.text('#meemail')).trim();
  614. // the identity as it would leak: its details line (names) — a bare label like "Work" is also a word in the framework's code
  615. const myIdentity = await w.evaluate('(document.querySelector("#identities identity-details") || {}).textContent || ""');
  616. check('pwa: browser A is signed in (the data that must not be kept offline)', /@example\.org$/.test(myEmail) && myIdentity !== '', myEmail + ' ' + myIdentity);
  617. await w.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { label: 'service worker active', timeout: 15000 });
  618. check('pwa: a service worker is registered for the whole app (scope /) and controls the page', await w.evaluate(`navigator.serviceWorker.getRegistration().then(r => !!r && new URL(r.scope).pathname === '/' && !!navigator.serviceWorker.controller)`));
  619. const inst = await w.send('Page.getInstallabilityErrors');
  620. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));
  621. await sleep(1500); // the probe's first ask (0.5 s after the page is up)
  622. check('pwa: online, the header says nothing about offline', await w.evaluate('!document.querySelector("#offline") && !!document.querySelector("application-header")'));
  623. // the installed app starts at /start: online it goes on to / by itself (the shell's probe)
  624. await w.goto(IDENT + '/start');
  625. await w.waitFor('location.pathname === "/" && !!document.querySelector("#meemail")', { label: '/start → /', timeout: 8000 }).catch(() => {});
  626. check('pwa: online, /start (the start_url) goes on to / (signed in)', await w.evaluate('location.pathname === "/" && !!document.querySelector("#meemail")'), await w.evaluate('location.pathname'));
  627. await connected(w, 'pwa / again');
  628. // everything this browser keeps offline, as text: every response in the worker's caches + hl:web's IndexedDB
  629. const keptText = () => w.evaluate(`(async () => {
  630. let out = '';
  631. for (const name of await caches.keys()) { const c = await caches.open(name); for (const rq of await c.keys()) { const r = await c.match(rq); out += '\\n' + rq.url + '\\n' + await r.clone().text(); } }
  632. const db = await new Promise((res) => { const q = indexedDB.open('hl-offline'); q.onsuccess = () => res(q.result); q.onerror = () => res(null); });
  633. if (db) { for (const st of db.objectStoreNames) { const all = await new Promise((res) => { const q = db.transaction(st).objectStore(st).getAll(); q.onsuccess = () => res(q.result); q.onerror = () => res([]); }); out += '\\n' + JSON.stringify(all); } db.close(); }
  634. return out;
  635. })()`);
  636. // NO NETWORK: the tab AND the service worker (a separate CDP target — the tab's emulation alone
  637. // leaves the worker's fetches online, measured) are cut off
  638. const swSessions = {};
  639. const swOffline = async (on) => {
  640. const { targetInfos } = await A.conn.send('Target.getTargets');
  641. const sws = targetInfos.filter(t => t.type === 'service_worker' && t.url.startsWith(IDENT));
  642. for (const t of sws) {
  643. const sid = swSessions[t.targetId] ||= (await A.conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true })).sessionId;
  644. await A.conn.send('Network.enable', {}, sid);
  645. await A.conn.send('Network.emulateNetworkConditions', { offline: on, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, sid);
  646. }
  647. return sws.length;
  648. };
  649. const nSw = await swOffline(true);
  650. await w.setOffline(true);
  651. const cutOff = await w.evaluate(`Promise.resolve(window.__hlAttempt(() => fetch('/api/online', { cache: 'no-store' }))).then(r => !r.ok)`);
  652. check('pwa: offline set up (the worker and the tab cannot reach ident)', nSw === 1 && cutOff, `${nSw} ${cutOff}`);
  653. // a real reload of the signed-in `/`: it is not kept, so the worker answers its data-free "Unavailable offline"
  654. await w.send('Page.reload');
  655. await w.waitFor('!!document.querySelector("main[data-hl-offline]") || !!document.querySelector("application-header")', { label: 'offline reload of /', timeout: 15000 }).catch(() => {});
  656. let doc = await w.evaluate('document.documentElement.outerHTML');
  657. check('pwa: OFFLINE reload of the signed-in / → the worker\'s "Unavailable offline" page, NO email or identity in it', /Unavailable offline/.test(doc) && !doc.includes(myEmail) && !doc.includes(myIdentity), doc.slice(0, 300));
  658. // the installed app's start: the data-free shell from the cache, and it says it is offline
  659. await w.goto(IDENT + '/start').catch(() => {});
  660. await w.waitFor('!!document.querySelector("application-header") && !!document.querySelector("#start")', { label: 'offline /start', timeout: 15000 }).catch(() => {});
  661. await w.waitFor('!!document.querySelector("#offline")', { label: 'offline note', timeout: 8000 }).catch(() => {});
  662. check('pwa: OFFLINE /start (the start_url) shows the shell (header, start card) from the worker', await w.evaluate('location.pathname === "/start" && !!document.querySelector("application-header a.brand") && !!document.querySelector("#start")'), await w.evaluate('document.body.innerText.slice(0, 200)'));
  663. check('pwa: … and the header says it is offline', (await w.evaluate('(document.querySelector("#offline") || {}).textContent || ""')) === 'Offline — ident needs the network to sign in and to save', await w.evaluate('document.body.innerText.slice(0, 200)'));
  664. doc = await w.evaluate('document.documentElement.outerHTML');
  665. check('pwa: … and it contains NO email or identity of the signed-in user', !doc.includes(myEmail) && !doc.includes(myIdentity) && !/@example\.org/.test(doc));
  666. const kept = await keptText();
  667. check('pwa: NOTHING the browser keeps offline (worker caches + hl:web IndexedDB) holds the email or an identity', kept.length > 1000 && !kept.includes(myEmail) && !kept.includes(myIdentity) && !/@example\.org/.test(kept), kept.length + ' chars; hits: ' + [myEmail, myIdentity, '@example.org'].map(x => kept.indexOf(x)).join(' ') + ' ' + J(myIdentity));
  668. await shot(w, 'phone-pwa-offline');
  669. check('layout: 390px offline shell has no horizontal overflow', await noOverflow(w));
  670. await w.goto(IDENT + '/apps').catch(() => {});
  671. await w.waitFor('!!document.querySelector("main[data-hl-offline]")', { label: 'offline /apps', timeout: 8000 }).catch(() => {});
  672. check('pwa: offline, a data page (/apps) needs the network: the worker\'s "Unavailable offline" page', await w.evaluate('location.pathname === "/apps" && /Unavailable offline/.test(document.body.textContent)'), await w.evaluate('document.body.innerText.slice(0, 200)'));
  673. // back online, the start page opens ident by itself
  674. await w.goto(IDENT + '/start').catch(() => {});
  675. await w.waitForSelector('#start');
  676. await swOffline(false);
  677. await w.setOffline(false);
  678. await w.waitFor('location.pathname === "/" && !!document.querySelector("#meemail")', { label: 'back online → /', timeout: 30000 }).catch(() => {});
  679. await connected(w, 'pwa back online').catch(() => {});
  680. await sleep(1000);
  681. check('pwa: back online, the offline start page goes on to / by itself (signed in, no offline note)', await w.evaluate('location.pathname === "/" && !!document.querySelector("#meemail") && !document.querySelector("#offline")'), await w.evaluate('location.pathname + " " + document.body.innerText.slice(0, 120)'));
  682. await shot(w, 'phone-pwa-online');
  683. await w.close();
  684. } catch (e) {
  685. failures++;
  686. console.log('FAIL (aborted) ' + (e && e.stack || e));
  687. for (const [n, pg] of [['A', a], ['B', b]]) if (pg) console.log(`console ${n}: ` + J(pg.messages.slice(-8)));
  688. } finally {
  689. for (const br of [A, B]) { if (br) { try { await br.close(); } catch {} } }
  690. for (const { p } of procs) { try { p.kill('SIGTERM'); } catch {} }
  691. await sleep(500);
  692. for (const { p } of procs) { if (p.exitCode === null && p.signalCode === null) { try { p.kill('SIGKILL'); } catch {} } }
  693. await sleep(200);
  694. console.log(`\n${passes} passed, ${failures} failed`);
  695. process.exit(failures ? 1 : 0);
  696. }

Branches

Latest commits

  • b96796bdtests: wait for hydration before real clicks after a navigation (H2)mre
  • 9722964fre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • c9b196c9tests/iplimit: wait for the welcome form itself after B's first login (identities list renders before it); mission 017 reportmre
  • 72e0f587ident#26: identity page with "Used in" (app, since, last use, Notif. chip, empty state); lastLogin recorded at exchange; gates + lisbeth E2E; mission 016 reportmre
  • 94576fbcident#26 WIP: identity page /identity/:iid with "Used in" (app, since, last use, Notif. chip), lastLogin recorded at exchange, "Used in…" link on the identities list; apps gate 4b, e2e-usedin.mjsmre
  • 349cb502tests/invites: wait for hydration on the code page before entering the code (native GET submit raced the welcome form); mission 015 reportmre
  • d1bf4720tests: no hard-coded ports — every gate's ports and fixture origins come from <GATE>_PORT / _CHROME env (defaults unchanged; Bob/fixture origins follow, selector cookie name too)mre
  • 6280c92fre-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • 147744bftests/migration: the fixture app origin follows MIGRATION_GATE_TESTAPP_PORT (oldstore-009 OLD_TESTAPP)mre
  • 48cd36bctests/migration: ports from env (MIGRATION_GATE_PORT, MIGRATION_GATE_TESTAPP_PORT); 8395/8396 were taken by a foreign servermre
  • 3d9b2fd8docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 19b7e3c3deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • c8a596f4re-vendor Hybriel 66c3db71 (web batch 4); e2e: main menu marked after in-place sign-in is a normal check; report 014mre
  • 8f3dc1ectests: delivery allow-list for the stopped server's network errors uses the gate port, not 8700mre
  • 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