gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitc28bddeec28bddeeMerge branch 'f2-shell' into mainIdentc28bddee/tests/notify.mjs

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

Branches

Latest commits

  • c28bddeeMerge branch 'f2-shell' into mainIdent
  • c3a40ff6|||PR ident#40 one shell for the app and /start (account part off on /start, #40.1); startshell.hl removed; unused signOut faces gone (#40.4)mre
  • 060f3870ident#40.4: use the shell sign-out faces in regression gatesmre
  • 9b94aa6aMerge branch 'f1b-cleanup' into mainIdent
  • edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
  • 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre
  • c7eef14aMerge branch 'nv1-navigate' into mainIdent
  • 644f9775|||PR ident#36 navigate() instead of window.location in the shell, start shell and homemre
  • 4ca2f921deploy.sh: tar --hard-dereference so backups hold no hard linksmre
  • 23971fb7ident#49: media queries in the language's @media formmre
  • 73f4f97dident: re-vendor to hybriel day38b (mpackdb store-open fix)mre
  • aa056c03ident: a startup error prints its message before exit 1 (hybriel#247)mre
  • ee37a861ident#G48: gitoria's registration gets the wildcard origin of its repo addresses at load (gate tests/gitoria-origin.mjs)mre
  • dc6d486fident#27: the docs gate expects the new Access entry in the main menumre
  • d277633cident#27: README: identity access and the introspect endpointmre
  • e999b0d3ident#27: the Access tab — one key per identity for all its apps: give access in three steps, the overview matrix, a cell's sheet (since, last use, level, rotate, revoke), the app's check POST /api/introspect, agent identities hidden from the login picker, an inbox icon in the header's icon style (gate: tests/access.mjs)mre
  • 436206fcident#47: deploy.sh runs the sign-in gate on the deploy's own port slot, like the sessionwrites and docs gates (the default 8700 can be taken by another process)mre
  • a4887ea3ident#47: the selector's sign-in frame no longer has a Continue button; the identity row itself is the link (gate tests/signin.mjs fails on the old code)mre
  • d8ec703dident#45: /docs shows docs/IDENT.md (hl:markdown, vendored from ac1ed9da), one Docs entry in the main menu, README for developers only, gates tests/docs.mjs and tests/sessionwrites.mjs in deploy.shmre
  • ec6aad35Merge branch 'a28g-amp-callsites' into d45-docsmre