gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9baad7459baad745tests: browser gate waits for the reloaded document (offline reload race under CPU throttle); HL_CPU_THROTTLE knobmre9baad745/tests/apps.mjs

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

Branches

Latest commits

  • 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
  • c8a596f4re-vendor Hybriel 66c3db71 (web batch 4); e2e: main menu marked after in-place sign-in is a normal check; report 014mre
  • 8f3dc1ectests: delivery allow-list for the stopped server's network errors uses the gate port, not 8700mre
  • 9cc8eddftests: notify and iplimit gate Chrome ports from env (NOTIFY_GATE_CHROME, IPLIMIT_GATE_CHROME_A/B)mre
  • d6da2d02tests: delivery and migration gate ports from env (DELIVERY_GATE_PORT, DELIVERY_GATE_CHROME, MIGRATION_GATE_CHROME) — hard-coded 8700-8719 collided with a worker during deploymre
  • 7276a008ident mission 013: re-vendor Hybriel master f9614007 (#200, #202 mpackdb copy fix); gates and e2e rerunmre
  • e13e30c3ident mission 013: report, mission, repro, LOGmre
  • eff734f3ident mission 013: in-place sign-out also closes the code step (no leftover code form); checksmre