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/notify.mjs

36.9 KB

  1. // tests/notify.mjs — THE GATE OF PIECE 4 (ticket ident#6, mission 013): notification kinds,
  2. // the send API, the inbox, the per-app page. Real headless Chrome (tests/cdp.mjs,
  3. // --disable-gpu) for what the user does; this script plays the APP'S SERVER (key + secret)
  4. // for what an app does:
  5. // an app registers kinds → sends to identities (normal + urgent, with/without icon and
  6. // link, a registered and an unregistered name) → the user sees them in /inbox (all
  7. // identities, newest first), marks read/unread → opens the per-app page → flips switches
  8. // and the override → the STORED effective settings change (read off a COPY of the gate's
  9. // store with tools/dump-store.hl) → a later notification gets the new channels.
  10. // Negatives: wrong secret / unknown key, another app's identity id, unknown identity,
  11. // strict bodies (unknown/missing/wrong-type fields, bad URLs, control characters, invalid
  12. // JSON, GET), forged face sessions (#31), another account can neither see nor change them.
  13. //
  14. // Own servers only, NEVER the dev server and NEVER real mail:
  15. // ident :8410 (IDENT_MAIL_SINK), a node server :8413 (the app's icon + link target).
  16. // Own storage: .scratch/notify-gate/ (wiped at start). Chrome debug ports 8740-8749.
  17. // Screenshots: .scratch/notify-{inbox,appsettings,override}-{390,1280}.png — look at them.
  18. //
  19. // Run: node tests/notify.mjs (exit 0 = all passed)
  20. import { spawn, execFileSync } from 'node:child_process';
  21. import { createServer } from 'node:http';
  22. import { deflateSync } from 'node:zlib';
  23. import { readFileSync, writeFileSync, rmSync, mkdirSync, existsSync, cpSync } from 'node:fs';
  24. import { dirname, join } from 'node:path';
  25. import { fileURLToPath } from 'node:url';
  26. import { launchBrowser, sleep } from './cdp.mjs';
  27. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  28. const APP = join(dirname(fileURLToPath(import.meta.url)), '..');
  29. const G = join(APP, '.scratch/notify-gate');
  30. const SHOTS = join(APP, '.scratch');
  31. const P0 = Number(process.env.NOTIFY_GATE_PORT || 8410); // ident = P0, the app's site = P0+3
  32. const ID = 'http://127.0.0.1:' + P0;
  33. const SITE = 'http://127.0.0.1:' + (P0 + 3); // "the app": its icon and its action link
  34. const CHROME_PORTS = (process.env.NOTIFY_GATE_CHROME || '8740-8749').split('-').map(Number);
  35. const J = JSON.stringify;
  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 });
  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. rmSync(G, { recursive: true, force: true });
  59. mkdirSync(join(G, 'main'), { recursive: true });
  60. const STORE = join(G, 'main', 'ident');
  61. start(APP, {
  62. IDENT_PORT: String(P0), IDENT_STORAGE: STORE, IDENT_SESSIONS: join(G, 'main', 'sess') + '/',
  63. IDENT_MAIL_SINK: join(G, 'main', 'mail.txt'), IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000',
  64. }, 'ident.log');
  65. // the app's site: a 64x64 PNG icon (one blue square, built here) and a page for the link
  66. const png = (() => {
  67. // a valid PNG built with zlib: 64x64 RGB, one colour
  68. const w = 64, h = 64, raw = Buffer.alloc((w * 3 + 1) * h);
  69. for (let y = 0; y < h; y++) { raw[y * (w * 3 + 1)] = 0; for (let x = 0; x < w; x++) { const o = y * (w * 3 + 1) + 1 + x * 3; raw[o] = 0x56; raw[o + 1] = 0x9b; raw[o + 2] = 0xd4; } }
  70. const crcT = []; for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; crcT[n] = c >>> 0; }
  71. const crc = (b) => { let c = 0xffffffff; for (const x of b) c = crcT[(c ^ x) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
  72. const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); };
  73. const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;
  74. return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
  75. })();
  76. const site = createServer((req, res) => {
  77. if (req.url.startsWith('/icon.png')) { res.writeHead(200, { 'content-type': 'image/png' }); res.end(png); return; }
  78. res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
  79. res.end('<!doctype html><html><head><meta charset="utf-8"><title>the app</title></head><body><p id="landed">the app: ' + req.url.replace(/[<>&]/g, '') + '</p></body></html>');
  80. });
  81. await new Promise(r => site.listen(P0 + 3, '127.0.0.1', r));
  82. await up(ID);
  83. // ---- helpers ----------------------------------------------------------------------------
  84. const lastCode = (email) => {
  85. const lines = readFileSync(join(G, 'main', 'mail.txt'), 'utf8').trim().split('\n').filter(l => l.startsWith(email + ' '));
  86. return lines.length ? lines[lines.length - 1].split(' ')[1] : null;
  87. };
  88. let emitI = 0;
  89. // hybriel#16 (mission 036): hl:web itself refuses an emit with one argument too many — the ack is
  90. // ok:false "… the `session` parameter is filled by the server, never by the peer"; the face never runs.
  91. 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; } };
  92. async function emit(event, payload, cookie) {
  93. const r = await fetch(ID + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++emitI, event, payload }) });
  94. const t = await r.text();
  95. let j = null; try { j = JSON.parse(t); } catch {}
  96. return { status: r.status, cookie: (r.headers.get('set-cookie') || '').split(';')[0], value: j && j.value, raw: t };
  97. }
  98. async function api(path, body, method = 'POST') {
  99. const r = await fetch(ID + path, { method, headers: { 'content-type': 'application/json' }, ...(method === 'GET' ? {} : { body: typeof body === 'string' ? body : J(body) }) });
  100. const t = await r.text();
  101. let j = null; try { j = JSON.parse(t); } catch {}
  102. return { status: r.status, j, t };
  103. }
  104. const idsOf = {};
  105. async function apiLogin(email) {
  106. const q = await fetch(ID + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email }) });
  107. if (q.status !== 200) throw new Error('code request failed: ' + q.status);
  108. const v = await emit('verifyCode', [email, lastCode(email), 'UTC']);
  109. if (!v.value || !v.value.account || !v.cookie) throw new Error('api login failed: ' + v.raw);
  110. idsOf[v.cookie] = v.value.identities.map(i => i.id);
  111. return v.cookie;
  112. }
  113. // THE APP'S SIDE of a login: button → choice → exchange → the app-specific identity id
  114. async function appIdentity(cookie, app, identity) {
  115. const l = await fetch(ID + '/login?key=' + app.key + '&return=' + encodeURIComponent(SITE + '/callback'), { redirect: 'manual' });
  116. const rid = (l.headers.get('location') || '').split('/').pop();
  117. const c = await emit('chooseIdentity', [rid, identity], cookie);
  118. const code = new URL(c.value.url).searchParams.get('ident_code');
  119. const x = await api('/api/exchange', { key: app.key, secret: app.secret, code });
  120. if (x.status !== 200) throw new Error('exchange failed: ' + x.t);
  121. return x.j.identity;
  122. }
  123. // THE STORED STATE, read off a COPY (opening a table rewrites it, hybriel #40)
  124. let copyN = 0;
  125. function store() {
  126. const copy = join(G, 'copy-' + (++copyN));
  127. cpSync(STORE, copy, { recursive: true });
  128. const out = execFileSync(join(APP, 'bin/hybriel'), ['tools/dump-store.hl'], { cwd: APP, env: { ...process.env, IDENT_STORAGE: copy }, encoding: 'utf8' });
  129. const line = out.split('\n').find(l => l.startsWith('{'));
  130. return JSON.parse(line);
  131. }
  132. const setting = (s, conn, kind) => s.settings.find(r => r.pair === conn + ':' + kind);
  133. const pages = [];
  134. async function ready(p) { await p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated' }); }
  135. async function viewport(p, w) {
  136. await p.send('Emulation.setDeviceMetricsOverride', { width: w, height: w < 500 ? 844 : 900, deviceScaleFactor: 1, mobile: w < 500 });
  137. }
  138. async function shot(p, name) {
  139. for (const w of [390, 1280]) {
  140. await viewport(p, w);
  141. await sleep(200);
  142. const over = await p.evaluate('document.documentElement.scrollWidth > window.innerWidth');
  143. check(`${name} @${w}px: no horizontal overflow`, !over);
  144. const { data } = await p.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  145. writeFileSync(join(SHOTS, `notify-${name}-${w}.png`), Buffer.from(data, 'base64'));
  146. }
  147. await viewport(p, 1280);
  148. }
  149. const txt = (p, sel) => p.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || ''`);
  150. const attr = (p, sel, a) => p.evaluate(`(document.querySelector(${J(sel)}) || { getAttribute: () => null }).getAttribute(${J(a)})`);
  151. const count = (p, sel) => p.evaluate(`document.querySelectorAll(${J(sel)}).length`);
  152. async function browserLogin(p, email) {
  153. await p.goto(ID + '/');
  154. await p.waitForSelector('#email');
  155. await ready(p);
  156. await p.type('#email', email);
  157. await p.click('#sendcode');
  158. await p.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'code page' });
  159. await ready(p); // ident#20: the code step is its own page (/code) — wait for it to hydrate
  160. await p.type('#code', lastCode(email));
  161. await p.click('#verify');
  162. }
  163. let browser1, browser2;
  164. try {
  165. browser1 = await launchBrowser({ debugPortRange: CHROME_PORTS });
  166. browser2 = await launchBrowser({ debugPortRange: CHROME_PORTS });
  167. const p = await browser1.newPage(); pages.push(p);
  168. await viewport(p, 1280);
  169. // ==== 0. accounts, apps, per-app ids ==================================================
  170. console.log('# setup: alice (2 identities), bob, apps A and B, per-app ids');
  171. const ALICE = '[email protected]', BOB = '[email protected]';
  172. await p.goto(ID + '/inbox');
  173. check('signed out /inbox asks to sign in', /sign in/i.test(await txt(p, '#signinfirst')));
  174. await browserLogin(p, ALICE);
  175. await p.waitForSelector('#skip');
  176. await p.click('#skip');
  177. await p.waitFor('!document.querySelector("#identityform")');
  178. const alice = await apiLogin(ALICE); // a second session of the same account (for API calls)
  179. await emit('addIdentity', [{ identityName: 'Work' }], alice);
  180. const aliceIds = (await emit('editIdentity', [idsOf[alice][0], { identityName: 'Default' }], alice)).value.identities.map(i => i.id);
  181. check('alice has two identities', aliceIds.length === 2, J(aliceIds));
  182. const mkApp = async (name) => { const v = (await emit('appCreate', [{ name, origins: [SITE] }], alice)).value; return { key: v.app.apiKey, secret: v.secret }; };
  183. const A = await mkApp('Chat app'), B = await mkApp('Shop');
  184. const idA1 = await appIdentity(alice, A, aliceIds[0]); // alice Default in A
  185. const idA2 = await appIdentity(alice, A, aliceIds[1]); // alice Work in A
  186. const idB1 = await appIdentity(alice, B, aliceIds[0]); // alice Default in B
  187. const bob = await apiLogin(BOB);
  188. const idBob = await appIdentity(bob, A, idsOf[bob][0]); // bob in A
  189. check('short ids: the same for alice Default in A and B, three different ones in all', idA1 === idB1 && new Set([idA1, idA2, idB1, idBob]).size === 3 && [idA1, idA2, idB1, idBob].every(x => /^[2-9a-hj-km-np-z]{5}$/.test(x)));
  190. let s = store();
  191. const identOf = (short) => s.identities.find(i => i.shortId === short);
  192. const connOf = (app, short) => s.connections.find(c => c.identity === identOf(short).id && c.app === app);
  193. const cA1 = connOf(s.apps.find(x => x.apiKey === A.key).id, idA1), cA2 = connOf(s.apps.find(x => x.apiKey === A.key).id, idA2), cB1 = connOf(s.apps.find(x => x.apiKey === B.key).id, idB1), cBob = connOf(s.apps.find(x => x.apiKey === A.key).id, idBob);
  194. // ==== 1. the app registers its kinds ==================================================
  195. console.log('# kinds');
  196. let r = await api('/api/kinds', { key: A.key, secret: A.secret, kinds: [{ name: 'New comment', push: true, email: false }, { name: 'Weekly digest', push: false, email: true }] });
  197. check('register kinds → 200, the registered list', r.status === 200 && J(r.j) === J({ kinds: [{ email: false, name: 'New comment', push: true }, { email: true, name: 'Weekly digest', push: false }] }), r.t);
  198. r = await api('/api/kinds', { key: A.key, secret: A.secret, kinds: [] });
  199. check('empty list → 200, lists the kinds', r.status === 200 && r.j.kinds.length === 2, r.t);
  200. const kindsBad = [
  201. [{ key: A.key, secret: B.secret, kinds: [] }, 401, /wrong secret/, 'wrong secret'],
  202. [{ key: 'pk_nope', secret: A.secret, kinds: [] }, 401, /wrong secret/, 'unknown key'],
  203. [{ key: A.key, secret: A.secret }, 400, /missing field: kinds/, 'missing kinds'],
  204. [{ key: A.key, secret: A.secret, kinds: {} }, 400, /must be a list/, 'kinds not a list'],
  205. [{ key: A.key, secret: A.secret, kinds: [], extra: 1 }, 400, /unknown field: extra/, 'unknown top field'],
  206. [{ key: A.key, secret: A.secret, kinds: [{ name: 'X', push: true, email: true, sound: 1 }] }, 400, /unknown field: kinds\[0\]\.sound/, 'unknown kind field'],
  207. [{ key: A.key, secret: A.secret, kinds: [{ name: 'X', push: true }] }, 400, /missing field: kinds\[0\]\.email/, 'missing kind field'],
  208. [{ key: A.key, secret: A.secret, kinds: [{ name: 'X', push: 'yes', email: true }] }, 400, /push must be a boolean/, 'push not boolean'],
  209. [{ key: A.key, secret: A.secret, kinds: [{ name: '', push: true, email: true }] }, 400, /empty/, 'empty name'],
  210. [{ key: A.key, secret: A.secret, kinds: [{ name: 'x'.repeat(61), push: true, email: true }] }, 400, /longer than 60/, 'name too long'],
  211. [{ key: A.key, secret: A.secret, kinds: [{ name: 'Y', push: true, email: true }, { name: 'Y', push: false, email: true }] }, 400, /twice/, 'duplicate name'],
  212. [{ key: A.key, secret: A.secret, kinds: ['X'] }, 400, /must be an object/, 'kind not an object'],
  213. ];
  214. for (const [body, st, re, label] of kindsBad) {
  215. r = await api('/api/kinds', body);
  216. check(`kinds refused: ${label} → ${st}`, r.status === st && re.test(r.j && r.j.error), r.t);
  217. }
  218. r = await api('/api/kinds', { key: A.key, secret: A.secret, kinds: [{ name: 'Ok', push: true, email: true }, { name: 'Bad', push: 1, email: true }] });
  219. s = store();
  220. check('a refused call writes nothing (no kind "Ok")', r.status === 400 && !s.kinds.some(k => k.name === 'Ok'), r.t);
  221. r = await api('/api/kinds', '{"key":');
  222. check('kinds: invalid JSON → 400', r.status === 400 && /not valid JSON/.test(r.j.error), r.t);
  223. r = await api('/api/kinds', null, 'GET');
  224. check('kinds: GET → 405', r.status === 405, r.t);
  225. // ==== 2. the app sends ================================================================
  226. console.log('# send');
  227. const send = (body) => api('/api/notify', { key: A.key, secret: A.secret, ...body });
  228. const n1 = await send({ identity: idA1, name: 'New comment', text: 'Bea commented on your post:\n“Nice one!”', icon: SITE + '/icon.png', link: SITE + '/post/7' });
  229. check('normal notification with icon + link → 200 { id }', n1.status === 200 && /^[0-9a-z]{12}$/.test(n1.j.id) && Object.keys(n1.j).length === 1, n1.t);
  230. await sleep(20);
  231. const n2 = await send({ identity: idA2, name: 'Weekly digest', text: 'Your week in the chat app.', urgent: true });
  232. check('urgent notification without icon/link → 200', n2.status === 200, n2.t);
  233. await sleep(20);
  234. const n3 = await send({ identity: idA1, name: 'Mention', text: 'You were mentioned.', urgent: false });
  235. check('unregistered name → allowed (200)', n3.status === 200, n3.t);
  236. await sleep(20);
  237. const n4 = await api('/api/notify', { key: B.key, secret: B.secret, identity: idB1, name: 'Invoice', text: 'Invoice #12 is ready.', link: SITE + '/invoice/12' });
  238. check('app B sends to its own id → 200', n4.status === 200, n4.t);
  239. await sleep(20);
  240. const nBob = await send({ identity: idBob, name: 'New comment', text: 'BOB-ONLY secret text' });
  241. check('app A sends to bob → 200', nBob.status === 200, nBob.t);
  242. const sendBad = [
  243. [{ key: A.key, secret: B.secret, identity: idA1, name: 'x', text: 'y' }, 401, /wrong secret/, 'wrong secret'],
  244. [{ key: 'pk_x', secret: A.secret, identity: idA1, name: 'x', text: 'y' }, 401, /wrong secret/, 'unknown key'],
  245. [{ key: B.key, secret: B.secret, identity: idA2, name: 'x', text: 'y' }, 404, /unknown identity/, "an identity that never logged in to this app"],
  246. [{ key: A.key, secret: A.secret, identity: '0'.repeat(32), name: 'x', text: 'y' }, 404, /unknown identity/, 'unknown identity id'],
  247. [{ key: A.key, secret: A.secret, identity: aliceIds[0], name: 'x', text: 'y' }, 404, /unknown identity/, "ident's own identity id"],
  248. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x', text: 'y', email: '[email protected]' }, 400, /unknown field: email/, 'unknown field'],
  249. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x' }, 400, /missing field: text/, 'missing text'],
  250. [{ key: A.key, secret: A.secret, identity: idA1, text: 'y' }, 400, /missing field: name/, 'missing name'],
  251. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x', text: 'y', urgent: 'yes' }, 400, /urgent must be a boolean/, 'urgent not boolean'],
  252. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x', text: 5 }, 400, /text must be a string/, 'text not a string'],
  253. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x', text: ' ' }, 400, /text is empty/, 'empty text'],
  254. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x', text: 'y'.repeat(2001) }, 400, /longer than 2000/, 'text too long'],
  255. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x', text: 'a\u0007b' }, 400, /control character/, 'control char in text'],
  256. [{ key: A.key, secret: A.secret, identity: idA1, name: 'a\nb', text: 'y' }, 400, /control character/, 'newline in name'],
  257. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x', text: 'y', icon: 'javascript:alert(1)' }, 400, /http/, 'javascript: icon'],
  258. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x', text: 'y', link: 'ftp://a.b/' }, 400, /http/, 'ftp link'],
  259. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x', text: 'y', link: 'https://a.b/x y' }, 400, /not allowed/, 'space in link'],
  260. [{ key: A.key, secret: A.secret, identity: idA1, name: 'x', text: 'y', link: 'https:///x' }, 400, /no host/, 'link without host'],
  261. ];
  262. for (const [body, st, re, label] of sendBad) {
  263. r = await api('/api/notify', body);
  264. check(`send refused: ${label} → ${st}`, r.status === st && re.test(r.j && r.j.error), r.t);
  265. }
  266. r = await api('/api/notify', '{"key":"a","secret":"b","identity":"c","name":"d","text":"\\ud83d\\ude00"}');
  267. check('send: surrogate escape → 400 (not 500)', r.status === 400, r.t);
  268. r = await api('/api/notify', '[1]');
  269. check('send: not an object → 400', r.status === 400 && /object/.test(r.j.error), r.t);
  270. r = await api('/api/notify', null, 'GET');
  271. check('send: GET → 405', r.status === 405, r.t);
  272. // what was stored: channels per notification, nothing delivered
  273. s = store();
  274. const note = (id) => s.notifications.find(n => n.id === id);
  275. check('stored: 5 notifications (refusals stored nothing)', s.notifications.length === 5, s.notifications.length);
  276. let x = note(n1.j.id);
  277. check('New comment (preset push on, email off): push, no mail', x && x.push === true && x.mail === 'none' && x.urgent === false, J(x));
  278. check('stored fields: identity, app, connection, icon, link, text, unread, not delivered', x && x.identity === aliceIds[0] && x.connection === cA1.id && x.icon === SITE + '/icon.png' && x.link === SITE + '/post/7' && x.text.includes('\n') && x.read === false && x.pushSent === false && x.mailSent === false, J(x));
  279. x = note(n2.j.id);
  280. check('urgent Weekly digest (email on, no push device): mail now', x && x.urgent === true && x.push === false && x.mail === 'now', J(x));
  281. x = note(n3.j.id);
  282. check('unregistered Mention: daily mail, no push', x && x.push === false && x.mail === 'daily', J(x));
  283. const mention = s.kinds.find(k => k.name === 'Mention');
  284. check('unregistered name stored as an unregistered kind (email on, push off)', mention && mention.registered === false && mention.email === true && mention.push === false, J(mention));
  285. check('effective settings stored for the connection', setting(s, cA1.id, 'New comment') && setting(s, cA1.id, 'New comment').push === true && setting(s, cA1.id, 'New comment').email === false && setting(s, cA1.id, 'Mention').push === false && setting(s, cA1.id, 'Mention').email === true, J(s.settings));
  286. // ==== 3. the inbox (browser) ==========================================================
  287. console.log('# inbox');
  288. await p.goto(ID + '/inbox');
  289. await p.waitForSelector('#inbox'); await ready(p);
  290. const names = await p.evaluate('[...document.querySelectorAll("#inbox li note-name")].map(e => e.textContent)');
  291. check('inbox: alice sees her 4 (both identities, both apps), newest first', J(names) === J(['Invoice', 'Mention', 'Weekly digest', 'New comment']), J(names));
  292. check('inbox: bob\'s notification is not there', !(await p.evaluate('document.body.textContent.includes("BOB-ONLY")')));
  293. check('inbox: 4 unread', (await txt(p, '#unreadcount')) === '4 unread', await txt(p, '#unreadcount'));
  294. const row = (n) => `#inbox li:nth-child(${n})`;
  295. check('inbox: app + identity shown', (await txt(p, row(1) + ' note-from')) === 'Shop · Default' && (await txt(p, row(3) + ' note-from')) === 'Chat app · Work', (await txt(p, row(1) + ' note-from')) + ' | ' + (await txt(p, row(3) + ' note-from')));
  296. check('inbox: text with its line break', (await p.evaluate(`document.querySelector("${row(4)} note-text").innerText`)).includes('post:\n“Nice one!”'));
  297. check('inbox: icon shown (loaded, no referrer)', (await attr(p, row(4) + ' img.icon', 'src')) === SITE + '/icon.png' && (await attr(p, row(4) + ' img.icon', 'referrerpolicy')) === 'no-referrer' && (await p.evaluate(`document.querySelector("${row(4)} img.icon").naturalWidth`)) === 64);
  298. check('inbox: no icon / no link where none was sent', (await count(p, row(3) + ' img')) === 0 && (await count(p, row(3) + ' a.action')) === 0);
  299. check('inbox: action link', (await attr(p, row(4) + ' a.action', 'href')) === SITE + '/post/7' && (await attr(p, row(4) + ' a.action', 'rel')) === 'noopener noreferrer');
  300. check('inbox: urgent badge only on the urgent one', (await count(p, row(3) + ' urgent-badge')) === 1 && (await count(p, '#inbox urgent-badge')) === 1);
  301. check('inbox: time shown', /^\d{4}-\d\d-\d\d \d\d:\d\d UTC$/.test(await txt(p, row(4) + ' time')), await txt(p, row(4) + ' time'));
  302. check('inbox: all unread', (await count(p, '#inbox li.unread')) === 4);
  303. await shot(p, 'inbox');
  304. // mark read / unread
  305. await p.click(row(4) + ' .toggle');
  306. await p.waitFor(`document.querySelector("${row(4)}").className === "read"`, { label: 'marked read' });
  307. check('mark read: row read, 3 unread, button says Mark unread', (await txt(p, '#unreadcount')) === '3 unread' && (await txt(p, row(4) + ' .toggle')) === 'Mark unread');
  308. await p.goto(ID + '/inbox'); await ready(p);
  309. check('read state survives a reload', (await attr(p, row(4), 'class')) === 'read' && (await txt(p, '#unreadcount')) === '3 unread');
  310. s = store();
  311. check('stored: read = true, readAt set', note(n1.j.id).read === true && note(n1.j.id).readAt > 0);
  312. await p.click(row(3) + ' .toggle');
  313. await p.waitFor(`document.querySelector("${row(3)}").className === "read"`);
  314. await p.click(row(3) + ' .toggle');
  315. await p.waitFor(`document.querySelector("${row(3)}").className === "unread"`, { label: 'marked unread' });
  316. check('mark unread again', (await txt(p, '#unreadcount')) === '3 unread');
  317. await shot(p, 'inbox-read');
  318. // the action link opens the app
  319. const href = await attr(p, row(4) + ' a.action', 'href');
  320. check('action link target answers (the app)', (await (await fetch(href)).text()).includes('/post/7'));
  321. // ==== 4. the per-app page ===============================================================
  322. console.log('# per-app page');
  323. const conns = await p.evaluate('[...document.querySelectorAll("#conns li")].map(li => li.textContent)');
  324. check('inbox lists the 3 app connections (identity · since)', conns.length === 3 && conns.some(c => c.startsWith('Chat appWork · since')) && conns.some(c => c.startsWith('ShopDefault · since')), J(conns));
  325. await p.click(`#conns a[href="/inbox/${cA1.id}"]`);
  326. await p.waitFor(`location.pathname === "/inbox/${cA1.id}" && !!document.querySelector("#kinds")`, { label: 'per-app page' });
  327. await ready(p);
  328. const since = new Date(cA1.created).toISOString();
  329. check('per-app page: app, identity, registered since (= the connection\'s created)', (await txt(p, '#connapp')) === 'Chat app' && (await txt(p, '#connidentity')) === 'Default' && (await txt(p, '#connsince')) === since.slice(0, 10) + ' ' + since.slice(11, 16) + ' UTC', (await txt(p, '#connsince')) + ' vs ' + since);
  330. const kindNames = await p.evaluate('[...document.querySelectorAll("#kinds kind-name")].map(e => e.textContent)');
  331. check('per-app page: all the app\'s notifications by name', J(kindNames) === J(['Mention', 'New comment', 'Weekly digest']), J(kindNames));
  332. const k = (n, ch) => `#kinds li:nth-child(${n}) .switch.${ch}`;
  333. const state = async () => ({
  334. ov: [await attr(p, '#ovactive', 'aria-checked'), await attr(p, '#ovpush', 'aria-checked'), await attr(p, '#ovemail', 'aria-checked')],
  335. kinds: await p.evaluate('[...document.querySelectorAll("#kinds li")].map(li => [li.querySelector(".switch.push") ? li.querySelector(".switch.push").getAttribute("aria-checked") : "none", li.querySelector(".switch.email").getAttribute("aria-checked")])'),
  336. });
  337. let st = await state();
  338. check('switches show the presets (Mention: no push)', J(st.kinds) === J([['none', 'true'], ['true', 'false'], ['false', 'true']]), J(st));
  339. check('override off, its switches: push off, email on', J(st.ov) === J(['false', 'false', 'true']), J(st.ov));
  340. check('Mention says it is not registered', /not registered/.test(await txt(p, '#kinds li:nth-child(1) kind-preset')));
  341. await shot(p, 'appsettings');
  342. // flip: New comment email on, Weekly digest push on
  343. await p.click(k(2, 'email'));
  344. await p.waitFor(`document.querySelector(${J(k(2, 'email'))}).getAttribute("aria-checked") === "true"`, { label: 'email switched on' });
  345. await p.click(k(3, 'push'));
  346. await p.waitFor(`document.querySelector(${J(k(3, 'push'))}).getAttribute("aria-checked") === "true"`, { label: 'push switched on' });
  347. check('flip shows "Saved."', (await txt(p, '#notice')) === 'Saved.');
  348. s = store();
  349. let nc = setting(s, cA1.id, 'New comment'), wd = setting(s, cA1.id, 'Weekly digest');
  350. check('stored: New comment user email on → effective push on + email on', nc.userEmail === 'on' && nc.push === true && nc.email === true, J(nc));
  351. check('stored: Weekly digest user push on → effective push on + email on', wd.userPush === 'on' && wd.push === true && wd.email === true, J(wd));
  352. check('other identity\'s settings untouched (Work in the same app)', setting(s, cA2.id, 'New comment').email === false, J(setting(s, cA2.id, 'New comment')));
  353. await p.goto(ID + '/inbox/' + cA1.id); await ready(p);
  354. st = await state();
  355. check('switches survive a reload', J(st.kinds) === J([['none', 'true'], ['true', 'true'], ['true', 'true']]), J(st));
  356. // a notification now follows the new effective settings
  357. const n5 = await send({ identity: idA1, name: 'New comment', text: 'Another comment.' });
  358. s = store();
  359. check('new notification follows the user: push + daily mail', note(n5.j.id).push === true && note(n5.j.id).mail === 'daily', J(note(n5.j.id)));
  360. // THE OVERRIDE
  361. await p.click('#ovactive');
  362. await p.waitFor('document.querySelector("#ovactive").getAttribute("aria-checked") === "true"', { label: 'override on' });
  363. st = await state();
  364. check('override on: every kind = push off, email on', J(st.kinds) === J([['none', 'true'], ['false', 'true'], ['false', 'true']]), J(st));
  365. check('override on: per-kind switches locked', (await count(p, '#kinds .switch.locked')) === 5, await count(p, '#kinds .switch.locked'));
  366. await p.click('#ovemail');
  367. await p.waitFor('document.querySelector("#ovemail").getAttribute("aria-checked") === "false"', { label: 'override email off' });
  368. await p.click('#ovpush');
  369. await p.waitFor('document.querySelector("#ovpush").getAttribute("aria-checked") === "true"', { label: 'override push on' });
  370. st = await state();
  371. check('override push on / email off: all kinds follow, Mention still no push', J(st.kinds) === J([['none', 'false'], ['true', 'false'], ['true', 'false']]), J(st));
  372. s = store();
  373. const ovr = setting(s, cA1.id, '');
  374. check('stored: the override row', ovr && ovr.active === true && ovr.push === true && ovr.email === false, J(ovr));
  375. check('stored effective: all kinds email off, push on where registered', ['New comment', 'Weekly digest'].every(n => setting(s, cA1.id, n).push === true && setting(s, cA1.id, n).email === false) && setting(s, cA1.id, 'Mention').push === false && setting(s, cA1.id, 'Mention').email === false, J(s.settings.filter(r => r.connection === cA1.id)));
  376. check('stored: the user\'s own switches kept under the override', setting(s, cA1.id, 'New comment').userEmail === 'on');
  377. await shot(p, 'override');
  378. const n6 = await send({ identity: idA1, name: 'Mention', text: 'Mentioned again.', urgent: true });
  379. const n7 = await send({ identity: idA1, name: 'Weekly digest', text: 'Digest.' });
  380. s = store();
  381. check('under the override: urgent Mention (push not allowed, email off) → inbox only', note(n6.j.id).push === false && note(n6.j.id).mail === 'none', J(note(n6.j.id)));
  382. check('under the override: Weekly digest → push, no mail', note(n7.j.id).push === true && note(n7.j.id).mail === 'none', J(note(n7.j.id)));
  383. // clicking a locked switch changes nothing
  384. await p.click(k(2, 'email'));
  385. await sleep(300);
  386. check('a locked switch does nothing', (await attr(p, k(2, 'email'), 'aria-checked')) === 'false');
  387. await p.click('#ovactive');
  388. await p.waitFor('document.querySelector("#ovactive").getAttribute("aria-checked") === "false"', { label: 'override off' });
  389. st = await state();
  390. check('override off: the user\'s own switches are back', J(st.kinds) === J([['none', 'true'], ['true', 'true'], ['true', 'true']]), J(st));
  391. s = store();
  392. check('stored effective back to the user\'s switches', setting(s, cA1.id, 'New comment').email === true && setting(s, cA1.id, 'Mention').email === true);
  393. // the app changes its presets / registers the unregistered name
  394. r = await api('/api/kinds', { key: A.key, secret: A.secret, kinds: [{ name: 'Mention', push: true, email: false }, { name: 'New comment', push: false, email: false }] });
  395. check('app re-registers: Mention now registered', r.status === 200 && r.j.kinds.length === 3, r.t);
  396. s = store();
  397. check('stored effective follows the new presets where the user did not switch', setting(s, cA1.id, 'Mention').push === true && setting(s, cA1.id, 'Mention').email === false && setting(s, cA2.id, 'New comment').push === false, J([setting(s, cA1.id, 'Mention'), setting(s, cA2.id, 'New comment')]));
  398. check('…and the user\'s switches still win', setting(s, cA1.id, 'New comment').email === true, J(setting(s, cA1.id, 'New comment')));
  399. await p.goto(ID + '/inbox/' + cA1.id); await ready(p);
  400. check('Mention now has a push switch', (await count(p, '#kinds li:nth-child(1) .switch.push')) === 1 && (await attr(p, k(1, 'push'), 'aria-checked')) === 'true');
  401. // ==== 5. faces: forged sessions, strict, other accounts ===============================
  402. console.log('# faces');
  403. const forged = { user: { id: s.accounts.find(a => a.email === ALICE).id } };
  404. for (const [ev, args] of [['inboxMark', [n1.j.id, true]], ['inboxSwitch', [cA1.id, 'New comment', 'email', false]], ['inboxOverride', [cA1.id, 'active', true]]]) {
  405. const f = await emit(ev, [...args, forged]);
  406. check(`forged session argument refused: ${ev}`, framework_refused(f.raw) || (f.value && /not signed in/.test(f.value.error)), f.raw);
  407. const f2 = await emit(ev, args);
  408. check(`no session refused: ${ev}`, f2.value && /not signed in/.test(f2.value.error), f2.raw);
  409. }
  410. let e = await emit('inboxMark', [n1.j.id, false], bob);
  411. check("bob cannot mark alice's notification", e.value.error === 'no such notification', e.raw);
  412. e = await emit('inboxSwitch', [cA1.id, 'New comment', 'email', false], bob);
  413. check("bob cannot switch alice's settings", e.value.error === 'no such app connection', e.raw);
  414. e = await emit('inboxOverride', [cA1.id, 'active', true], bob);
  415. check("bob cannot set alice's override", e.value.error === 'no such app connection', e.raw);
  416. const bobPage = await (await fetch(ID + '/inbox/' + cA1.id, { headers: { cookie: bob } })).text();
  417. check("bob opening alice's per-app page: not found, nothing of hers", bobPage.includes('does not exist or is not yours') && !bobPage.includes('Weekly digest'));
  418. const bobInbox = await (await fetch(ID + '/inbox', { headers: { cookie: bob } })).text();
  419. check("bob's inbox: only his own", bobInbox.includes('BOB-ONLY') && !bobInbox.includes('Invoice') && !bobInbox.includes('Mention'));
  420. s = store();
  421. check("alice's data unchanged by bob", note(n1.j.id).read === true && setting(s, cA1.id, 'New comment').email === true && !setting(s, cA1.id, '').active);
  422. e = await emit('inboxMark', [n1.j.id, 'yes'], alice);
  423. check('inboxMark: read not a boolean → refused', /must be a boolean/.test(e.value.error), e.raw);
  424. e = await emit('inboxMark', [5, true], alice);
  425. check('inboxMark: id not a string → refused', e.value.error === 'no such notification', e.raw);
  426. e = await emit('inboxSwitch', [cA1.id, 'New comment', 'sms', true], alice);
  427. check('inboxSwitch: unknown channel refused', /push or email/.test(e.value.error), e.raw);
  428. e = await emit('inboxSwitch', [cA1.id, 'New comment', 'email', 'on'], alice);
  429. check('inboxSwitch: value not a boolean refused', /must be a boolean/.test(e.value.error), e.raw);
  430. e = await emit('inboxSwitch', [cA1.id, 'Nope', 'email', true], alice);
  431. check('inboxSwitch: unknown kind refused', /no such notification kind/.test(e.value.error), e.raw);
  432. e = await emit('inboxSwitch', [cB1.id, 'Invoice', 'push', true], alice);
  433. check('inboxSwitch: push on an unregistered kind refused', /cannot be pushed/.test(e.value.error), e.raw);
  434. e = await emit('inboxSwitch', [7, 'Invoice', 'email', true], alice);
  435. check('inboxSwitch: connection not a string refused', /must be a string/.test(e.value.error), e.raw);
  436. e = await emit('inboxOverride', [cA1.id, 'sound', true], alice);
  437. check('inboxOverride: unknown field refused', /active, push or email/.test(e.value.error), e.raw);
  438. e = await emit('inboxSwitch', [cBob.id, 'New comment', 'email', true], alice);
  439. check("alice cannot switch bob's connection", e.value.error === 'no such app connection', e.raw);
  440. const unknownPage = await (await fetch(ID + '/inbox/zzzzzzzzzzzz', { headers: { cookie: alice } })).text();
  441. check('unknown connection id → not found page', unknownPage.includes('does not exist or is not yours'));
  442. const signedOutPage = await (await fetch(ID + '/inbox/' + cA1.id)).text();
  443. check('signed out per-app page → sign in', signedOutPage.includes('Sign in to ident first') && !signedOutPage.includes('Weekly digest'));
  444. // ==== 6. a second browser: bob sees only his own ======================================
  445. console.log('# second browser (bob)');
  446. const q = await browser2.newPage(); pages.push(q);
  447. await viewport(q, 390);
  448. await browserLogin(q, BOB);
  449. await q.waitFor('!!document.querySelector("#identities")');
  450. await q.goto(ID + '/inbox'); await q.waitForSelector('#inbox'); await ready(q);
  451. check('bob (browser): one notification, his', (await count(q, '#inbox li')) === 1 && (await txt(q, '#inbox li note-text')) === 'BOB-ONLY secret text');
  452. await q.goto(ID + '/inbox/' + cA1.id);
  453. check("bob (browser): alice's per-app page refused", /not yours/.test(await txt(q, '#notfound')));
  454. // ==== 7. console ======================================================================
  455. const probs = pages.flatMap(x => x.problems().map(m => m.text));
  456. check('no console errors or warnings', probs.length === 0, probs.join(' | '));
  457. } catch (err) {
  458. failed++;
  459. console.log(' FAIL (aborted) ' + (err && err.stack || err));
  460. for (const x of pages) console.log('--- console:\n' + x.dumpConsole());
  461. } finally {
  462. for (const b of [browser1, browser2]) { if (b) { try { await b.close(); } catch {} } }
  463. for (const { p } of procs) { try { p.kill(); } catch {} }
  464. site.close();
  465. await sleep(300);
  466. }
  467. console.log(`\n${passed} passed, ${failed} failed`);
  468. 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