gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf07658c7f07658c7ident: home page shows the account once (account bar removed, the user menu carries email, Sign out, Sign out everywhere); wildcard origins https://*.domain for apps on many subdomains; gates follow (WIP: gates not re-run after the last edits)mref07658c7/tests/apps.mjs

36.1 KB

  1. // tests/apps.mjs — THE GATE OF PIECE 2 (ticket #25): apps, one id per app, the login
  2. // button, the exchange. Real headless Chrome (tests/cdp.mjs, --disable-gpu) drives:
  3. // register apps in ident → set up the test app → "Log in with ident" → ident login →
  4. // choose identity → back → exchange → the test app shows the id. Plus the negatives.
  5. //
  6. // Own servers only, NEVER the dev server and NEVER real mail:
  7. // ident :8370 (IDENT_MAIL_SINK), ident :8371 (grant TTL 1.5 s, for the expiry case),
  8. // test app A :8372, test app B :8373 (both against ident :8370).
  9. // Own storage: .scratch/apps-gate/ (wiped at start). Chrome debug ports 8670-8679.
  10. // Screenshots: .scratch/apps-*.png (390 and 1280 px) — look at them.
  11. //
  12. // Run: node tests/apps.mjs (exit 0 = all passed)
  13. import { spawn } from 'node:child_process';
  14. import { readFileSync, writeFileSync, rmSync, mkdirSync, existsSync } from 'node:fs';
  15. import { dirname, join } from 'node:path';
  16. import { fileURLToPath } from 'node:url';
  17. import { launchBrowser, sleep } from './cdp.mjs';
  18. // 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
  19. // page (the SSR HTML carries #hl-seed) therefore waits until the page is live (socket open) before the test touches it.
  20. function live(page) {
  21. const goto = page.goto.bind(page);
  22. page.goto = async (url, o) => {
  23. const r = await goto(url, o);
  24. await page.waitFor("!document.getElementById('hl-seed') || (!!window.__hl && !!window.__hl.socket && window.__hl.socket.readyState === 1)", { label: 'page hydrated ' + url });
  25. return r;
  26. };
  27. return page;
  28. }
  29. const APP = join(dirname(fileURLToPath(import.meta.url)), '..');
  30. const G = join(APP, '.scratch/apps-gate');
  31. const SHOTS = join(APP, '.scratch');
  32. const P0 = Number(process.env.APPS_GATE_PORT || 8370); // ident = P0, ident short = P0+1, test app A = P0+2, test app B = P0+3; Chrome APPS_GATE_CHROME (default 8670-8679)
  33. const ID = 'http://127.0.0.1:' + P0, IDS = 'http://127.0.0.1:' + (P0 + 1);
  34. const TA = 'http://127.0.0.1:' + (P0 + 2), TB = 'http://127.0.0.1:' + (P0 + 3);
  35. const CHROME_PORTS = (process.env.APPS_GATE_CHROME || '8670-8679').split('-').map(Number);
  36. let passed = 0, failed = 0;
  37. const check = (name, ok, detail = '') => {
  38. if (ok) { passed++; console.log(' ok ' + name); }
  39. else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); }
  40. };
  41. // ---- servers ----------------------------------------------------------------------------
  42. const procs = [];
  43. function start(cwd, env, log) {
  44. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], {
  45. cwd, env: { ...process.env, SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', ...env },
  46. stdio: ['ignore', 'pipe', 'pipe'],
  47. });
  48. let out = '';
  49. p.stdout.on('data', d => { out += d; }); p.stderr.on('data', d => { out += d; });
  50. p.on('exit', () => writeFileSync(join(G, log), out));
  51. procs.push({ p, log, out: () => out });
  52. return p;
  53. }
  54. async function up(url) {
  55. for (const end = Date.now() + Number(process.env.IDENT_COLD_MS || 120000); Date.now() < end;) { try { await fetch(url + "/", { redirect: "manual" }); return; } catch {} await sleep(250); }
  56. throw new Error('server did not come up: ' + url);
  57. }
  58. function stopAll() { for (const { p } of procs) { try { p.kill(); } catch {} } }
  59. rmSync(G, { recursive: true, force: true });
  60. mkdirSync(G, { recursive: true });
  61. const identEnv = (port, dir, extra = {}) => ({
  62. IDENT_PORT: String(port), IDENT_STORAGE: join(G, dir, 'ident'), IDENT_SESSIONS: join(G, dir, 'sess') + '/',
  63. IDENT_MAIL_SINK: join(G, dir, 'mail.txt'), IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000', ...extra,
  64. });
  65. mkdirSync(join(G, 'main'), { recursive: true }); mkdirSync(join(G, 'short'), { recursive: true });
  66. start(APP, identEnv(P0, 'main'), 'ident-main.log');
  67. start(APP, identEnv(P0 + 1, 'short', { IDENT_GRANT_TTL_MS: '1500' }), 'ident-short.log');
  68. const testapp = (port, file) => start(join(APP, 'testapp'), {
  69. TESTAPP_PORT: String(port), TESTAPP_URL: 'http://127.0.0.1:' + port, IDENT_URL: ID, TESTAPP_STORE: join(G, file),
  70. }, 'testapp-' + port + '.log');
  71. testapp(P0 + 2, 'testapp-a.json'); testapp(P0 + 3, 'testapp-b.json');
  72. await Promise.all([up(ID), up(IDS), up(TA), up(TB)]);
  73. // ---- helpers ----------------------------------------------------------------------------
  74. const lastCode = (dir, email) => {
  75. const lines = readFileSync(join(G, dir, 'mail.txt'), 'utf8').trim().split('\n').filter(l => l.startsWith(email + ' '));
  76. return lines.length ? lines[lines.length - 1].split(' ')[1] : null;
  77. };
  78. let emitI = 0;
  79. // hybriel#16 (mission 036): hl:web itself refuses an emit with one argument too many — the ack is
  80. // ok:false "… the `session` parameter is filled by the server, never by the peer"; the face never runs.
  81. 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; } };
  82. async function emit(base, event, payload, cookie) {
  83. const r = await fetch(base + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: JSON.stringify({ t: 'emit', i: ++emitI, event, payload }) });
  84. const t = await r.text();
  85. let j = null; try { j = JSON.parse(t); } catch {}
  86. return { status: r.status, cookie: (r.headers.get('set-cookie') || '').split(';')[0], value: j && j.value, raw: t };
  87. }
  88. async function exchange(base, body) {
  89. const r = await fetch(base + '/api/exchange', { method: 'POST', headers: { 'content-type': 'application/json' }, body: typeof body === 'string' ? body : JSON.stringify(body) });
  90. const t = await r.text();
  91. let j = null; try { j = JSON.parse(t); } catch {}
  92. return { status: r.status, j, t };
  93. }
  94. // log in over the emit API (for the non-browser parts): answers the cookie; the account's
  95. // identities (oldest first; ids are mpackdb UUIDs since mission 009) land in idsOf[cookie]
  96. const idsOf = {};
  97. // (mission 010: the code is requested with POST /api/code — no longer a face; the session
  98. // cookie comes from the verifyCode frame, which mints it)
  99. async function apiLogin(base, dir, email) {
  100. const q = await fetch(base + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email }) });
  101. if (q.status !== 200) throw new Error('code request failed: ' + q.status + ' ' + await q.text());
  102. const v = await emit(base, 'verifyCode', [email, lastCode(dir, email), 'UTC']);
  103. if (!v.value || !v.value.account || !v.cookie) throw new Error('api login failed: ' + v.raw);
  104. idsOf[v.cookie] = v.value.identities.map(i => i.id);
  105. return v.cookie;
  106. }
  107. // the ids a signed-in page renders in its buttons' value attributes (SSR), in order, once each
  108. async function ssrIds(base, path, cookie) {
  109. const t = await (await fetch(base + path, { headers: { cookie } })).text();
  110. return [...new Set([...t.matchAll(/value="([0-9a-z]{12})"/g)].map(m => m[1]))];
  111. }
  112. // a login button press + choice over HTTP: answers the one-time code
  113. async function codeFor(base, cookie, key, returnUrl, identity) {
  114. const l = await fetch(base + '/login?key=' + key + '&return=' + encodeURIComponent(returnUrl), { redirect: 'manual' });
  115. const rid = (l.headers.get('location') || '').split('/').pop();
  116. const c = await emit(base, 'chooseIdentity', [rid, identity], cookie);
  117. if (!c.value || !c.value.url) throw new Error('choose failed: ' + c.raw);
  118. return new URL(c.value.url).searchParams.get('ident_code');
  119. }
  120. const pages = [];
  121. async function ready(p) { await p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated' }); }
  122. // the account's Sign out lives in the header's user menu (the home page's own buttons were dropped 2026-10-24: the same account was shown twice): a real tap on the icon, then on the entry
  123. 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); };
  124. async function viewport(p, w) {
  125. await p.send('Emulation.setDeviceMetricsOverride', { width: w, height: w < 500 ? 844 : 900, deviceScaleFactor: 1, mobile: w < 500 });
  126. }
  127. async function shot(p, name) {
  128. for (const w of [390, 1280]) {
  129. await viewport(p, w);
  130. await sleep(150);
  131. const over = await p.evaluate('document.documentElement.scrollWidth > window.innerWidth');
  132. check(`${name} @${w}px: no horizontal overflow`, !over);
  133. const { data } = await p.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  134. writeFileSync(join(SHOTS, `apps-${name}-${w}.png`), Buffer.from(data, 'base64'));
  135. }
  136. await viewport(p, 1280);
  137. }
  138. // confirm() answers: the next dialog is accepted (true) or dismissed (false)
  139. function onDialogs(p) {
  140. p.dialogAnswers = [];
  141. p.dialogs = [];
  142. p.conn.onEvent((msg) => {
  143. if (msg.sessionId !== p.sessionId || msg.method !== 'Page.javascriptDialogOpening') return;
  144. p.dialogs.push(msg.params.message);
  145. const accept = p.dialogAnswers.length ? p.dialogAnswers.shift() : false;
  146. p.send('Page.handleJavaScriptDialog', { accept }).catch(() => {});
  147. });
  148. }
  149. const here = (p) => p.evaluate('location.href');
  150. const txt = (p, sel) => p.evaluate(`(document.querySelector(${JSON.stringify(sel)}) || {}).textContent || ''`);
  151. async function browserLogin(p, email) {
  152. await p.waitForSelector('#email');
  153. await ready(p);
  154. await p.type('#email', email);
  155. await p.click('#sendcode');
  156. // ident#20: a sent code navigates to the code page (/code, /signin/<rid>/code)
  157. await p.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'code page' });
  158. await ready(p);
  159. await p.type('#code', lastCode('main', email));
  160. await p.click('#verify');
  161. }
  162. // ident#20: a REAL reload (Page.reload), then hydrated
  163. async function reload(p) {
  164. p._loaded = false;
  165. await p.send('Page.reload', { ignoreCache: false });
  166. const deadline = Date.now() + 15000;
  167. while (!p._loaded && Date.now() < deadline) await sleep(25);
  168. if (!p._loaded) throw new Error('reload: load event never fired');
  169. await ready(p);
  170. }
  171. let browser1, browser2;
  172. try {
  173. browser1 = await launchBrowser({ debugPortRange: CHROME_PORTS });
  174. browser2 = await launchBrowser({ debugPortRange: CHROME_PORTS });
  175. const p = live(await browser1.newPage()); pages.push(p); onDialogs(p);
  176. await viewport(p, 1280);
  177. // ==== 1. sign in to ident, register two apps ==========================================
  178. console.log('# apps: register, list, secret shown once');
  179. const ALICE = '[email protected]';
  180. await p.goto(ID + '/apps');
  181. check('signed out /apps asks to sign in', /sign in/i.test(await txt(p, '#signinfirst')));
  182. await p.goto(ID + '/');
  183. await browserLogin(p, ALICE);
  184. await p.waitForSelector('#skip');
  185. await p.click('#skip');
  186. await p.waitFor('!document.querySelector("#identityform")');
  187. await p.goto(ID + '/apps');
  188. await p.waitForSelector('#newapp'); await ready(p);
  189. check('no apps yet', /No apps yet/.test(await txt(p, '#noapps')));
  190. const register = async (name, origins) => {
  191. await p.click('#newapp');
  192. await p.waitForSelector('#appform');
  193. await p.type('#fappname', name);
  194. await p.type('#forigins', origins);
  195. await p.click('#saveapp');
  196. await p.waitFor('!!document.querySelector("#secret") || /\\S/.test(document.querySelector("#message").textContent)');
  197. };
  198. // a bad origin first: refused, named
  199. await register('Bad', TA + '/callback');
  200. check('origin with a path refused', /no path/.test(await txt(p, '#message')), await txt(p, '#message'));
  201. await p.click('#cancelapp');
  202. await register('Test app A', TA);
  203. const secretA = (await txt(p, '#secret')).trim();
  204. check('secret shown after register (sk_ + 48 hex)', /^sk_[0-9a-f]{48}$/.test(secretA), secretA);
  205. const keyA = (await txt(p, '#apps li:nth-child(1) .apikey')).trim();
  206. check('API key listed (pk_ + 32 hex)', /^pk_[0-9a-f]{32}$/.test(keyA), keyA);
  207. // hybriel#121 (mission 048): a face taking the session syncs the session-derived list back — a row added on top would show twice
  208. check('first app listed ONCE (no session-sync double row)', (await p.evaluate('document.querySelectorAll("#apps li").length')) === 1, await txt(p, '#apps'));
  209. await shot(p, 'secret');
  210. await p.click('#secretdone');
  211. await p.waitFor('!document.querySelector("#secretbox")');
  212. await p.goto(ID + '/apps'); await ready(p);
  213. check('secret not shown again after reload', !(await p.evaluate('document.body.textContent.includes(' + JSON.stringify(secretA) + ')')));
  214. await register('Test app B', TB + ', ' + TB.replace('127.0.0.1', 'localhost'));
  215. const secretB = (await txt(p, '#secret')).trim();
  216. const keyB = (await txt(p, '#apps li:nth-child(2) .apikey')).trim();
  217. check('second app: own key and secret', keyB !== keyA && secretB !== secretA && /^pk_/.test(keyB));
  218. check('second app: two rows, each app ONCE', (await p.evaluate('[...document.querySelectorAll("#apps li .apikey")].map(e => e.textContent.trim()).join(" ")')) === keyA + ' ' + keyB, await txt(p, '#apps'));
  219. check('origins listed', (await txt(p, '#apps li:nth-child(2)')).includes(TB + ' ' + TB.replace('127.0.0.1', 'localhost')));
  220. await p.click('#secretdone');
  221. await shot(p, 'list');
  222. // edit: rename B and keep one origin
  223. await p.click('#apps li:nth-child(2) .edit');
  224. await p.waitForSelector('#appform');
  225. check('edit form filled', (await p.evaluate('document.querySelector("#forigins").value')) === TB + ' ' + TB.replace('127.0.0.1', 'localhost'));
  226. await p.type('#fappname', 'Test app B2', { clear: true });
  227. await p.type('#forigins', TB, { clear: true });
  228. await p.click('#saveapp');
  229. await p.waitFor('/App saved/.test(document.querySelector("#notice").textContent)');
  230. const bRow = await txt(p, '#apps li:nth-child(2)');
  231. check('edit saved (name, origins, key unchanged)', bRow.includes('Test app B2') && !bRow.includes('localhost') && bRow.includes(keyB), bRow);
  232. // ==== 2. the test apps are set up with key + secret ===================================
  233. console.log('# test app setup');
  234. const setupApp = async (base, key, secret) => {
  235. await p.goto(base + '/');
  236. await p.type('#key', key, { clear: true });
  237. await p.type('#secret', secret, { clear: true });
  238. await p.evaluate('window.__old = 1');
  239. await p.click('#savesetup');
  240. await p.waitFor('!window.__old && document.readyState === "complete" && (!!document.querySelector("#login") || !!document.querySelector("#result"))', { label: 'setup saved' });
  241. check('test app ' + base + ' saved key + secret', (await txt(p, '#setupkey')) === key, await txt(p, 'body'));
  242. };
  243. await setupApp(TA, keyA, secretA);
  244. check('test app A set up', (await txt(p, '#setupkey')) === keyA);
  245. await setupApp(TB, keyB, secretB);
  246. // ==== 3. the login button, signed in already, one identity ============================
  247. console.log('# login button: signed in, one identity');
  248. const pressLogin = async (base) => {
  249. await p.goto(base + '/');
  250. await p.click('#login');
  251. await p.waitFor('location.pathname.startsWith("/signin/") && !!document.querySelector("#apprequest")', { label: 'ident sign-in page' });
  252. await ready(p);
  253. };
  254. const chooseAndReturn = async (nth, base) => {
  255. await p.waitForSelector('#chooselist');
  256. await p.click(`#chooselist li:nth-child(${nth}) .choose`);
  257. await p.waitFor(`location.href.startsWith(${JSON.stringify(base + '/callback')}) && !!document.querySelector("#result")`, { label: 'back at the app' });
  258. return { identity: (await txt(p, '#identity')).trim(), state: await txt(p, '#userstate'), answer: await txt(p, '#answer'), result: await txt(p, '#result') };
  259. };
  260. await pressLogin(TA);
  261. check('ident names the app and its origin', (await txt(p, '#appname')) === 'Test app A' && (await txt(p, '#apporigin')) === TA);
  262. check('one identity: still shown, one choice', (await p.evaluate('document.querySelectorAll("#chooselist li").length')) === 1 && (await txt(p, '#chooselist li')).includes('Default'));
  263. check('identities management not shown on the app page', !(await p.evaluate('!!document.querySelector("#identitiessection")')));
  264. await shot(p, 'choose-one');
  265. const a1 = await chooseAndReturn(1, TA);
  266. check('back at test app A with an identity id', /^[2-9a-hj-km-np-z]{5}$/.test(a1.identity), JSON.stringify(a1));
  267. check('the app got ONLY the id (no email, no names)', a1.answer === JSON.stringify({ identity: a1.identity }), a1.answer);
  268. check('test app: new user', a1.state === 'new user');
  269. await shot(p, 'testapp-result');
  270. await pressLogin(TA);
  271. const a2 = await chooseAndReturn(1, TA);
  272. check('same identity, same app → same id', a2.identity === a1.identity && a2.state === 'welcome back', JSON.stringify(a2));
  273. await pressLogin(TB);
  274. const b1 = await chooseAndReturn(1, TB);
  275. check('same identity, second app → the SAME id (ident#23)', b1.identity === a1.identity, JSON.stringify([a1.identity, b1.identity]));
  276. // ==== 4. two identities: the choice matters ============================================
  277. console.log('# two identities');
  278. await p.goto(ID + '/'); await ready(p);
  279. await p.click('#newidentity');
  280. await p.waitForSelector('#identityform');
  281. await p.type('#fidentityname', 'Work');
  282. await p.click('#saveidentity');
  283. await p.waitFor('document.querySelectorAll("#identities li").length === 2');
  284. await pressLogin(TA);
  285. check('two identities offered', (await p.evaluate('document.querySelectorAll("#chooselist li").length')) === 2);
  286. await shot(p, 'choose-two');
  287. const aWork = await chooseAndReturn(2, TA);
  288. check('other identity, same app → other id', /^[2-9a-hj-km-np-z]{5}$/.test(aWork.identity) && aWork.identity !== a1.identity && aWork.state === 'new user', JSON.stringify(aWork));
  289. await pressLogin(TA);
  290. const aDef = await chooseAndReturn(1, TA);
  291. check('first identity again → its old id', aDef.identity === a1.identity);
  292. // ==== 4b. ident#26: "Used in" on each identity's page ==================================
  293. console.log('# used in (ident#26)');
  294. await p.goto(ID + '/'); await ready(p);
  295. await p.click('#newidentity');
  296. await p.waitForSelector('#identityform');
  297. await p.type('#fidentityname', 'Idle');
  298. await p.click('#saveidentity');
  299. await p.waitFor('document.querySelectorAll("#identities li").length === 3');
  300. const usedRows = () => p.evaluate('[...document.querySelectorAll("#usedin li")].map(li => li.querySelector("used-app").textContent + " | " + li.querySelector("used-line").textContent + " | " + li.querySelector("a.notif").getAttribute("href"))');
  301. const openUsed = async (nth) => {
  302. await p.goto(ID + '/'); await ready(p);
  303. await p.click(`#identities li:nth-child(${nth}) a.used`); // ONE tap from the identities list
  304. await p.waitFor('location.pathname.startsWith("/identity/") && !!document.querySelector("#idlabel")', { label: 'identity page' });
  305. };
  306. await openUsed(1);
  307. check('26: the identity page names the identity and its short id', (await txt(p, '#idlabel')) === 'Default' && (await txt(p, '#idshort')).trim() === a1.identity, await txt(p, 'ident-card'));
  308. const rowsDef = await usedRows();
  309. check('26: Default is used in two apps, newest first (B2, then A)', rowsDef.length === 2 && rowsDef[0].startsWith('Test app B2 | ') && rowsDef[1].startsWith('Test app A | '), JSON.stringify(rowsDef));
  310. check('26: each row: since <Mon d> · last use just now (a login moments ago)', rowsDef.every(r => /\| since [A-Z][a-z]{2} \d{1,2} · last use (just now|\d+ min ago) \|/.test(r)), JSON.stringify(rowsDef));
  311. check('26: the Notif. chip leads to the per-app page', rowsDef.every(r => /\| \/inbox\/[0-9a-z]{12}$/.test(r)), JSON.stringify(rowsDef));
  312. await shot(p, 'used-in');
  313. await p.click('#usedin li:nth-child(1) a.notif');
  314. await p.waitFor('location.pathname.startsWith("/inbox/") && !!document.querySelector("#connapp")');
  315. check('26: the chip opens that app\'s page for this identity', (await txt(p, '#connapp')) === 'Test app B2' && (await txt(p, '#connidentity')) === 'Default');
  316. await openUsed(2);
  317. const rowsWork = await usedRows();
  318. check('26: Work is used in Test app A only', (await txt(p, '#idlabel')) === 'Work' && rowsWork.length === 1 && rowsWork[0].startsWith('Test app A | '), JSON.stringify(rowsWork));
  319. await openUsed(3);
  320. check('26: an identity never used shows the empty state', (await txt(p, '#idlabel')) === 'Idle' && /Not used in any app yet/.test(await txt(p, '#usedinnone')) && (await p.evaluate('document.querySelectorAll("#usedin li").length')) === 0, await txt(p, 'ident-card'));
  321. await shot(p, 'used-in-empty');
  322. await p.goto(ID + '/identity/00000000-0000-0000-0000-000000000000'); await ready(p);
  323. check('26: somebody else\'s / unknown identity id: not found', /does not exist or is not yours/.test(await txt(p, '#notfound')));
  324. // ==== 5. signed out: ident login first, then the choice ===============================
  325. console.log('# login button: signed out');
  326. const q = live(await browser2.newPage()); pages.push(q); onDialogs(q);
  327. await viewport(q, 1280);
  328. await q.goto(TB + '/');
  329. await q.click('#login');
  330. await q.waitFor('location.pathname.startsWith("/signin/") && !!document.querySelector("#email")', { label: 'ident login for the app' });
  331. check('signed out: login form under the app banner', (await txt(q, '#apprequest')).includes('Test app B2'));
  332. await shot(q, 'signin-for-app');
  333. const BOB = '[email protected]';
  334. // ident#20 (mission 032): the app login's code step is the page /signin/<rid>/code and
  335. // survives a reload; the code entered after it signs in and the app flow completes
  336. await ready(q);
  337. const ridPath = await q.evaluate('location.pathname');
  338. await q.type('#email', BOB);
  339. await q.click('#sendcode');
  340. await q.waitFor(`location.pathname === ${JSON.stringify(ridPath + '/code')} && !!document.querySelector("#code")`, { label: 'app code page' });
  341. await ready(q);
  342. check('ident#20: app login: "Send me a code" → /signin/<rid>/code with the code form', /^\/signin\/[0-9a-f]{32}\/code$/.test(await q.evaluate('location.pathname')) && (await txt(q, '#sentto strong')) === BOB, await q.evaluate('location.pathname'));
  343. await reload(q);
  344. check('ident#20: app login: RELOAD of /signin/<rid>/code → code form for bob, still under the app banner', (await q.evaluate('location.pathname')) === ridPath + '/code' && (await txt(q, '#sentto strong')) === BOB && !!(await q.evaluate('!!document.querySelector("#code") && !document.querySelector("#email")')) && (await txt(q, '#apprequest')).includes('Test app B2'), await txt(q, 'ident-card'));
  345. await shot(q, 'code-for-app-reloaded');
  346. await q.type('#code', lastCode('main', BOB));
  347. await q.click('#verify');
  348. // a first login: the optional names come first, then the choice
  349. await q.waitForSelector('#welcome');
  350. check('ident#20: app login: signed in after the reload, address bar back on /signin/<rid>', (await q.evaluate('location.pathname')) === ridPath, await q.evaluate('location.pathname'));
  351. check('first login via an app: optional names first', /optional/.test(await txt(q, '#welcome')) && !(await q.evaluate('!!document.querySelector("#chooselist")')));
  352. await q.click('#skip');
  353. await q.waitForSelector('#chooselist');
  354. await q.click('#chooselist li:nth-child(1) .choose');
  355. await q.waitFor(`location.href.startsWith(${JSON.stringify(TB + '/callback')}) && !!document.querySelector("#identity")`);
  356. const bob = (await txt(q, '#identity')).trim();
  357. check('another account → another id', /^[2-9a-hj-km-np-z]{5}$/.test(bob) && bob !== b1.identity && bob !== a1.identity);
  358. // an existing account signs in via the app: no names form, straight to the choice
  359. await q.goto(ID + '/'); await ready(q);
  360. await menuClick(q, '#menusignout');
  361. await q.waitForSelector('#email');
  362. await q.goto(TB + '/');
  363. await q.click('#login');
  364. await q.waitFor('!!document.querySelector("#email")');
  365. // ident#20: "Other address" on the app's code page → back to /signin/<rid>, the email form
  366. await ready(q);
  367. const ridPath2 = await q.evaluate('location.pathname');
  368. await q.type('#email', '[email protected]');
  369. await q.click('#sendcode');
  370. await q.waitFor(`location.pathname === ${JSON.stringify(ridPath2 + '/code')} && !!document.querySelector("#back")`, { label: 'app code page 2' });
  371. await ready(q);
  372. await q.click('#back');
  373. await q.waitFor(`location.pathname === ${JSON.stringify(ridPath2)} && !!document.querySelector("#email")`, { label: 'back to the app sign-in' });
  374. check('ident#20: app login: "Other address" → /signin/<rid> email form under the app banner', (await txt(q, '#apprequest')).includes('Test app B2') && !(await q.evaluate('!!document.querySelector("#code")')));
  375. await reload(q);
  376. check('ident#20: app login: … and a reload stays on the email form', (await q.evaluate('location.pathname')) === ridPath2 && (await q.evaluate('!!document.querySelector("#email") && !document.querySelector("#code")')));
  377. await q.goto(ID + ridPath2 + '/code');
  378. await q.waitForSelector('#email');
  379. check('ident#20: app login: /signin/<rid>/code with nothing pending → back to /signin/<rid>', (await q.evaluate('location.pathname')) === ridPath2);
  380. await browserLogin(q, BOB);
  381. await q.waitForSelector('#chooselist');
  382. check('known account: straight to the choice (no names form)', !(await q.evaluate('!!document.querySelector("#welcome")')));
  383. await q.click('#chooselist li:nth-child(1) .choose');
  384. await q.waitFor(`!!document.querySelector("#identity")`);
  385. check('after an OTP login: same id as before', (await txt(q, '#identity')).trim() === bob);
  386. // ==== 6. the login button refuses: error page, never a redirect =======================
  387. console.log('# login button negatives');
  388. const badLogin = async (qs, re, label) => {
  389. const before = p.messages.length;
  390. await p.goto(ID + '/login' + qs);
  391. const url = await here(p);
  392. const msg = await txt(p, '#errormessage');
  393. check(label + ' → error page, no redirect', url.startsWith(ID + '/login') && re.test(msg), url + ' | ' + msg);
  394. p.messages.splice(before); // the page's own 400 is expected in the console
  395. };
  396. await badLogin('?key=' + keyA + '&return=' + encodeURIComponent('http://evil.example.org/callback'), /not one of the origins/, 'foreign origin');
  397. await badLogin('?key=' + keyA + '&return=' + encodeURIComponent(TB + '/callback'), /not one of the origins/, "the other app's origin");
  398. await badLogin('?key=' + keyA + '&return=' + encodeURIComponent(TA + '@evil.example.org/'), /not one of the origins/, 'user@host trick');
  399. await badLogin('?key=' + keyA + '&return=' + encodeURIComponent('javascript:alert(1)'), /http/, 'javascript: URL');
  400. await badLogin('?key=' + keyA, /missing/, 'no return URL');
  401. await badLogin('?key=pk_00000000000000000000000000000000&return=' + encodeURIComponent(TA + '/callback'), /no app has this API key/, 'unknown key');
  402. await badLogin('?return=' + encodeURIComponent(TA + '/callback'), /missing/, 'no key');
  403. const res = await fetch(ID + '/login?key=' + keyA + '&return=' + encodeURIComponent('http://evil.example.org/'), { redirect: 'manual' });
  404. check('foreign origin: HTTP 400, no Location', res.status === 400 && !res.headers.get('location'), res.status + ' ' + res.headers.get('location'));
  405. await shot(p, 'error');
  406. await p.goto(ID + '/signin/0123456789abcdef0123456789abcdef');
  407. check('unknown request id → "expired" page', /unknown or expired/.test(await txt(p, '#badrequest')));
  408. // ==== 7. the exchange ==================================================================
  409. console.log('# exchange');
  410. const aliceCookie = await apiLogin(ID, 'main', ALICE);
  411. const aliceId = idsOf[aliceCookie][0]; // her default (oldest) identity
  412. check('ids: identity ids are 12-char mpackdb UUIDs', idsOf[aliceCookie].length >= 1 && idsOf[aliceCookie].every(i => /^[0-9a-z]{12}$/.test(i)), JSON.stringify(idsOf[aliceCookie]));
  413. let code = await codeFor(ID, aliceCookie, keyA, TA + '/callback', aliceId);
  414. let r = await exchange(ID, { key: keyA, secret: secretB, code });
  415. check('wrong secret → 401', r.status === 401, r.t);
  416. r = await exchange(ID, { key: 'pk_x', secret: secretA, code });
  417. check('unknown key → 401', r.status === 401, r.t);
  418. r = await exchange(ID, { key: keyA, secret: secretA, code });
  419. check('right key + secret → 200 { identity } only', r.status === 200 && JSON.stringify(Object.keys(r.j)) === '["identity"]' && r.j.identity === a1.identity, r.t);
  420. r = await exchange(ID, { key: keyA, secret: secretA, code });
  421. check('reused code → 400', r.status === 400 && /already used/.test(r.j.error), r.t);
  422. code = await codeFor(ID, aliceCookie, keyA, TA + '/callback', aliceId);
  423. r = await exchange(ID, { key: keyB, secret: secretB, code });
  424. check("other app's code → 400", r.status === 400 && /not issued to this app/.test(r.j.error), r.t);
  425. r = await exchange(ID, { key: keyA, secret: secretA, code });
  426. check('a code shown to the wrong app is spent → 400', r.status === 400, r.t);
  427. r = await exchange(ID, { key: keyA, secret: secretA, code: 'nope' });
  428. check('unknown code → 400', r.status === 400, r.t);
  429. r = await exchange(ID, '{"key": "x",');
  430. check('invalid JSON → 400', r.status === 400 && /not valid JSON/.test(r.j.error), r.t);
  431. r = await exchange(ID, '[1]');
  432. check('not an object → 400', r.status === 400 && /object/.test(r.j.error), r.t);
  433. r = await exchange(ID, { key: keyA, secret: secretA });
  434. check('missing field → 400 naming it', r.status === 400 && r.j.error === 'missing field: code', r.t);
  435. r = await exchange(ID, { key: keyA, secret: secretA, code: 'x', email: 'x' });
  436. check('unknown field → 400 naming it', r.status === 400 && r.j.error === 'unknown field: email', r.t);
  437. r = await exchange(ID, { key: keyA, secret: secretA, code: 5 });
  438. check('wrong type → 400 naming it', r.status === 400 && /field code must be a string/.test(r.j.error), r.t);
  439. r = await exchange(ID, '{"key":"\\ud83d\\ude00","secret":"a","code":"b"}');
  440. check('surrogate escape → 400 (not 500)', r.status === 400, r.t);
  441. const g = await fetch(ID + '/api/exchange');
  442. check('GET /api/exchange → 405', g.status === 405);
  443. // expiry, on the short-clock server (grant TTL 1.5 s)
  444. const sc = await apiLogin(IDS, 'short', '[email protected]');
  445. const sApp = (await emit(IDS, 'appCreate', [{ name: 'S', origins: [TA] }], sc)).value;
  446. const sCode = await codeFor(IDS, sc, sApp.app.apiKey, TA + '/callback', idsOf[sc][0]);
  447. await sleep(2000);
  448. r = await exchange(IDS, { key: sApp.app.apiKey, secret: sApp.secret, code: sCode });
  449. check('expired code → 400', r.status === 400 && /expired/.test(r.j.error), r.t);
  450. const sCode2 = await codeFor(IDS, sc, sApp.app.apiKey, TA + '/callback', idsOf[sc][0]);
  451. r = await exchange(IDS, { key: sApp.app.apiKey, secret: sApp.secret, code: sCode2 });
  452. check('fresh code on the short server → 200', r.status === 200, r.t);
  453. // ==== 8. faces: forged sessions (#31), strict fields, other accounts ==================
  454. console.log('# faces');
  455. const forged = { user: { id: 1 } };
  456. for (const [ev, args] of [['appCreate', [{ name: 'X', origins: [TA] }]], ['appUpdate', [1, { name: 'X', origins: [TA] }]], ['appNewSecret', [1]], ['appDelete', [1]], ['chooseIdentity', ['x', 1]]]) {
  457. const f = await emit(ID, ev, [...args, forged]);
  458. check(`forged session argument refused: ${ev}`, framework_refused(f.raw) || (f.value && /not signed in/.test(f.value.error)), f.raw);
  459. }
  460. let e = await emit(ID, 'appCreate', [{ name: 'X', origins: [TA], secret: 'mine' }], aliceCookie);
  461. check('appCreate unknown field → named', e.value.error === 'unknown field: secret' && e.value.field === 'secret', e.raw);
  462. e = await emit(ID, 'appCreate', [{ name: 'X' }], aliceCookie);
  463. check('appCreate missing origins → named', e.value.field === 'origins', e.raw);
  464. e = await emit(ID, 'appCreate', [{ name: '', origins: [TA] }], aliceCookie);
  465. check('appCreate empty name refused', e.value.field === 'name', e.raw);
  466. e = await emit(ID, 'appCreate', [{ name: 'X', origins: 'http://a.b' }], aliceCookie);
  467. check('appCreate origins not a list refused', e.value.field === 'origins', e.raw);
  468. e = await emit(ID, 'appCreate', [{ name: 'X', origins: Array.from({ length: 11 }, (_, i) => 'http://h' + i + '.example') }], aliceCookie);
  469. check('appCreate 11 origins refused', /at most 10/.test(e.value.error), e.raw);
  470. e = await emit(ID, 'appCreate', [{ name: 'X', origins: ['ftp://a.b'] }], aliceCookie);
  471. check('appCreate ftp origin refused', e.value.field === 'origins', e.raw);
  472. const bobCookie = await apiLogin(ID, 'main', BOB);
  473. const aliceApp = (await ssrIds(ID, '/apps', aliceCookie))[0];
  474. check('ids: app ids are 12-char mpackdb UUIDs (read off /apps)', /^[0-9a-z]{12}$/.test(aliceApp || ''), JSON.stringify(aliceApp));
  475. e = await emit(ID, 'appUpdate', [aliceApp, { name: 'hijack', origins: ['http://evil.example'] }], bobCookie);
  476. check("another account cannot edit alice's app", e.value.error === 'no such app', e.raw);
  477. e = await emit(ID, 'appNewSecret', [aliceApp], bobCookie);
  478. check("another account cannot renew alice's secret", e.value.error === 'no such app', e.raw);
  479. e = await emit(ID, 'appDelete', [aliceApp], bobCookie);
  480. check("another account cannot delete alice's app", e.value.error === 'no such app', e.raw);
  481. const l = await fetch(ID + '/login?key=' + keyA + '&return=' + encodeURIComponent(TA + '/callback'), { redirect: 'manual' });
  482. const rid = l.headers.get('location').split('/').pop();
  483. e = await emit(ID, 'chooseIdentity', [rid, aliceId], bobCookie);
  484. check("choosing another account's identity refused", e.value.error === 'no such identity', e.raw);
  485. e = await emit(ID, 'chooseIdentity', [rid, 1], aliceCookie);
  486. check('chooseIdentity wrong type (a number, the old ids) refused', /must be a string/.test(e.value.error), e.raw);
  487. e = await emit(ID, 'appUpdate', [1, { name: 'X', origins: [TA] }], aliceCookie);
  488. check('appUpdate with an old numeric id: no such app', e.value.error === 'no such app', e.raw);
  489. // ==== 9. new secret, delete (browser) ==================================================
  490. console.log('# new secret, delete');
  491. await p.goto(ID + '/apps'); await ready(p);
  492. p.dialogAnswers.push(false);
  493. await p.click('#apps li:nth-child(1) .newsecret');
  494. await sleep(300);
  495. check('new secret: dismissed confirm changes nothing', !(await p.evaluate('!!document.querySelector("#secretbox")')) && p.dialogs.length === 1);
  496. p.dialogAnswers.push(true);
  497. await p.click('#apps li:nth-child(1) .newsecret');
  498. await p.waitForSelector('#secret');
  499. const secretA2 = (await txt(p, '#secret')).trim();
  500. check('new secret shown once, differs', /^sk_[0-9a-f]{48}$/.test(secretA2) && secretA2 !== secretA);
  501. await p.click('#secretdone');
  502. code = await codeFor(ID, aliceCookie, keyA, TA + '/callback', aliceId);
  503. r = await exchange(ID, { key: keyA, secret: secretA, code });
  504. check('old secret → 401 after renewal', r.status === 401, r.t);
  505. r = await exchange(ID, { key: keyA, secret: secretA2, code });
  506. check('new secret works, same id', r.status === 200 && r.j.identity === a1.identity, r.t);
  507. // the test app still has the old secret: its exchange fails visibly
  508. await pressLogin(TA);
  509. await p.click('#chooselist li:nth-child(1) .choose');
  510. const beforeOld = p.messages.length;
  511. await p.waitFor('!!document.querySelector("#result")');
  512. await sleep(300);
  513. p.messages.splice(beforeOld); // the test app's own 400 page is expected
  514. check('test app with the old secret: exchange refused (401)', (await txt(p, '#status')) === '401', await txt(p, '#result'));
  515. await setupApp(TA, keyA, secretA2);
  516. await pressLogin(TA);
  517. const a3 = await chooseAndReturn(1, TA);
  518. check('test app with the new secret: logged in, same id', a3.identity === a1.identity, JSON.stringify(a3));
  519. // delete app B
  520. await p.goto(ID + '/apps'); await ready(p);
  521. p.dialogAnswers.push(true);
  522. await p.click('#apps li:nth-child(2) .delete');
  523. await p.waitFor('document.querySelectorAll("#apps li").length === 1');
  524. check('app deleted from the list', !(await txt(p, '#apps')).includes('Test app B2'));
  525. await badLogin('?key=' + keyB + '&return=' + encodeURIComponent(TB + '/callback'), /no app has this API key/, 'deleted app key');
  526. // ==== 10. console ======================================================================
  527. const probs = pages.flatMap(x => x.problems().map(m => m.text));
  528. check('no console errors or warnings', probs.length === 0, probs.join(' | '));
  529. } catch (err) {
  530. failed++;
  531. console.log(' FAIL (aborted) ' + (err && err.stack || err));
  532. for (const x of pages) console.log('--- console:\n' + x.dumpConsole());
  533. } finally {
  534. for (const b of [browser1, browser2]) { if (b) { try { await b.close(); } catch {} } }
  535. stopAll();
  536. await sleep(300);
  537. }
  538. console.log(`\n${passed} passed, ${failed} failed`);
  539. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • f07658c7ident: home page shows the account once (account bar removed, the user menu carries email, Sign out, Sign out everywhere); wildcard origins https://*.domain for apps on many subdomains; gates follow (WIP: gates not re-run after the last edits)mre
  • f2c43bbbtheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 6d4f996esessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • 029eb5e5deploy: security gate (tests/security.mjs)mre
  • d3c065a8security audit (SI): uploadMax 0, Secure __Host- cookie behind https, headers on function routes/files, page CSP+referrer meta, app/identity caps, tests/security.mjs, reportmre
  • 5561a0cbreport I4-mobilemre
  • 4ca2ed20404 page in the shell (viewport, status 404, way home); phone: account actions live in the user menu so the open menu covers nothing; mobile gate; signoutall waits for a cold startmre
  • 9baad745tests: browser gate waits for the reloaded document (offline reload race under CPU throttle); HL_CPU_THROTTLE knobmre
  • 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