gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit061abfe2061abfe2ident: the apps gate waits until the test app's login button stops moving before it clicks (the page grows after load and the click missed about every second run)mre061abfe2/tests/apps.mjs

37.0 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. // The test app's page grows after it loads (the ident selector upgrades and the login state line settles), which
  124. // moves the login button down by ~45 px. A click at the old spot then misses (the apps gate failed about every
  125. // second run at "!!document.querySelector('#email')"), so wait until the button has stopped moving, then click it.
  126. const clickSettled = async (page, sel) => {
  127. const top = async () => page.evaluate(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); return el ? Math.round(el.getBoundingClientRect().top) : null; })()`);
  128. let last = null, still = 0;
  129. for (let i = 0; i < 100 && still < 6; i++) {
  130. await new Promise(r => setTimeout(r, 100));
  131. const n = await top();
  132. still = n !== null && n === last ? still + 1 : 0; last = n;
  133. }
  134. if (still < 6) throw new Error('the button ' + sel + ' never stopped moving');
  135. await page.click(sel);
  136. };
  137. 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); };
  138. async function viewport(p, w) {
  139. await p.send('Emulation.setDeviceMetricsOverride', { width: w, height: w < 500 ? 844 : 900, deviceScaleFactor: 1, mobile: w < 500 });
  140. }
  141. async function shot(p, name) {
  142. for (const w of [390, 1280]) {
  143. await viewport(p, w);
  144. await sleep(150);
  145. const over = await p.evaluate('document.documentElement.scrollWidth > window.innerWidth');
  146. check(`${name} @${w}px: no horizontal overflow`, !over);
  147. const { data } = await p.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  148. writeFileSync(join(SHOTS, `apps-${name}-${w}.png`), Buffer.from(data, 'base64'));
  149. }
  150. await viewport(p, 1280);
  151. }
  152. // confirm() answers: the next dialog is accepted (true) or dismissed (false)
  153. function onDialogs(p) {
  154. p.dialogAnswers = [];
  155. p.dialogs = [];
  156. p.conn.onEvent((msg) => {
  157. if (msg.sessionId !== p.sessionId || msg.method !== 'Page.javascriptDialogOpening') return;
  158. p.dialogs.push(msg.params.message);
  159. const accept = p.dialogAnswers.length ? p.dialogAnswers.shift() : false;
  160. p.send('Page.handleJavaScriptDialog', { accept }).catch(() => {});
  161. });
  162. }
  163. const here = (p) => p.evaluate('location.href');
  164. const txt = (p, sel) => p.evaluate(`(document.querySelector(${JSON.stringify(sel)}) || {}).textContent || ''`);
  165. async function browserLogin(p, email) {
  166. await p.waitForSelector('#email');
  167. await ready(p);
  168. await p.type('#email', email);
  169. await p.click('#sendcode');
  170. // ident#20: a sent code navigates to the code page (/code, /signin/<rid>/code)
  171. await p.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'code page' });
  172. await ready(p);
  173. await p.type('#code', lastCode('main', email));
  174. await p.click('#verify');
  175. }
  176. // ident#20: a REAL reload (Page.reload), then hydrated
  177. async function reload(p) {
  178. p._loaded = false;
  179. await p.send('Page.reload', { ignoreCache: false });
  180. const deadline = Date.now() + 15000;
  181. while (!p._loaded && Date.now() < deadline) await sleep(25);
  182. if (!p._loaded) throw new Error('reload: load event never fired');
  183. await ready(p);
  184. }
  185. let browser1, browser2;
  186. try {
  187. browser1 = await launchBrowser({ debugPortRange: CHROME_PORTS });
  188. browser2 = await launchBrowser({ debugPortRange: CHROME_PORTS });
  189. const p = live(await browser1.newPage()); pages.push(p); onDialogs(p);
  190. await viewport(p, 1280);
  191. // ==== 1. sign in to ident, register two apps ==========================================
  192. console.log('# apps: register, list, secret shown once');
  193. const ALICE = '[email protected]';
  194. await p.goto(ID + '/apps');
  195. check('signed out /apps asks to sign in', /sign in/i.test(await txt(p, '#signinfirst')));
  196. await p.goto(ID + '/');
  197. await browserLogin(p, ALICE);
  198. await p.waitForSelector('#skip');
  199. await p.click('#skip');
  200. await p.waitFor('!document.querySelector("#identityform")');
  201. await p.goto(ID + '/apps');
  202. await p.waitForSelector('#newapp'); await ready(p);
  203. check('no apps yet', /No apps yet/.test(await txt(p, '#noapps')));
  204. const register = async (name, origins) => {
  205. await p.click('#newapp');
  206. await p.waitForSelector('#appform');
  207. await p.type('#fappname', name);
  208. await p.type('#forigins', origins);
  209. await p.click('#saveapp');
  210. await p.waitFor('!!document.querySelector("#secret") || /\\S/.test(document.querySelector("#message").textContent)');
  211. };
  212. // a bad origin first: refused, named
  213. await register('Bad', TA + '/callback');
  214. check('origin with a path refused', /no path/.test(await txt(p, '#message')), await txt(p, '#message'));
  215. await p.click('#cancelapp');
  216. await register('Test app A', TA);
  217. const secretA = (await txt(p, '#secret')).trim();
  218. check('secret shown after register (sk_ + 48 hex)', /^sk_[0-9a-f]{48}$/.test(secretA), secretA);
  219. const keyA = (await txt(p, '#apps li:nth-child(1) .apikey')).trim();
  220. check('API key listed (pk_ + 32 hex)', /^pk_[0-9a-f]{32}$/.test(keyA), keyA);
  221. // hybriel#121 (mission 048): a face taking the session syncs the session-derived list back — a row added on top would show twice
  222. check('first app listed ONCE (no session-sync double row)', (await p.evaluate('document.querySelectorAll("#apps li").length')) === 1, await txt(p, '#apps'));
  223. await shot(p, 'secret');
  224. await p.click('#secretdone');
  225. await p.waitFor('!document.querySelector("#secretbox")');
  226. await p.goto(ID + '/apps'); await ready(p);
  227. check('secret not shown again after reload', !(await p.evaluate('document.body.textContent.includes(' + JSON.stringify(secretA) + ')')));
  228. await register('Test app B', TB + ', ' + TB.replace('127.0.0.1', 'localhost'));
  229. const secretB = (await txt(p, '#secret')).trim();
  230. const keyB = (await txt(p, '#apps li:nth-child(2) .apikey')).trim();
  231. check('second app: own key and secret', keyB !== keyA && secretB !== secretA && /^pk_/.test(keyB));
  232. 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'));
  233. check('origins listed', (await txt(p, '#apps li:nth-child(2)')).includes(TB + ' ' + TB.replace('127.0.0.1', 'localhost')));
  234. await p.click('#secretdone');
  235. await shot(p, 'list');
  236. // edit: rename B and keep one origin
  237. await p.click('#apps li:nth-child(2) .edit');
  238. await p.waitForSelector('#appform');
  239. check('edit form filled', (await p.evaluate('document.querySelector("#forigins").value')) === TB + ' ' + TB.replace('127.0.0.1', 'localhost'));
  240. await p.type('#fappname', 'Test app B2', { clear: true });
  241. await p.type('#forigins', TB, { clear: true });
  242. await p.click('#saveapp');
  243. await p.waitFor('/App saved/.test(document.querySelector("#notice").textContent)');
  244. const bRow = await txt(p, '#apps li:nth-child(2)');
  245. check('edit saved (name, origins, key unchanged)', bRow.includes('Test app B2') && !bRow.includes('localhost') && bRow.includes(keyB), bRow);
  246. // ==== 2. the test apps are set up with key + secret ===================================
  247. console.log('# test app setup');
  248. const setupApp = async (base, key, secret) => {
  249. await p.goto(base + '/');
  250. await p.type('#key', key, { clear: true });
  251. await p.type('#secret', secret, { clear: true });
  252. await p.evaluate('window.__old = 1');
  253. await p.click('#savesetup');
  254. await p.waitFor('!window.__old && document.readyState === "complete" && (!!document.querySelector("#login") || !!document.querySelector("#result"))', { label: 'setup saved' });
  255. check('test app ' + base + ' saved key + secret', (await txt(p, '#setupkey')) === key, await txt(p, 'body'));
  256. };
  257. await setupApp(TA, keyA, secretA);
  258. check('test app A set up', (await txt(p, '#setupkey')) === keyA);
  259. await setupApp(TB, keyB, secretB);
  260. // ==== 3. the login button, signed in already, one identity ============================
  261. console.log('# login button: signed in, one identity');
  262. const pressLogin = async (base) => {
  263. await p.goto(base + '/');
  264. await clickSettled(p, '#login');
  265. await p.waitFor('location.pathname.startsWith("/signin/") && !!document.querySelector("#apprequest")', { label: 'ident sign-in page' });
  266. await ready(p);
  267. };
  268. const chooseAndReturn = async (nth, base) => {
  269. await p.waitForSelector('#chooselist');
  270. await p.click(`#chooselist li:nth-child(${nth}) .choose`);
  271. await p.waitFor(`location.href.startsWith(${JSON.stringify(base + '/callback')}) && !!document.querySelector("#result")`, { label: 'back at the app' });
  272. return { identity: (await txt(p, '#identity')).trim(), state: await txt(p, '#userstate'), answer: await txt(p, '#answer'), result: await txt(p, '#result') };
  273. };
  274. await pressLogin(TA);
  275. check('ident names the app and its origin', (await txt(p, '#appname')) === 'Test app A' && (await txt(p, '#apporigin')) === TA);
  276. check('one identity: still shown, one choice', (await p.evaluate('document.querySelectorAll("#chooselist li").length')) === 1 && (await txt(p, '#chooselist li')).includes('Default'));
  277. check('identities management not shown on the app page', !(await p.evaluate('!!document.querySelector("#identitiessection")')));
  278. await shot(p, 'choose-one');
  279. const a1 = await chooseAndReturn(1, TA);
  280. check('back at test app A with an identity id', /^[2-9a-hj-km-np-z]{5}$/.test(a1.identity), JSON.stringify(a1));
  281. check('the app got ONLY the id (no email, no names)', a1.answer === JSON.stringify({ identity: a1.identity }), a1.answer);
  282. check('test app: new user', a1.state === 'new user');
  283. await shot(p, 'testapp-result');
  284. await pressLogin(TA);
  285. const a2 = await chooseAndReturn(1, TA);
  286. check('same identity, same app → same id', a2.identity === a1.identity && a2.state === 'welcome back', JSON.stringify(a2));
  287. await pressLogin(TB);
  288. const b1 = await chooseAndReturn(1, TB);
  289. check('same identity, second app → the SAME id (ident#23)', b1.identity === a1.identity, JSON.stringify([a1.identity, b1.identity]));
  290. // ==== 4. two identities: the choice matters ============================================
  291. console.log('# two identities');
  292. await p.goto(ID + '/'); await ready(p);
  293. await p.click('#newidentity');
  294. await p.waitForSelector('#identityform');
  295. await p.type('#fidentityname', 'Work');
  296. await p.click('#saveidentity');
  297. await p.waitFor('document.querySelectorAll("#identities li").length === 2');
  298. await pressLogin(TA);
  299. check('two identities offered', (await p.evaluate('document.querySelectorAll("#chooselist li").length')) === 2);
  300. await shot(p, 'choose-two');
  301. const aWork = await chooseAndReturn(2, TA);
  302. 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));
  303. await pressLogin(TA);
  304. const aDef = await chooseAndReturn(1, TA);
  305. check('first identity again → its old id', aDef.identity === a1.identity);
  306. // ==== 4b. ident#26: "Used in" on each identity's page ==================================
  307. console.log('# used in (ident#26)');
  308. await p.goto(ID + '/'); await ready(p);
  309. await p.click('#newidentity');
  310. await p.waitForSelector('#identityform');
  311. await p.type('#fidentityname', 'Idle');
  312. await p.click('#saveidentity');
  313. await p.waitFor('document.querySelectorAll("#identities li").length === 3');
  314. 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"))');
  315. const openUsed = async (nth) => {
  316. await p.goto(ID + '/'); await ready(p);
  317. await p.click(`#identities li:nth-child(${nth}) a.used`); // ONE tap from the identities list
  318. await p.waitFor('location.pathname.startsWith("/identity/") && !!document.querySelector("#idlabel")', { label: 'identity page' });
  319. };
  320. await openUsed(1);
  321. 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'));
  322. const rowsDef = await usedRows();
  323. 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));
  324. 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));
  325. check('26: the Notif. chip leads to the per-app page', rowsDef.every(r => /\| \/inbox\/[0-9a-z]{12}$/.test(r)), JSON.stringify(rowsDef));
  326. await shot(p, 'used-in');
  327. await p.click('#usedin li:nth-child(1) a.notif');
  328. await p.waitFor('location.pathname.startsWith("/inbox/") && !!document.querySelector("#connapp")');
  329. check('26: the chip opens that app\'s page for this identity', (await txt(p, '#connapp')) === 'Test app B2' && (await txt(p, '#connidentity')) === 'Default');
  330. await openUsed(2);
  331. const rowsWork = await usedRows();
  332. 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));
  333. await openUsed(3);
  334. 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'));
  335. await shot(p, 'used-in-empty');
  336. await p.goto(ID + '/identity/00000000-0000-0000-0000-000000000000'); await ready(p);
  337. check('26: somebody else\'s / unknown identity id: not found', /does not exist or is not yours/.test(await txt(p, '#notfound')));
  338. // ==== 5. signed out: ident login first, then the choice ===============================
  339. console.log('# login button: signed out');
  340. const q = live(await browser2.newPage()); pages.push(q); onDialogs(q);
  341. await viewport(q, 1280);
  342. await q.goto(TB + '/');
  343. await clickSettled(q, '#login');
  344. await q.waitFor('location.pathname.startsWith("/signin/") && !!document.querySelector("#email")', { label: 'ident login for the app' });
  345. check('signed out: login form under the app banner', (await txt(q, '#apprequest')).includes('Test app B2'));
  346. await shot(q, 'signin-for-app');
  347. const BOB = '[email protected]';
  348. // ident#20 (mission 032): the app login's code step is the page /signin/<rid>/code and
  349. // survives a reload; the code entered after it signs in and the app flow completes
  350. await ready(q);
  351. const ridPath = await q.evaluate('location.pathname');
  352. await q.type('#email', BOB);
  353. await q.click('#sendcode');
  354. await q.waitFor(`location.pathname === ${JSON.stringify(ridPath + '/code')} && !!document.querySelector("#code")`, { label: 'app code page' });
  355. await ready(q);
  356. 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'));
  357. await reload(q);
  358. 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'));
  359. await shot(q, 'code-for-app-reloaded');
  360. await q.type('#code', lastCode('main', BOB));
  361. await q.click('#verify');
  362. // a first login: the optional names come first, then the choice
  363. await q.waitForSelector('#welcome');
  364. 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'));
  365. check('first login via an app: optional names first', /optional/.test(await txt(q, '#welcome')) && !(await q.evaluate('!!document.querySelector("#chooselist")')));
  366. await q.click('#skip');
  367. await q.waitForSelector('#chooselist');
  368. await q.click('#chooselist li:nth-child(1) .choose');
  369. await q.waitFor(`location.href.startsWith(${JSON.stringify(TB + '/callback')}) && !!document.querySelector("#identity")`);
  370. const bob = (await txt(q, '#identity')).trim();
  371. check('another account → another id', /^[2-9a-hj-km-np-z]{5}$/.test(bob) && bob !== b1.identity && bob !== a1.identity);
  372. // an existing account signs in via the app: no names form, straight to the choice
  373. await q.goto(ID + '/'); await ready(q);
  374. await menuClick(q, '#menusignout');
  375. await q.waitForSelector('#email');
  376. await q.goto(TB + '/');
  377. await clickSettled(q, '#login');
  378. await q.waitFor('!!document.querySelector("#email")');
  379. // ident#20: "Other address" on the app's code page → back to /signin/<rid>, the email form
  380. await ready(q);
  381. const ridPath2 = await q.evaluate('location.pathname');
  382. await q.type('#email', '[email protected]');
  383. await q.click('#sendcode');
  384. await q.waitFor(`location.pathname === ${JSON.stringify(ridPath2 + '/code')} && !!document.querySelector("#back")`, { label: 'app code page 2' });
  385. await ready(q);
  386. await q.click('#back');
  387. await q.waitFor(`location.pathname === ${JSON.stringify(ridPath2)} && !!document.querySelector("#email")`, { label: 'back to the app sign-in' });
  388. 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")')));
  389. await reload(q);
  390. 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")')));
  391. await q.goto(ID + ridPath2 + '/code');
  392. await q.waitForSelector('#email');
  393. check('ident#20: app login: /signin/<rid>/code with nothing pending → back to /signin/<rid>', (await q.evaluate('location.pathname')) === ridPath2);
  394. await browserLogin(q, BOB);
  395. await q.waitForSelector('#chooselist');
  396. check('known account: straight to the choice (no names form)', !(await q.evaluate('!!document.querySelector("#welcome")')));
  397. await q.click('#chooselist li:nth-child(1) .choose');
  398. await q.waitFor(`!!document.querySelector("#identity")`);
  399. check('after an OTP login: same id as before', (await txt(q, '#identity')).trim() === bob);
  400. // ==== 6. the login button refuses: error page, never a redirect =======================
  401. console.log('# login button negatives');
  402. const badLogin = async (qs, re, label) => {
  403. const before = p.messages.length;
  404. await p.goto(ID + '/login' + qs);
  405. const url = await here(p);
  406. const msg = await txt(p, '#errormessage');
  407. check(label + ' → error page, no redirect', url.startsWith(ID + '/login') && re.test(msg), url + ' | ' + msg);
  408. p.messages.splice(before); // the page's own 400 is expected in the console
  409. };
  410. await badLogin('?key=' + keyA + '&return=' + encodeURIComponent('http://evil.example.org/callback'), /not one of the origins/, 'foreign origin');
  411. await badLogin('?key=' + keyA + '&return=' + encodeURIComponent(TB + '/callback'), /not one of the origins/, "the other app's origin");
  412. await badLogin('?key=' + keyA + '&return=' + encodeURIComponent(TA + '@evil.example.org/'), /not one of the origins/, 'user@host trick');
  413. await badLogin('?key=' + keyA + '&return=' + encodeURIComponent('javascript:alert(1)'), /http/, 'javascript: URL');
  414. await badLogin('?key=' + keyA, /missing/, 'no return URL');
  415. await badLogin('?key=pk_00000000000000000000000000000000&return=' + encodeURIComponent(TA + '/callback'), /no app has this API key/, 'unknown key');
  416. await badLogin('?return=' + encodeURIComponent(TA + '/callback'), /missing/, 'no key');
  417. const res = await fetch(ID + '/login?key=' + keyA + '&return=' + encodeURIComponent('http://evil.example.org/'), { redirect: 'manual' });
  418. check('foreign origin: HTTP 400, no Location', res.status === 400 && !res.headers.get('location'), res.status + ' ' + res.headers.get('location'));
  419. await shot(p, 'error');
  420. await p.goto(ID + '/signin/0123456789abcdef0123456789abcdef');
  421. check('unknown request id → "expired" page', /unknown or expired/.test(await txt(p, '#badrequest')));
  422. // ==== 7. the exchange ==================================================================
  423. console.log('# exchange');
  424. const aliceCookie = await apiLogin(ID, 'main', ALICE);
  425. const aliceId = idsOf[aliceCookie][0]; // her default (oldest) identity
  426. 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]));
  427. let code = await codeFor(ID, aliceCookie, keyA, TA + '/callback', aliceId);
  428. let r = await exchange(ID, { key: keyA, secret: secretB, code });
  429. check('wrong secret → 401', r.status === 401, r.t);
  430. r = await exchange(ID, { key: 'pk_x', secret: secretA, code });
  431. check('unknown key → 401', r.status === 401, r.t);
  432. r = await exchange(ID, { key: keyA, secret: secretA, code });
  433. check('right key + secret → 200 { identity } only', r.status === 200 && JSON.stringify(Object.keys(r.j)) === '["identity"]' && r.j.identity === a1.identity, r.t);
  434. r = await exchange(ID, { key: keyA, secret: secretA, code });
  435. check('reused code → 400', r.status === 400 && /already used/.test(r.j.error), r.t);
  436. code = await codeFor(ID, aliceCookie, keyA, TA + '/callback', aliceId);
  437. r = await exchange(ID, { key: keyB, secret: secretB, code });
  438. check("other app's code → 400", r.status === 400 && /not issued to this app/.test(r.j.error), r.t);
  439. r = await exchange(ID, { key: keyA, secret: secretA, code });
  440. check('a code shown to the wrong app is spent → 400', r.status === 400, r.t);
  441. r = await exchange(ID, { key: keyA, secret: secretA, code: 'nope' });
  442. check('unknown code → 400', r.status === 400, r.t);
  443. r = await exchange(ID, '{"key": "x",');
  444. check('invalid JSON → 400', r.status === 400 && /not valid JSON/.test(r.j.error), r.t);
  445. r = await exchange(ID, '[1]');
  446. check('not an object → 400', r.status === 400 && /object/.test(r.j.error), r.t);
  447. r = await exchange(ID, { key: keyA, secret: secretA });
  448. check('missing field → 400 naming it', r.status === 400 && r.j.error === 'missing field: code', r.t);
  449. r = await exchange(ID, { key: keyA, secret: secretA, code: 'x', email: 'x' });
  450. check('unknown field → 400 naming it', r.status === 400 && r.j.error === 'unknown field: email', r.t);
  451. r = await exchange(ID, { key: keyA, secret: secretA, code: 5 });
  452. check('wrong type → 400 naming it', r.status === 400 && /field code must be a string/.test(r.j.error), r.t);
  453. r = await exchange(ID, '{"key":"\\ud83d\\ude00","secret":"a","code":"b"}');
  454. check('surrogate escape → 400 (not 500)', r.status === 400, r.t);
  455. const g = await fetch(ID + '/api/exchange');
  456. check('GET /api/exchange → 405', g.status === 405);
  457. // expiry, on the short-clock server (grant TTL 1.5 s)
  458. const sc = await apiLogin(IDS, 'short', '[email protected]');
  459. const sApp = (await emit(IDS, 'appCreate', [{ name: 'S', origins: [TA] }], sc)).value;
  460. const sCode = await codeFor(IDS, sc, sApp.app.apiKey, TA + '/callback', idsOf[sc][0]);
  461. await sleep(2000);
  462. r = await exchange(IDS, { key: sApp.app.apiKey, secret: sApp.secret, code: sCode });
  463. check('expired code → 400', r.status === 400 && /expired/.test(r.j.error), r.t);
  464. const sCode2 = await codeFor(IDS, sc, sApp.app.apiKey, TA + '/callback', idsOf[sc][0]);
  465. r = await exchange(IDS, { key: sApp.app.apiKey, secret: sApp.secret, code: sCode2 });
  466. check('fresh code on the short server → 200', r.status === 200, r.t);
  467. // ==== 8. faces: forged sessions (#31), strict fields, other accounts ==================
  468. console.log('# faces');
  469. const forged = { user: { id: 1 } };
  470. for (const [ev, args] of [['appCreate', [{ name: 'X', origins: [TA] }]], ['appUpdate', [1, { name: 'X', origins: [TA] }]], ['appNewSecret', [1]], ['appDelete', [1]], ['chooseIdentity', ['x', 1]]]) {
  471. const f = await emit(ID, ev, [...args, forged]);
  472. check(`forged session argument refused: ${ev}`, framework_refused(f.raw) || (f.value && /not signed in/.test(f.value.error)), f.raw);
  473. }
  474. let e = await emit(ID, 'appCreate', [{ name: 'X', origins: [TA], secret: 'mine' }], aliceCookie);
  475. check('appCreate unknown field → named', e.value.error === 'unknown field: secret' && e.value.field === 'secret', e.raw);
  476. e = await emit(ID, 'appCreate', [{ name: 'X' }], aliceCookie);
  477. check('appCreate missing origins → named', e.value.field === 'origins', e.raw);
  478. e = await emit(ID, 'appCreate', [{ name: '', origins: [TA] }], aliceCookie);
  479. check('appCreate empty name refused', e.value.field === 'name', e.raw);
  480. e = await emit(ID, 'appCreate', [{ name: 'X', origins: 'http://a.b' }], aliceCookie);
  481. check('appCreate origins not a list refused', e.value.field === 'origins', e.raw);
  482. e = await emit(ID, 'appCreate', [{ name: 'X', origins: Array.from({ length: 11 }, (_, i) => 'http://h' + i + '.example') }], aliceCookie);
  483. check('appCreate 11 origins refused', /at most 10/.test(e.value.error), e.raw);
  484. e = await emit(ID, 'appCreate', [{ name: 'X', origins: ['ftp://a.b'] }], aliceCookie);
  485. check('appCreate ftp origin refused', e.value.field === 'origins', e.raw);
  486. const bobCookie = await apiLogin(ID, 'main', BOB);
  487. const aliceApp = (await ssrIds(ID, '/apps', aliceCookie))[0];
  488. check('ids: app ids are 12-char mpackdb UUIDs (read off /apps)', /^[0-9a-z]{12}$/.test(aliceApp || ''), JSON.stringify(aliceApp));
  489. e = await emit(ID, 'appUpdate', [aliceApp, { name: 'hijack', origins: ['http://evil.example'] }], bobCookie);
  490. check("another account cannot edit alice's app", e.value.error === 'no such app', e.raw);
  491. e = await emit(ID, 'appNewSecret', [aliceApp], bobCookie);
  492. check("another account cannot renew alice's secret", e.value.error === 'no such app', e.raw);
  493. e = await emit(ID, 'appDelete', [aliceApp], bobCookie);
  494. check("another account cannot delete alice's app", e.value.error === 'no such app', e.raw);
  495. const l = await fetch(ID + '/login?key=' + keyA + '&return=' + encodeURIComponent(TA + '/callback'), { redirect: 'manual' });
  496. const rid = l.headers.get('location').split('/').pop();
  497. e = await emit(ID, 'chooseIdentity', [rid, aliceId], bobCookie);
  498. check("choosing another account's identity refused", e.value.error === 'no such identity', e.raw);
  499. e = await emit(ID, 'chooseIdentity', [rid, 1], aliceCookie);
  500. check('chooseIdentity wrong type (a number, the old ids) refused', /must be a string/.test(e.value.error), e.raw);
  501. e = await emit(ID, 'appUpdate', [1, { name: 'X', origins: [TA] }], aliceCookie);
  502. check('appUpdate with an old numeric id: no such app', e.value.error === 'no such app', e.raw);
  503. // ==== 9. new secret, delete (browser) ==================================================
  504. console.log('# new secret, delete');
  505. await p.goto(ID + '/apps'); await ready(p);
  506. p.dialogAnswers.push(false);
  507. await p.click('#apps li:nth-child(1) .newsecret');
  508. await sleep(300);
  509. check('new secret: dismissed confirm changes nothing', !(await p.evaluate('!!document.querySelector("#secretbox")')) && p.dialogs.length === 1);
  510. p.dialogAnswers.push(true);
  511. await p.click('#apps li:nth-child(1) .newsecret');
  512. await p.waitForSelector('#secret');
  513. const secretA2 = (await txt(p, '#secret')).trim();
  514. check('new secret shown once, differs', /^sk_[0-9a-f]{48}$/.test(secretA2) && secretA2 !== secretA);
  515. await p.click('#secretdone');
  516. code = await codeFor(ID, aliceCookie, keyA, TA + '/callback', aliceId);
  517. r = await exchange(ID, { key: keyA, secret: secretA, code });
  518. check('old secret → 401 after renewal', r.status === 401, r.t);
  519. r = await exchange(ID, { key: keyA, secret: secretA2, code });
  520. check('new secret works, same id', r.status === 200 && r.j.identity === a1.identity, r.t);
  521. // the test app still has the old secret: its exchange fails visibly
  522. await pressLogin(TA);
  523. await p.click('#chooselist li:nth-child(1) .choose');
  524. const beforeOld = p.messages.length;
  525. await p.waitFor('!!document.querySelector("#result")');
  526. await sleep(300);
  527. p.messages.splice(beforeOld); // the test app's own 400 page is expected
  528. check('test app with the old secret: exchange refused (401)', (await txt(p, '#status')) === '401', await txt(p, '#result'));
  529. await setupApp(TA, keyA, secretA2);
  530. await pressLogin(TA);
  531. const a3 = await chooseAndReturn(1, TA);
  532. check('test app with the new secret: logged in, same id', a3.identity === a1.identity, JSON.stringify(a3));
  533. // delete app B
  534. await p.goto(ID + '/apps'); await ready(p);
  535. p.dialogAnswers.push(true);
  536. await p.click('#apps li:nth-child(2) .delete');
  537. await p.waitFor('document.querySelectorAll("#apps li").length === 1');
  538. check('app deleted from the list', !(await txt(p, '#apps')).includes('Test app B2'));
  539. await badLogin('?key=' + keyB + '&return=' + encodeURIComponent(TB + '/callback'), /no app has this API key/, 'deleted app key');
  540. // ==== 10. console ======================================================================
  541. const probs = pages.flatMap(x => x.problems().map(m => m.text));
  542. check('no console errors or warnings', probs.length === 0, probs.join(' | '));
  543. } catch (err) {
  544. failed++;
  545. console.log(' FAIL (aborted) ' + (err && err.stack || err));
  546. for (const x of pages) console.log('--- console:\n' + x.dumpConsole());
  547. } finally {
  548. for (const b of [browser1, browser2]) { if (b) { try { await b.close(); } catch {} } }
  549. stopAll();
  550. await sleep(300);
  551. }
  552. console.log(`\n${passed} passed, ${failed} failed`);
  553. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • 061abfe2ident: the apps gate waits until the test app's login button stops moving before it clicks (the page grows after load and the click missed about every second run)mre
  • 45f7e4daident: the user menu's Sign out waits for the server before it reloads (the apps gate failed because the session could still be signed in)mre
  • 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