gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9722964f9722964fre-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)mre9722964f/tests/apps.mjs

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

Branches

Latest commits

  • 9722964fre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • c9b196c9tests/iplimit: wait for the welcome form itself after B's first login (identities list renders before it); mission 017 reportmre
  • 72e0f587ident#26: identity page with "Used in" (app, since, last use, Notif. chip, empty state); lastLogin recorded at exchange; gates + lisbeth E2E; mission 016 reportmre
  • 94576fbcident#26 WIP: identity page /identity/:iid with "Used in" (app, since, last use, Notif. chip), lastLogin recorded at exchange, "Used in…" link on the identities list; apps gate 4b, e2e-usedin.mjsmre
  • 349cb502tests/invites: wait for hydration on the code page before entering the code (native GET submit raced the welcome form); mission 015 reportmre
  • d1bf4720tests: no hard-coded ports — every gate's ports and fixture origins come from <GATE>_PORT / _CHROME env (defaults unchanged; Bob/fixture origins follow, selector cookie name too)mre
  • 6280c92fre-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • 147744bftests/migration: the fixture app origin follows MIGRATION_GATE_TESTAPP_PORT (oldstore-009 OLD_TESTAPP)mre
  • 48cd36bctests/migration: ports from env (MIGRATION_GATE_PORT, MIGRATION_GATE_TESTAPP_PORT); 8395/8396 were taken by a foreign servermre
  • 3d9b2fd8docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 19b7e3c3deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • c8a596f4re-vendor Hybriel 66c3db71 (web batch 4); e2e: main menu marked after in-place sign-in is a normal check; report 014mre
  • 8f3dc1ectests: delivery allow-list for the stopped server's network errors uses the gate port, not 8700mre
  • 9cc8eddftests: notify and iplimit gate Chrome ports from env (NOTIFY_GATE_CHROME, IPLIMIT_GATE_CHROME_A/B)mre
  • d6da2d02tests: delivery and migration gate ports from env (DELIVERY_GATE_PORT, DELIVERY_GATE_CHROME, MIGRATION_GATE_CHROME) — hard-coded 8700-8719 collided with a worker during deploymre
  • 7276a008ident mission 013: re-vendor Hybriel master f9614007 (#200, #202 mpackdb copy fix); gates and e2e rerunmre
  • e13e30c3ident mission 013: report, mission, repro, LOGmre
  • eff734f3ident mission 013: in-place sign-out also closes the code step (no leftover code form); checksmre
  • b7a61546ident mission 013: e2e — in-place main-menu mark kept as a known gapmre
  • 59b43d81ident mission 013: sign out everywhere keeps this browser's own (signed-out) session so the page goes on in placemre