gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit0d18abc40d18abc4Merge branch 'f13-avatar' into mainIdent0d18abc4/tests/browser.mjs

65.1 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. // the account's Sign out / Sign out everywhere live in the header's user menu (the home page's own buttons were dropped 2026-10-24: the same account was shown twice): a real tap on the icon, then on the entry
  94. const menuClick = async (page, id) => { await page.click('application-header user-menu > button'); await page.waitFor('document.querySelector("#user-menu").matches(":popover-open")', { label: 'user menu open' }); await page.click(id); };
  95. async function viewport(page, width, height) {
  96. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  97. await sleep(250);
  98. }
  99. async function shot(page, name) {
  100. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  101. writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));
  102. }
  103. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  104. async function bothWidths(page, name) {
  105. await viewport(page, 390, 844); await shot(page, 'phone-' + name);
  106. check(`layout: 390px ${name} has no horizontal overflow`, await noOverflow(page));
  107. await viewport(page, 1280, 900); await shot(page, 'desktop-' + name);
  108. check(`layout: 1280px ${name} has no horizontal overflow`, await noOverflow(page));
  109. }
  110. const msg = (page) => page.text('#message');
  111. const waitMsg = (page, re, label) => page.waitFor(`/${re}/.test((document.querySelector('#message') || {}).textContent || '')`, { label });
  112. const waitNotice = (page, re, label) => page.waitFor(`/${re}/.test((document.querySelector('#notice') || {}).textContent || '')`, { label });
  113. // the identity list as the page shows it: [{ label, details, isDefault, edit, del }]
  114. 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[name=edit]'), del: !!li.querySelector('button[name=delete]') }))`);
  115. const labels = async (page) => (await listed(page)).map(r => r.label);
  116. // click a row's button by the row's label
  117. async function rowButton(page, label, cls) {
  118. 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[name=${cls}]'); if (!b) return null; b.id = 'gate-target'; return '#gate-target'; })()`);
  119. if (!sel) throw new Error(`no ${cls} button for ${label}`);
  120. await page.click(sel);
  121. await page.evaluate(`document.querySelector('#gate-target') && document.querySelector('#gate-target').removeAttribute('id')`);
  122. }
  123. // window.confirm: answer the NEXT dialog of this page with `accept`
  124. function dialogs(page) {
  125. page.dialogAnswer = true;
  126. page.dialogTexts = [];
  127. page.conn.onEvent(m => {
  128. if (m.method === 'Page.javascriptDialogOpening' && m.sessionId === page.sessionId) {
  129. page.dialogTexts.push(m.params.message);
  130. page.send('Page.handleJavaScriptDialog', { accept: page.dialogAnswer }).catch(() => {});
  131. }
  132. });
  133. }
  134. // THE LOGIN AS A PERSON DOES IT: type the address, click, read the mail, type the code
  135. async function askCode(page, email) {
  136. await page.waitForSelector('#email');
  137. await connected(page, 'socket before asking');
  138. await page.type('#email', email, { clear: true });
  139. await page.evaluate('document.querySelector("#message").textContent = ""');
  140. await page.click('#sendcode');
  141. // ident#20: a sent code NAVIGATES to the code page (/code); a refusal stays with a message
  142. await page.waitFor('(/\\/code$/.test(location.pathname) && !!document.querySelector("#code")) || /\\S/.test(document.querySelector("#message").textContent)', { label: 'code page or message after ' + email });
  143. if (await page.evaluate('/\\/code$/.test(location.pathname)')) await connected(page, 'code page hydrated');
  144. }
  145. // A REAL RELOAD (Page.reload, like a phone reloading the tab), then the hydrated socket
  146. async function reload(page) {
  147. page._loaded = false;
  148. await page.send('Page.reload', { ignoreCache: false });
  149. const deadline = Date.now() + 15000;
  150. while (!page._loaded && Date.now() < deadline) await sleep(25);
  151. if (!page._loaded) throw new Error('reload: load event never fired');
  152. await connected(page, 'socket after reload');
  153. }
  154. // what the page shows: '<path> code:<address>' | '<path> email' | '<path> signedin' | '<path> ?'
  155. 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('#whoami') ? 'signedin' : '?')))`);
  156. // what the SERVER answers a plain GET with this cookie (no JS, no redirect following):
  157. // '302 <location>' or '200 code:<address>' / '200 email' / '200 signedin'
  158. async function ssr(path, cookie, base = IDENT) {
  159. const r = await fetch(base + path, { redirect: 'manual', headers: cookie ? { cookie } : {} });
  160. if (r.status >= 300 && r.status < 400) return r.status + ' ' + r.headers.get('location');
  161. const t = await r.text();
  162. const m = /id="sentto"[^>]*>.*?<strong[^>]*>([^<]*)</s.exec(t);
  163. return r.status + ' ' + (t.includes('id="codeform"') && m ? 'code:' + m[1] : (t.includes('id="emailform"') ? 'email' : (t.includes('id="whoami"') ? 'signedin' : '?')));
  164. }
  165. const cookieOf = async (page, url) => (await page.cookies([url])).filter(c => c.name === 'identsid').map(c => `identsid=${c.value}`)[0];
  166. async function enterCode(page, code) {
  167. await page.evaluate('document.querySelector("#message").textContent = ""');
  168. await page.type('#code', code, { clear: true });
  169. await page.click('#verify');
  170. }
  171. async function fill(page, values) {
  172. for (const [id, v] of Object.entries(values)) await page.type('#' + id, v, { clear: true });
  173. }
  174. // a PNG 300×200 (left half red, right half blue) and a text file, for the avatar upload
  175. function makePng() {
  176. const W = 300, H = 200, raw = Buffer.alloc((W * 3 + 1) * H);
  177. 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; }
  178. 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; }
  179. const crc = (b) => { let c = 0xffffffff; for (const x of b) c = crcT[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
  180. 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]); };
  181. const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(W, 0); ihdr.writeUInt32BE(H, 4); ihdr[8] = 8; ihdr[9] = 2;
  182. 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))]);
  183. }
  184. const PNG_FILE = join(STORE, 'avatar.png'), TXT_FILE = join(STORE, 'avatar.txt');
  185. writeFileSync(PNG_FILE, makePng()); writeFileSync(TXT_FILE, 'not a picture');
  186. // pick a file in an <input type=file> like a person does (the browser's own file chooser result)
  187. async function upload(page, selector, file) {
  188. const { root } = await page.send('DOM.getDocument');
  189. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector });
  190. await page.send('DOM.setFileInputFiles', { files: [file], nodeId });
  191. }
  192. // a PASTE (one input event with the whole value), unlike page.type()'s per-character keys —
  193. // used for the avatar URL so a live `src`-bound preview does not fetch every half-typed prefix
  194. async function paste(page, selector, text) {
  195. await page.evaluate(`(() => { const el = document.querySelector(${J(selector)}); el.value = ${J(text)}; el.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  196. }
  197. let A, B, a, b;
  198. try {
  199. for (const [name, url] of [['main', IDENT + '/'], ['short', `http://127.0.0.1:${P_SHORT}/`]]) {
  200. let up = false;
  201. 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)
  202. if (!up) throw new Error(`${name} server did not come up\n` + procs.find(p => p.name === name).log());
  203. }
  204. // ---- the mission-003 app flow is gone; piece 2 rebuilt /login and /api/exchange ------------
  205. // (ticket #37: these two checks asserted 404s from before piece 2; they now check that the
  206. // mission-003 shapes are refused by the piece-2 routes. The full piece-2 rules: tests/apps.mjs)
  207. let r = await req('POST', IDENT + '/api/exchange', { raw: '{"code":"x"}', headers: { 'content-type': 'application/json' } });
  208. 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));
  209. r = await req('GET', IDENT + '/login?app=testclient&return=http://127.0.0.1:' + (P_MAIN + 2) + '/callback');
  210. 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}`);
  211. r = await req('GET', IDENT + '/continue/abc');
  212. check('removed: GET /continue/<rid> is 404', r.status === 404, String(r.status));
  213. // ---- faces without a session ----------------------------------------------------------------
  214. let v = await face('addIdentity', [{ identityName: 'X' }]);
  215. check('face: addIdentity without a session → not signed in', v.error === 'you are not signed in', J(v));
  216. v = await face('changeTimeZone', ['Europe/Vienna']);
  217. check('face: changeTimeZone without a session → not signed in', v.error === 'you are not signed in', J(v));
  218. A = await launchBrowser({ debugPortRange: [CHROME[0], CHROME_MID] });
  219. B = await launchBrowser({ debugPortRange: [CHROME_MID + 1, CHROME[1]] });
  220. a = live(await A.newPage());
  221. b = live(await B.newPage());
  222. dialogs(a); dialogs(b);
  223. await a.send('Emulation.setTimezoneOverride', { timezoneId: TZ_A });
  224. await b.send('Emulation.setTimezoneOverride', { timezoneId: TZ_B });
  225. // ---- browser A: the first login creates the account --------------------------------------------
  226. await a.goto(IDENT + '/');
  227. await a.waitForSelector('#emailform');
  228. await connected(a, 'A connected');
  229. 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'));
  230. check('home: the page says there is no sign-up', /no sign-up/.test(await a.text('ident-card')), await a.text('ident-card'));
  231. 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)'; })()`));
  232. await bothWidths(a, 'signin');
  233. await askCode(a, 'foo@bar');
  234. check('login: an address without a dotted domain is refused', (await msg(a)) === 'that is not an email address', await msg(a));
  235. await askCode(a, ' [email protected] ');
  236. check('login: code form shows the LOWERCASED address', (await a.text('#sentto strong')) === '[email protected]', await a.text('#sentto'));
  237. check('ident#20: "Send me a code" lands on the code page /code', (await step(a)) === '/code code:[email protected]', await step(a));
  238. const aliceCode1 = lastCode(SINK_MAIN, '[email protected]');
  239. 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'));
  240. await bothWidths(a, 'code');
  241. await enterCode(a, aliceCode1 === '000000' ? '111111' : '000000');
  242. await waitMsg(a, 'wrong code', 'wrong code message');
  243. check('login: a wrong code says so and counts down', (await msg(a)) === 'wrong code (4 tries left)', await msg(a));
  244. await enterCode(a, aliceCode1);
  245. await a.waitForSelector('#identityform');
  246. 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)));
  247. 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'));
  248. 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', '', '', '']));
  249. check('time zone: the browser\'s (emulated ' + TZ_A + ') was stored at first use', (await a.text('#timezone')) === TZ_A, await a.text('#timezone'));
  250. await bothWidths(a, 'welcome');
  251. // SKIPPED: the form closes, the default identity stays as it is
  252. await a.click('#skip');
  253. await a.waitFor('!document.querySelector("#identityform")', { label: 'welcome closed' });
  254. 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)));
  255. await a.goto(IDENT + '/');
  256. await a.waitForSelector('#identities');
  257. check('reload: still signed in (SSR), identities and time zone read back, no welcome again', (await a.text('#whoami')) === '[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'));
  258. check('title: signed in', (await a.evaluate('document.title')) === 'ident | your identities', await a.evaluate('document.title'));
  259. // IW (creator 2026-10-24): the home page showed the signed-in account TWICE (its own account bar and the header's user menu, same email,
  260. // same Sign out / Sign out everywhere). Now only the user menu carries them — on EVERY signed-in page, at 390 and 1280 — and the home page keeps no copy
  261. for (const [w, h] of [[390, 844], [1280, 900]]) {
  262. await viewport(a, w, h);
  263. for (const path of ['/', '/apps', '/inbox']) {
  264. await a.goto(IDENT + path);
  265. await a.waitForSelector('#menusignout');
  266. await connected(a, 'IW ' + path);
  267. await a.click('application-header user-menu > button');
  268. await a.waitFor('document.querySelector("#user-menu").matches(":popover-open")', { label: 'user menu open' });
  269. const um = await a.evaluate(`(() => { const box = (s) => { const e = document.querySelector(s); const r = e && e.getBoundingClientRect(); return r && { w: r.width, h: r.height, r: r.right, b: r.bottom }; }; return { who: (document.querySelector('#whoami') || {}).textContent, out: box('#menusignout'), all: box('#menusignoutall'), vw: innerWidth }; })()`);
  270. check(`IW ${w}px ${path}: the user menu offers the email, Sign out and Sign out everywhere (44 px taps, inside the screen)`, um.who === '[email protected]' && um.out && um.all && um.out.h >= 43.5 && um.all.h >= 43.5 && um.out.r <= um.vw + 0.5 && um.all.r <= um.vw + 0.5, J(um));
  271. if (path === '/') await shot(a, `iw-home-menu-${w}`);
  272. await a.evaluate('document.querySelector("#user-menu").hidePopover()');
  273. }
  274. await a.goto(IDENT + '/');
  275. await a.waitForSelector('#identities');
  276. check(`IW ${w}px home: the account is shown once — no account bar, no own Sign out buttons, no second copy of the email`, await a.evaluate('!document.querySelector("account-bar") && !document.querySelector("#signout") && !document.querySelector("#signoutall") && !document.querySelector("#meemail") && [...document.querySelectorAll("main *")].filter(e => e.children.length === 0 && e.textContent.trim() === "[email protected]").length === 0'));
  277. await shot(a, `iw-home-${w}`);
  278. }
  279. await viewport(a, 1280, 900);
  280. await a.goto(IDENT + '/');
  281. await a.waitForSelector('#identities');
  282. 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])));
  283. const aliceCookie = (await a.cookies([IDENT])).filter(c => c.name === 'identsid').map(c => `identsid=${c.value}`)[0];
  284. // EDIT the default identity: all four fields
  285. await connected(a, 'A before edit');
  286. await rowButton(a, 'Default', 'edit');
  287. await a.waitForSelector('#identityform');
  288. 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'));
  289. await fill(a, { fidentityname: 'Private', fnickname: 'Ali', ffirstname: 'Alice', flastname: 'Example' });
  290. await upload(a, '#favatarfile', TXT_FILE);
  291. await a.waitFor(`document.querySelector('#avatarnote').textContent.length > 0`, { label: 'avatar: text file refused' });
  292. 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'));
  293. await upload(a, '#favatarfile', PNG_FILE);
  294. await a.waitFor(`document.querySelector('#favatar').value.startsWith('data:image/')`, { label: 'avatar: picture scaled' });
  295. 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.hasAttribute('hidden') && document.querySelector('#favatar').value.length < 60000; })()`), await a.evaluate(`document.querySelector('#favatar').value.slice(0, 40)`));
  296. 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; })()`));
  297. await bothWidths(a, 'edit');
  298. await a.click('#saveidentity');
  299. await waitNotice(a, 'Identity saved', 'saved notice');
  300. 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)));
  301. check('avatar: the identity list shows a round avatar image with the saved picture', await a.evaluate(`(() => { const img = document.querySelector('#identities li img'); return !!img && img.src.startsWith('data:image/') && img.naturalWidth === 128; })()`), await a.evaluate(`document.querySelector('#identities').innerHTML`));
  302. // reopening the edit form shows the saved avatar again, and typing focus survives (ticket #15
  303. // regression: an `if` next to the text inputs in the SAME view made hl:webex recreate the
  304. // form on every keystroke, losing focus after one character — hybriel #32)
  305. await rowButton(a, 'Private', 'edit');
  306. await a.waitForSelector('#identityform');
  307. 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').hasAttribute('hidden')`));
  308. await a.focus('#fnickname');
  309. await a.send('Input.dispatchKeyEvent', { type: 'keyDown', text: 'z', unmodifiedText: 'z', key: 'z' });
  310. await a.send('Input.dispatchKeyEvent', { type: 'keyDown', text: 'z', unmodifiedText: 'z', key: 'z' });
  311. 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');
  312. await a.click('#avatarremove');
  313. check('avatar: "Remove picture" hides the preview again', await a.evaluate(`document.querySelector('#avatarpreview').hasAttribute('hidden')`));
  314. await a.click('#cancel');
  315. await a.waitFor('!document.querySelector("#identityform")', { label: 'avatar-check cancel closes' });
  316. // A SECOND identity, then a third with NO fields at all
  317. await a.click('#newidentity');
  318. await a.waitForSelector('#identityform');
  319. 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(['', '', '', '']));
  320. await fill(a, { fidentityname: 'Work', ffirstname: 'Alice', flastname: 'Example-Work' });
  321. await a.click('#saveidentity');
  322. await waitNotice(a, 'Identity created', 'created notice');
  323. check('new: the second identity is listed; now both can be deleted, the first stays default', J(await listed(a)) === J([
  324. { label: 'Private', details: '“Ali” · Alice Example', isDefault: true, edit: true, del: true },
  325. { label: 'Work', details: 'Alice Example-Work', isDefault: false, edit: true, del: true }]), J(await listed(a)));
  326. // hybriel#121 (mission 048): a face taking the session syncs the session-derived list back — a row added on top would show twice
  327. 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)));
  328. await a.click('#newidentity');
  329. await a.waitForSelector('#identityform');
  330. await a.click('#saveidentity');
  331. await waitNotice(a, 'Identity created', 'created notice 3');
  332. 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)));
  333. // cancel does not save
  334. await rowButton(a, 'Work', 'edit');
  335. await a.waitForSelector('#identityform');
  336. await fill(a, { fnickname: 'SHOULD-NOT-SAVE' });
  337. await a.click('#cancel');
  338. await a.waitFor('!document.querySelector("#identityform")', { label: 'cancel closes' });
  339. // edit the second one
  340. await rowButton(a, 'Work', 'edit');
  341. await a.waitForSelector('#identityform');
  342. 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)')));
  343. await fill(a, { fnickname: 'AE' });
  344. await a.click('#saveidentity');
  345. await waitNotice(a, 'Identity saved', 'saved notice 2');
  346. await a.goto(IDENT + '/');
  347. await a.waitForSelector('#identities');
  348. check('reload: three identities as saved', J(await listed(a)) === J([
  349. { label: 'Private', details: '“Ali” · Alice Example', isDefault: true, edit: true, del: true },
  350. { label: 'Work', details: '“AE” · Alice Example-Work', isDefault: false, edit: true, del: true },
  351. { label: 'Identity 3', details: 'no names', isDefault: false, edit: true, del: true }]), J(await listed(a)));
  352. await bothWidths(a, 'identities');
  353. // DELETE: a dismissed confirm keeps it; accepted removes it; the last one cannot go
  354. await connected(a, 'A before delete');
  355. a.dialogAnswer = false;
  356. await rowButton(a, 'Identity 3', 'delete');
  357. await sleep(500);
  358. 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)));
  359. a.dialogAnswer = true;
  360. await rowButton(a, 'Identity 3', 'delete');
  361. await waitNotice(a, 'Identity deleted', 'deleted notice');
  362. check('delete: accepted → gone', J(await labels(a)) === J(['Private', 'Work']), J(await labels(a)));
  363. await rowButton(a, 'Private', 'delete');
  364. await a.waitFor(`document.querySelectorAll('#identities li').length === 1`, { label: 'default deleted' });
  365. 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)));
  366. // ids are mpackdb UUIDs (mission 009): read Alice's remaining identity's id off its Edit button
  367. const aliceWorkId = await a.evaluate('document.querySelector("#identities li [name=edit]").value');
  368. check('ids: an identity id is a 12-char mpackdb UUID (not a number)', /^[0-9a-z]{12}$/.test(aliceWorkId), J(aliceWorkId));
  369. v = await face('dropIdentity', [aliceWorkId], aliceCookie);
  370. check('face: deleting the LAST identity is refused', v.error === 'this is your only identity — an account always keeps one', J(v));
  371. await a.goto(IDENT + '/');
  372. await a.waitForSelector('#identities');
  373. check('reload: the last identity is still there', J(await labels(a)) === J(['Work']), J(await labels(a)));
  374. // TIME ZONE: change, browser button, unknown name refused in the page
  375. await connected(a, 'A before tz');
  376. await a.type('#tzinput', 'Mars/Olympus_Mons', { clear: true });
  377. await a.click('#savetz');
  378. await waitMsg(a, 'does not know', 'unknown zone');
  379. 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));
  380. await a.type('#tzinput', 'Europe/Vienna', { clear: true });
  381. await a.click('#savetz');
  382. await waitNotice(a, 'Time zone saved', 'tz saved');
  383. check('time zone: changed to Europe/Vienna', (await a.text('#timezone')) === 'Europe/Vienna', await a.text('#timezone'));
  384. await a.click('#browsertz');
  385. await a.waitFor(`document.querySelector('#tzinput').value === ${J(TZ_A)}`, { label: 'browser tz button' });
  386. check('time zone: "Use this browser\'s" fills in the browser\'s zone (not saved yet)', (await a.text('#timezone')) === 'Europe/Vienna');
  387. await a.goto(IDENT + '/');
  388. await a.waitForSelector('#timezone');
  389. check('reload: the time zone reads back Europe/Vienna', (await a.text('#timezone')) === 'Europe/Vienna' && (await a.evaluate('document.querySelector("#tzinput").value')) === 'Europe/Vienna');
  390. // SIGN OUT, then a known address signs in: no welcome, the time zone is NOT reset
  391. await connected(a, 'A before sign out');
  392. await a.evaluate('window.__m = 1');
  393. await menuClick(a, '#menusignout');
  394. await a.waitForSelector('#emailform');
  395. check('sign out (user menu): the page reloads into the sign-in, the header has no user menu and no main menu any more', await a.evaluate('!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'));
  396. await a.goto(IDENT + '/');
  397. await a.waitForSelector('#emailform');
  398. check('sign out: the reload is signed out', !(await a.evaluate('!!document.querySelector("#identities")')));
  399. v = await face('addIdentity', [{ identityName: 'after sign out' }], aliceCookie);
  400. check('face: the signed-out cookie cannot add an identity', v.error === 'you are not signed in', J(v));
  401. await askCode(a, '[email protected]');
  402. await enterCode(a, lastCode(SINK_MAIN, '[email protected]'));
  403. await a.waitForSelector('#identities');
  404. await sleep(300);
  405. 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'));
  406. await enterCode(a, lastCode(SINK_MAIN, '[email protected]')).catch(() => {});
  407. const aliceCookie2 = (await a.cookies([IDENT])).filter(c => c.name === 'identsid').map(c => `identsid=${c.value}`)[0];
  408. // ---- browser B: first login, names FILLED at the welcome; wrong codes; rate limit ----------------
  409. await b.goto(IDENT + '/');
  410. await askCode(b, '[email protected]');
  411. await b.evaluate('window.__m = 1');
  412. await enterCode(b, lastCode(SINK_MAIN, '[email protected]'));
  413. await b.waitForSelector('#identityform');
  414. check('B first login: time zone ' + TZ_B + ' from this browser', (await b.text('#timezone')) === TZ_B, await b.text('#timezone'));
  415. await fill(b, { fidentityname: 'Bob', fnickname: 'Bobby', ffirstname: 'Bob', flastname: 'Builder' });
  416. // mission 013 (hybriel#193): the page's emit reaches the shell — no reload anywhere in this flow. `__m` survives only without one.
  417. 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'));
  418. await b.click('#saveidentity');
  419. await b.waitFor('!document.querySelector("#identityform") && /Identity saved/.test(document.querySelector("#notice").textContent)', { label: 'B saved: the "Identity saved." notice' });
  420. 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'));
  421. 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)));
  422. const bobCookie = (await b.cookies([IDENT])).filter(c => c.name === 'identsid').map(c => `identsid=${c.value}`)[0];
  423. // FACE NEGATIVES (Bob's cookie): strict fields, other accounts' identities, time zone shapes
  424. const neg = [
  425. ['unknown field', ['addIdentity', [{ identityName: 'x', email: '[email protected]' }]], { error: 'unknown field: email', field: 'email' }],
  426. ['wrong type', ['addIdentity', [{ nickname: 5 }]], { error: 'field nickname must be a string', field: 'nickname' }],
  427. ['null value', ['addIdentity', [{ nickname: null }]], { error: 'field nickname must be a string', field: 'nickname' }],
  428. ['fields a list', ['addIdentity', [['x']]], { error: 'the identity fields must be an object', field: '' }],
  429. ['fields a string', ['addIdentity', ['x']], { error: 'the identity fields must be an object', field: '' }],
  430. ['61 characters', ['addIdentity', [{ lastname: 'x'.repeat(61) }]], { error: 'field lastname is longer than 60 characters', field: 'lastname' }],
  431. ['control character', ['addIdentity', [{ firstname: 'a\u0007b' }]], { error: 'field firstname contains a control character', field: 'firstname' }],
  432. ['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' }],
  433. ['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' }],
  434. ['avatar: wrong bytes for the type', ['addIdentity', [{ avatar: 'data:image/png;base64,AAAAAAAAAAAA' }]], { error: 'field avatar is not a valid picture', field: 'avatar' }],
  435. ['avatar: not base64', ['addIdentity', [{ avatar: 'data:image/png;base64,iVBORw0KGgo<script>' }]], { error: 'field avatar is not valid base64', field: 'avatar' }],
  436. ['avatar: too long', ['addIdentity', [{ avatar: 'data:image/png;base64,iVBORw0KGgo' + 'A'.repeat(60000) }]], { error: 'field avatar is longer than 60000 characters', field: 'avatar' }],
  437. ['avatar: wrong type', ['addIdentity', [{ avatar: 5 }]], { error: 'field avatar must be a string', field: 'avatar' }],
  438. ['edit: another account\'s identity', ['editIdentity', [aliceWorkId, { nickname: 'hacked' }]], { error: 'no such identity', field: 'id' }],
  439. ['edit: id as a number (the old numeric ids)', ['editIdentity', [2, { nickname: 'x' }]], { error: 'no such identity', field: 'id' }],
  440. ['edit: unknown id', ['editIdentity', ['0zzzzzzzzzzz', {}]], { error: 'no such identity', field: 'id' }],
  441. ['delete: another account\'s identity', ['dropIdentity', [aliceWorkId]], { error: 'no such identity' }],
  442. ['delete: an old numeric id', ['dropIdentity', [2]], { error: 'no such identity' }],
  443. ['delete: own last identity', ['dropIdentity', ['(Bob\'s)']], { error: 'this is your only identity — an account always keeps one' }],
  444. ['time zone: bad characters', ['changeTimeZone', ['Europe/Vienna; x']], { error: 'that is not a time zone name (like Europe/Vienna)' }],
  445. ['time zone: a number', ['changeTimeZone', [5]], { error: 'the time zone must be a string' }],
  446. ['time zone: empty', ['changeTimeZone', [' ']], { error: 'the time zone is empty' }],
  447. ];
  448. const bobIds = await face('addIdentity', [{}], bobCookie); // a 2nd identity: learn Bob's ids
  449. const bobRows = bobIds.identities || [];
  450. check('face: Bob can add an identity with an empty object', bobRows.length === 2, J(bobIds));
  451. await face('dropIdentity', [bobRows[1] && bobRows[1].id], bobCookie);
  452. for (const [label, [ev, payload], want] of neg) {
  453. // `own last identity` must name Bob's id
  454. const p = label === 'delete: own last identity' ? [bobRows[0].id] : payload;
  455. v = await face(ev, p, bobCookie);
  456. check(`face negative: ${label}`, J(v) === J(want), J(v));
  457. }
  458. // IMPERSONATION: a hand-made frame with one argument too many puts ITS object where the
  459. // session goes (hybriel: positional trailing session); ident only takes a real session
  460. v = await face('addIdentity', [{ identityName: 'forged' }, { user: { id: 1 }, data: {} }]);
  461. check('face: a forged session object (extra argument, no cookie) is refused', v.refused === true || v.error === 'you are not signed in', J(v));
  462. v = await face('dropIdentity', [aliceWorkId, { user: { id: 1 }, data: {} }], bobCookie);
  463. 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));
  464. await a.goto(IDENT + '/');
  465. await a.waitForSelector('#identities');
  466. 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)));
  467. v = await face('changeTimeZone', ['UTC'], aliceCookie2);
  468. check('face: UTC is a valid zone', v.timeZone === 'UTC', J(v));
  469. // mission 013 (hybriel#193): "Sign out everywhere" in place — its notice is back, the header drops the user menu, no reload;
  470. // 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)
  471. await b.goto(IDENT + '/');
  472. await b.waitForSelector('#menusignoutall');
  473. await connected(b, 'B before sign out everywhere');
  474. 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"'));
  475. await b.evaluate('window.__m = 1');
  476. await menuClick(b, '#menusignoutall');
  477. await b.waitFor('!!document.querySelector("#emailform")', { label: 'B signed out everywhere: the sign-in form' });
  478. check('sign out everywhere (user menu): the page reloads into the sign-in, the header has no user menu', await b.evaluate('!document.querySelector("application-header button.user-toggle") && !document.querySelector("#code") && location.pathname === "/"'), await b.evaluate('location.pathname'));
  479. // OTP RULES (kept from mission 003): 5 wrong codes, rate limit (Bob is signed out everywhere by now)
  480. await b.waitForSelector('#emailform');
  481. await askCode(b, '[email protected]');
  482. const carolCode = lastCode(SINK_MAIN, '[email protected]');
  483. const wrong = carolCode === '123456' ? '654321' : '123456';
  484. const seen = [];
  485. for (let i = 0; i < 5; i++) {
  486. await enterCode(b, wrong);
  487. await b.waitFor('/\\S/.test(document.querySelector("#message").textContent)', { label: 'wrong try ' + (i + 1) });
  488. seen.push(await msg(b));
  489. }
  490. 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));
  491. await enterCode(b, carolCode);
  492. await b.waitFor('/\\S/.test(document.querySelector("#message").textContent)', { label: 'right code after kill' });
  493. 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));
  494. await b.click('#back');
  495. await askCode(b, '[email protected]');
  496. const carolOld = lastCode(SINK_MAIN, '[email protected]');
  497. await b.click('#back');
  498. await askCode(b, '[email protected]');
  499. 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]')));
  500. await enterCode(b, carolOld === lastCode(SINK_MAIN, '[email protected]') ? '000001' : carolOld);
  501. await waitMsg(b, 'wrong code', 'old code refused');
  502. check('otp: a replaced (older) code no longer works', /^wrong code/.test(await msg(b)), await msg(b));
  503. await b.click('#back');
  504. await askCode(b, '[email protected]');
  505. 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));
  506. v = await face('verifyCode', ['[email protected]', lastCode(SINK_MAIN, '[email protected]'), 'UTC', { user: { id: 1 }, data: {} }]);
  507. 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));
  508. v = await face('verifyCode', ['[email protected]', 123456, 'UTC']);
  509. check('face: verifyCode with a numeric code → refused', v.error === 'email and code must be strings', J(v));
  510. // single use: the code that signed Bob in does not work twice (fresh session, REST)
  511. const bobFirst = mails(SINK_MAIN, '[email protected]')[0];
  512. // (Hybriel W124: sessions are lazy, a request with no cookie makes none until a face stores something, so the fresh session is simply no cookie)
  513. v = await face('verifyCode', ['[email protected]', bobFirst, 'UTC']);
  514. 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));
  515. // ---- ident#20 (mission 032): THE CODE PAGE /code SURVIVES A RELOAD --------------------------
  516. // "Send me a code" records the address in the session (face rememberPending) and goes to
  517. // /code; /code shows the code form while that code is waiting, else 302 back to the form.
  518. await b.goto(IDENT + '/');
  519. await connected(b, 'B before ident#20');
  520. const bCookie = await cookieOf(b, IDENT);
  521. check('ident#20: after "Other address" the browser is on the email form', (await step(b)) === '/ email', await step(b));
  522. check('ident#20: GET /code with nothing pending → 302 to /', (await ssr('/code', bCookie)) === '302 /', await ssr('/code', bCookie));
  523. check('ident#20: GET /code without any cookie → 302 to /', (await ssr('/code')) === '302 /', await ssr('/code'));
  524. await askCode(b, '[email protected]');
  525. check('ident#20: "Send me a code" → /code shows the code form for dave', (await step(b)) === '/code code:[email protected]', await step(b));
  526. 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));
  527. await reload(b);
  528. 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));
  529. await bothWidths(b, 'code-reloaded');
  530. const b2 = live(await B.newPage());
  531. await b2.goto(IDENT + '/code');
  532. await b2.waitForSelector('ident-card');
  533. 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));
  534. await b2.close();
  535. const daveCode = lastCode(SINK_MAIN, '[email protected]');
  536. await enterCode(b, daveCode === '000000' ? '111111' : '000000');
  537. await waitMsg(b, 'wrong code', 'dave wrong code');
  538. await reload(b);
  539. check('ident#20: a WRONG code keeps it (reload → code form)', (await step(b)) === '/code code:[email protected]', await step(b));
  540. 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]')));
  541. await enterCode(b, daveCode);
  542. await b.waitForSelector('#identityform');
  543. check('ident#20: the code entered after the reloads signs in (first login: welcome form), address bar back on /', (await b.text('#whoami')) === '[email protected]' && /optional/i.test(await b.text('#welcome')) && (await b.evaluate('location.pathname')) === '/', (await b.evaluate('location.pathname')) + ' ' + await b.text('ident-card'));
  544. await b.click('#skip');
  545. await b.waitFor('!document.querySelector("#identityform")', { label: 'dave skip' });
  546. await reload(b);
  547. check('ident#20: signed in → reload shows the account', (await step(b)) === '/ signedin' && (await b.text('#whoami')) === '[email protected]', await step(b));
  548. check('ident#20: signed in → GET /code is 302 to / (the sign-in cleared it)', (await ssr('/code', bCookie)) === '302 /', await ssr('/code', bCookie));
  549. await menuClick(b, '#menusignout');
  550. await b.waitForSelector('#emailform');
  551. await b.goto(IDENT + '/code');
  552. await b.waitForSelector('#emailform');
  553. check('ident#20: signed out again → /code in the browser lands on the email form at /', (await step(b)) === '/ email', await step(b));
  554. // "Other address" forgets it
  555. await connected(b, 'B before frank');
  556. await askCode(b, '[email protected]');
  557. check('ident#20: frank on /code', (await step(b)) === '/code code:[email protected]', await step(b));
  558. await b.click('#back');
  559. await b.waitFor('location.pathname === "/" && !!document.querySelector("#emailform")', { label: 'back to /' });
  560. check('ident#20: "Other address" → the email form at /', (await step(b)) === '/ email', await step(b));
  561. check('ident#20: "Other address" → the server forgot it (GET /code is 302 to /)', (await ssr('/code', bCookie)) === '302 /', await ssr('/code', bCookie));
  562. await reload(b);
  563. check('ident#20: "Other address" → RELOAD shows the email form', (await step(b)) === '/ email', await step(b));
  564. // a code killed by 5 wrong tries is no longer waiting → /code sends the browser back
  565. await askCode(b, '[email protected]');
  566. const ginaWrong = lastCode(SINK_MAIN, '[email protected]') === '123456' ? '654321' : '123456';
  567. for (let i = 0; i < 5; i++) {
  568. await enterCode(b, ginaWrong);
  569. await b.waitFor('/\\S/.test(document.querySelector("#message").textContent)', { label: 'gina wrong ' + (i + 1) });
  570. }
  571. 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));
  572. await reload(b);
  573. check('ident#20: a killed code → reload of /code lands on the email form at /', (await step(b)) === '/ email', await step(b));
  574. // THE FACE is honest: it records only an address a code is really waiting for
  575. v = await face('rememberPending', ['[email protected]'], bCookie);
  576. check('ident#20 face: rememberPending without a waiting code → refused', v.error === 'no code is waiting for this address', J(v));
  577. check('ident#20 face: … and /code still sends this browser back (302 /)', (await ssr('/code', bCookie)) === '302 /', await ssr('/code', bCookie));
  578. v = await face('rememberPending', [5], bCookie);
  579. check('ident#20 face: rememberPending with a number → refused', v.error === 'field email must be a string', J(v));
  580. const hq = await req('POST', IDENT + '/api/code', { raw: J({ email: '[email protected]' }), headers: { 'content-type': 'application/json' } });
  581. v = await face('rememberPending', ['[email protected]', { user: null, data: {} }], bCookie);
  582. 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));
  583. check('ident#20 face: … and nothing was recorded (302 /)', (await ssr('/code', bCookie)) === '302 /', await ssr('/code', bCookie));
  584. v = await face('rememberPending', [' [email protected] '], bCookie);
  585. check('ident#20 face: an address with a waiting code is accepted, normalised', v.email === '[email protected]', J(v));
  586. 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(' | '));
  587. v = await face('forgetPending', [], bCookie);
  588. check('ident#20 face: forgetPending → /code is 302 to / again', v === true && (await ssr('/code', bCookie)) === '302 /', J(v) + ' ' + await ssr('/code', bCookie));
  589. 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));
  590. 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));
  591. // ---- expiry (the short-clock server) ---------------------------------------------------------
  592. await a.goto(SHORT + '/');
  593. await askCode(a, '[email protected]');
  594. const erinCode = lastCode(SINK_SHORT, '[email protected]');
  595. await reload(a);
  596. check('ident#20: short server — reload right after asking → the code form', (await step(a)) === '/code code:[email protected]', await step(a));
  597. await sleep(3500);
  598. await enterCode(a, erinCode);
  599. await waitMsg(a, 'expired', 'expired otp');
  600. 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));
  601. await reload(a);
  602. check('ident#20: an EXPIRED code → reload of /code lands on the email form at /', (await step(a)) === '/ email', await step(a));
  603. await askCode(a, '[email protected]');
  604. check('ident#20: short server — ivy on /code', (await step(a)) === '/code code:[email protected]', await step(a));
  605. await sleep(3500);
  606. await reload(a);
  607. check('ident#20: expiry alone (no try) → reload of /code lands on the email form', (await step(a)) === '/ email', await step(a));
  608. // mission 010: the code request is a fetch to /api/code; its refusals (invalid address 400,
  609. // rate limit 429) make Chrome log "Failed to load resource … 400/429" — expected, shown on the page
  610. const expected = /favicon|status of (400|429) .*\/api\/code$/;
  611. const problems = [...a.problems(), ...b.problems()].filter(m => !expected.test(m.text));
  612. check('browsers: no console errors or warnings', problems.length === 0, J(problems.slice(0, 5)));
  613. // ---- mission 046: THE INSTALLABLE APP (manifest, icons, service worker) and the offline shell ------------
  614. const head = await (await fetch(IDENT + '/')).text();
  615. const link = (rel) => { const m = new RegExp(`<link rel="${rel}" href="([^"]+)"`).exec(head); return m ? m[1] : null; };
  616. const mhref = link('manifest');
  617. 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')]));
  618. const mres = await fetch(IDENT + (mhref || '/__hl/manifest.webmanifest'));
  619. const man = await mres.json();
  620. 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));
  621. 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; };
  622. const iconOks = [];
  623. for (const ic of man.icons) iconOks.push(ic.type === 'image/png' && await pngOk(ic.src, Number(ic.sizes.split('x')[0])));
  624. 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));
  625. const fav = await fetch(IDENT + '/favicon.ico'); const favB = Buffer.from(await fav.arrayBuffer());
  626. 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));
  627. r = await req('GET', IDENT + '/api/online');
  628. check('pwa: /api/online (the shell\'s network probe) answers 204, not cached', r.status === 204 && r.text === '', String(r.status));
  629. // THE OFFLINE COPY HOLDS NO PERSONAL DATA (ident is the identity provider; shared devices): browser A
  630. // is signed in; with the network gone neither `/` nor `/start`, nor anything in the worker's caches
  631. // or hl:web's IndexedDB, may contain the account's address or an identity name
  632. const w = live(await A.newPage());
  633. await viewport(w, 390, 844);
  634. await w.goto(IDENT + '/');
  635. await w.waitForSelector('#whoami');
  636. await connected(w, 'pwa page');
  637. const myEmail = (await w.text('#whoami')).trim();
  638. // the identity as it would leak: its details line (names) — a bare label like "Work" is also a word in the framework's code
  639. const myIdentity = await w.evaluate('(document.querySelector("#identities identity-details") || {}).textContent || ""');
  640. check('pwa: browser A is signed in (the data that must not be kept offline)', /@example\.org$/.test(myEmail) && myIdentity !== '', myEmail + ' ' + myIdentity);
  641. await w.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { label: 'service worker active', timeout: 15000 });
  642. 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)`));
  643. const inst = await w.send('Page.getInstallabilityErrors');
  644. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));
  645. await sleep(1500); // the probe's first ask (0.5 s after the page is up)
  646. check('pwa: online, the header says nothing about offline', await w.evaluate('!document.querySelector("#offline") && !!document.querySelector("application-header")'));
  647. // the installed app starts at /start: online it goes on to / by itself (the shell's probe)
  648. await w.goto(IDENT + '/start');
  649. await w.waitFor('location.pathname === "/" && !!document.querySelector("#whoami")', { label: '/start → /', timeout: 8000 }).catch(() => {});
  650. check('pwa: online, /start (the start_url) goes on to / (signed in)', await w.evaluate('location.pathname === "/" && !!document.querySelector("#whoami")'), await w.evaluate('location.pathname'));
  651. await connected(w, 'pwa / again');
  652. // everything this browser keeps offline, as text: every response in the worker's caches + hl:web's IndexedDB
  653. const keptText = () => w.evaluate(`(async () => {
  654. let out = '';
  655. 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(); } }
  656. const db = await new Promise((res) => { const q = indexedDB.open('hl-offline'); q.onsuccess = () => res(q.result); q.onerror = () => res(null); });
  657. 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(); }
  658. return out;
  659. })()`);
  660. // NO NETWORK: the tab AND the service worker (a separate CDP target — the tab's emulation alone
  661. // leaves the worker's fetches online, measured) are cut off
  662. const swSessions = {};
  663. const swOffline = async (on) => {
  664. const { targetInfos } = await A.conn.send('Target.getTargets');
  665. const sws = targetInfos.filter(t => t.type === 'service_worker' && t.url.startsWith(IDENT));
  666. for (const t of sws) {
  667. const sid = swSessions[t.targetId] ||= (await A.conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true })).sessionId;
  668. await A.conn.send('Network.enable', {}, sid);
  669. await A.conn.send('Network.emulateNetworkConditions', { offline: on, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, sid);
  670. }
  671. return sws.length;
  672. };
  673. const nSw = await swOffline(true);
  674. await w.setOffline(true);
  675. const cutOff = await w.evaluate(`Promise.resolve(window.__hlAttempt(() => fetch('/api/online', { cache: 'no-store' }))).then(r => !r.ok)`);
  676. check('pwa: offline set up (the worker and the tab cannot reach ident)', nSw === 1 && cutOff, `${nSw} ${cutOff}`);
  677. // a real reload of the signed-in `/`: it is not kept, so the worker answers its data-free "Unavailable offline"
  678. // the OLD document still answers for a moment after Page.reload returns (it has the header too, and then the new document is
  679. // briefly empty: documentElement null — measured with HL_CPU_THROTTLE=6): mark the old one, wait for an unmarked, loaded one
  680. await w.evaluate('window.__beforeReload = true');
  681. await w.send('Page.reload');
  682. await w.waitFor('!window.__beforeReload && document.readyState === "complete" && !!document.documentElement && (!!document.querySelector("main[data-hl-offline]") || !!document.querySelector("application-header"))', { label: 'offline reload of /', timeout: 15000 }).catch(() => {});
  683. let doc = await w.evaluate('document.documentElement.outerHTML');
  684. 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));
  685. // the installed app's start: the data-free shell from the cache, and it says it is offline
  686. await w.goto(IDENT + '/start').catch(() => {});
  687. await w.waitFor('!!document.querySelector("application-header") && !!document.querySelector("#start")', { label: 'offline /start', timeout: 15000 }).catch(() => {});
  688. await w.waitFor('!!document.querySelector("#offline")', { label: 'offline note', timeout: 8000 }).catch(() => {});
  689. 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)'));
  690. 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)'));
  691. doc = await w.evaluate('document.documentElement.outerHTML');
  692. check('pwa: … and it contains NO email or identity of the signed-in user', !doc.includes(myEmail) && !doc.includes(myIdentity) && !/@example\.org/.test(doc));
  693. const kept = await keptText();
  694. 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));
  695. await shot(w, 'phone-pwa-offline');
  696. check('layout: 390px offline shell has no horizontal overflow', await noOverflow(w));
  697. await w.goto(IDENT + '/apps').catch(() => {});
  698. await w.waitFor('!!document.querySelector("main[data-hl-offline]")', { label: 'offline /apps', timeout: 8000 }).catch(() => {});
  699. 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)'));
  700. // back online, the start page opens ident by itself
  701. await w.goto(IDENT + '/start').catch(() => {});
  702. await w.waitForSelector('#start');
  703. await swOffline(false);
  704. await w.setOffline(false);
  705. await w.waitFor('location.pathname === "/" && !!document.querySelector("#whoami")', { label: 'back online → /', timeout: 30000 }).catch(() => {});
  706. await connected(w, 'pwa back online').catch(() => {});
  707. await sleep(1000);
  708. 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("#whoami") && !document.querySelector("#offline")'), await w.evaluate('location.pathname + " " + document.body.innerText.slice(0, 120)'));
  709. await shot(w, 'phone-pwa-online');
  710. await w.close();
  711. } catch (e) {
  712. failures++;
  713. console.log('FAIL (aborted) ' + (e && e.stack || e));
  714. for (const [n, pg] of [['A', a], ['B', b]]) if (pg) console.log(`console ${n}: ` + J(pg.messages.slice(-8)));
  715. } finally {
  716. for (const br of [A, B]) { if (br) { try { await br.close(); } catch {} } }
  717. for (const { p } of procs) { try { p.kill('SIGTERM'); } catch {} }
  718. await sleep(500);
  719. for (const { p } of procs) { if (p.exitCode === null && p.signalCode === null) { try { p.kill('SIGKILL'); } catch {} } }
  720. await sleep(200);
  721. console.log(`\n${passes} passed, ${failures} failed`);
  722. process.exit(failures ? 1 : 0);
  723. }

Branches

Latest commits

  • 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
  • 675493b1ident#42: editing an identity upserts the one edited row (face editIdentity answers { identity, row }); a create or delete keeps the whole list because the rows' position-dependent parts (default, Delete, Identity n) changemre
  • 45e55303ident#42: an app write patches one row: upsert on create, edit and new secret, one-argument remove on delete; the faces answer the changed app (or the deleted id), not the whole listmre
  • 991641d4Merge branch 'f10-access' into mainIdent
  • e56d8273|||PR ident#34 part 4: access and inbox fixed classesmre
  • df7696dbident#34: tests: access ticks selector quoting fixmre
  • 7215903eident#34: access: the unstyled classes all, app, tick, apptick, plus are dropped; the gate finds the app ticks by input[name=app]mre
  • 69b0a0ceident#34: access: the pick buttons use Style.pickCard instead of class pickmre
  • dc702419Merge branch 'f9-choose' into mainIdent
  • 8caec771|||PR ident#34 restore .choose hookmre
  • 0dbff960Merge branch 'f8-shared' into mainIdent
  • d69665f6|||PR ident#34 part 3: shared look classes (wide, avatar, chip/used, conn, choose, who, inboxlink) moved to statics or droppedmre
  • 3a64dc48ident#34: chipLook: radius as the same var() string (a bare token name in a static does not compile); selector gate selectormre
  • eb039073ident#34: tests: signin and migration find the choice without the classmre
  • 4b94a594ident#34: tests: fix selector of the identity choicemre
  • bebc88e4ident#34: main.hl drops the unstyled classes inboxlink and whomre
  • b4e7ad04ident#34: the identity choice link/button has no class (rule on #chooselist a)mre