gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchmainf9b8f918Merge branch 'calendar-vendor-day61' into mainAtlasmain/tests/push.mjs

26.2 KB

  1. // tests/push.mjs — calendar#9 part 2 (mission 008): WEB PUSH, a reminder reaches a device whose calendar is CLOSED.
  2. // node tests/push.mjs [app dir] env: PUSH_GATE_PORT (app, default 8700; ident +1; the fake push service +2; Chrome +4),
  3. // PUSH_GATE_SCRATCH. A real headless Chrome as a 390 px phone, own ident, own server + storage, VAPID keys made here.
  4. // The FAKE PUSH SERVICE is a local http server that decrypts like a user agent (ECDH with the subscription's private key,
  5. // RFC 8291; the approach of hybriel tests/core-ast/web-tickets.mjs #173): it answers 201 at /ok/*, 410 at /gone/*.
  6. // Headless Chrome cannot reach a real push service, so the browser's `PushManager.subscribe` is replaced by one that answers
  7. // the subscription made here (the page's own code — subscribePush, the button, the server emit — is the real one).
  8. // 1 ok tap "Turn on notifications" → the page says it is subscribed; the browser is then CLOSED; at the reminder time
  9. // the fake service gets ONE encrypted push: VAPID header with the app's key, payload = event title + "Starts in 1 minute"
  10. // 2 gone a device whose service answers 410 gets the first push, and none after it (the subscription is dropped)
  11. // 4 test a subscribed device taps "Send a test notification": ONE push, ~10 s later, to that device only (calendar#12)
  12. // 3 shown + off a device that allowed notifications before is subscribed when the app is shown again (no touch); "Turn off on this device" unsubscribes it and the server drops it: no push, a reload does not subscribe it again (PUSH_GATE_ONLY3=1 runs only this)
  13. import { spawn } from 'node:child_process';
  14. import { writeFileSync, existsSync, mkdirSync, rmSync } from 'node:fs';
  15. import { createServer as httpServer } from 'node:http';
  16. import { generateKeyPairSync, createECDH, hkdfSync, createDecipheriv, randomBytes, verify } from 'node:crypto';
  17. import { dirname, join, resolve } from 'node:path';
  18. import { fileURLToPath } from 'node:url';
  19. const HERE = dirname(fileURLToPath(import.meta.url));
  20. const APP = resolve(process.argv[2] || resolve(HERE, '..'));
  21. const PORT = Number(process.env.PUSH_GATE_PORT || 8700);
  22. const FPORT = PORT + 2, CPORT = PORT + 4;
  23. const BASE = `http://127.0.0.1:${PORT}`;
  24. const SCRATCH = resolve(process.env.PUSH_GATE_SCRATCH || join(APP, '.scratch', 'push-gate'));
  25. rmSync(SCRATCH, { recursive: true, force: true });
  26. mkdirSync(join(SCRATCH, 'chrome'), { recursive: true });
  27. process.env.TMPDIR = join(SCRATCH, 'chrome');
  28. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  29. const { launchBrowser } = await import('./cdp.mjs');
  30. const { startIdent } = await import('./identkit.mjs');
  31. const IDENT_DIR = process.env.CALENDAR_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  32. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  33. const J = JSON.stringify;
  34. const pad = (n) => String(n).padStart(2, '0');
  35. const b64 = (b) => Buffer.from(b).toString('base64url');
  36. let failures = 0, passes = 0;
  37. function check(label, ok, detail = '') { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; }
  38. const say = (what) => console.log(`${new Date().toTimeString().slice(0, 8)} ${what}`);
  39. // the app's VAPID pair
  40. const app = generateKeyPairSync('ec', { namedCurve: 'P-256' });
  41. const jwk = app.privateKey.export({ format: 'jwk' });
  42. const PUB = b64(Buffer.concat([Buffer.from([4]), Buffer.from(jwk.x, 'base64url'), Buffer.from(jwk.y, 'base64url')]));
  43. const PRIV = jwk.d;
  44. // the fake push service: a user agent per subscription (its ECDH key and auth secret), decrypting what arrives
  45. const agents = {};
  46. function newAgent(path) { const ua = createECDH('prime256v1'); ua.generateKeys(); agents[path] = { ua, auth: randomBytes(16) }; return { endpoint: `http://127.0.0.1:${FPORT}${path}`, keys: { p256dh: b64(ua.getPublicKey()), auth: b64(agents[path].auth) } }; }
  47. const received = [];
  48. function decrypt(path, b) {
  49. const { ua, auth } = agents[path]; const uaPub = ua.getPublicKey();
  50. const salt = b.subarray(0, 16); const idlen = b[20]; const asPub = b.subarray(21, 21 + idlen);
  51. const ikm = Buffer.from(hkdfSync('sha256', ua.computeSecret(asPub), auth, Buffer.concat([Buffer.from('WebPush: info\0'), uaPub, asPub]), 32));
  52. const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16));
  53. const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12));
  54. const rec = b.subarray(21 + idlen);
  55. const d = createDecipheriv('aes-128-gcm', cek, nonce); d.setAuthTag(rec.subarray(rec.length - 16));
  56. const pt = Buffer.concat([d.update(rec.subarray(0, rec.length - 16)), d.final()]);
  57. return pt.subarray(0, pt.lastIndexOf(2)).toString('utf8');
  58. }
  59. const fake = httpServer((q, r) => {
  60. const c = []; q.on('data', d => c.push(d));
  61. q.on('end', () => {
  62. const body = Buffer.concat(c); let plain = null, err = null;
  63. try { plain = decrypt(q.url, body); } catch (e) { err = String(e.message); }
  64. received.push({ at: Date.now(), url: q.url, headers: q.headers, plain, err });
  65. r.statusCode = q.url.startsWith('/gone') ? 410 : 201; r.end('');
  66. });
  67. });
  68. const ANDROID_UA = 'Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Mobile Safari/537.36';
  69. let ident = null, server = null, log = '', APPKEY = null, browser = null;
  70. async function stopAll() {
  71. if (browser) { try { await browser.close(); } catch {} browser = null; }
  72. if (ident) { try { await ident.stop(); } catch {} ident = null; }
  73. try { fake.close(); } catch {}
  74. if (server) { try { server.kill('SIGTERM'); } catch {} await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); }); server = null; }
  75. }
  76. const shot = async (page, name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `${name}.png`), Buffer.from(data, 'base64')); };
  77. async function tap(page, sel) {
  78. const at = await page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return null; e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(); return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }; })()`);
  79. if (!at) throw new Error('tap: no ' + sel);
  80. await page.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: at.x, y: at.y }] });
  81. await page.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
  82. }
  83. // the notification controls live in the reminder settings (C13): user menu → "Reminder settings" (a real tap each), the dialog open
  84. async function openSettings(page) {
  85. if (await page.evaluate(`document.querySelector('#settingseditor').matches(':popover-open')`)) return;
  86. await tap(page, '#settings-open');
  87. await page.waitFor(`document.querySelector('#settingseditor').matches(':popover-open')`, { timeout: 30000, label: 'reminder settings open' }).catch(async (e) => { console.log('---- page console\n' + page.dumpConsole().slice(-1500)); throw e; });
  88. await sleep(300);
  89. }
  90. const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 120000, label: 'hydrated' });
  91. // a signed-in phone of `who`; `sub` is what the (replaced) browser subscribe answers
  92. async function phone(who, sub) {
  93. browser = await launchBrowser({ debugPortRange: [CPORT, CPORT] });
  94. const page = await browser.newPage();
  95. await page.addInitScript(`(() => { const want = ${J({ endpoint: sub.endpoint, expirationTime: null, keys: sub.keys })}; let held = JSON.parse(sessionStorage.getItem('__held') || 'null');
  96. const mk = () => ({ endpoint: want.endpoint, toJSON: () => want, unsubscribe: () => { sessionStorage.setItem('__held', 'null'); held = null; window.__unsub = (window.__unsub || 0) + 1; return Promise.resolve(true); } });
  97. PushManager.prototype.subscribe = function (o) { window.__subKey = String(o.applicationServerKey) + '|' + o.userVisibleOnly; sessionStorage.setItem('__held', '1'); held = 1; return Promise.resolve(mk()); };
  98. PushManager.prototype.getSubscription = function () { return Promise.resolve(held ? mk() : null); }; })();`);
  99. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 2, mobile: true });
  100. await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  101. await page.send('Emulation.setUserAgentOverride', { userAgent: ANDROID_UA, platform: 'Linux armv8l' });
  102. const code = await ident.selectorCode(who, APPKEY, BASE);
  103. await page.goto(BASE + '/login/callback?ident_code=' + code, { timeout: 120000 });
  104. await page.waitForSelector('#logout', { timeout: 60000 });
  105. await hydrated(page);
  106. await page.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { label: 'service worker active', timeout: 60000 });
  107. return page;
  108. }
  109. // an event starting `ahead` ms from now (rounded up to a whole minute), own reminder 1 minute before → the reminder's instant
  110. async function addEvent(page, title, ahead) {
  111. const zone = await page.evaluate('Intl.DateTimeFormat().resolvedOptions().timeZone');
  112. const now = Date.now();
  113. const start = new Date(Math.ceil((now + ahead) / 60000) * 60000);
  114. const dateOf = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
  115. const cookie = (await page.cookies([BASE])).map(c => c.name + '=' + c.value).join('; ');
  116. const fields = { title, allDay: false, startDate: dateOf(start), startTime: `${pad(start.getHours())}:${pad(start.getMinutes())}`, endDate: '', endTime: '', place: '', notes: '', zone, custom: true, reminders: [{ unit: 'minutes', n: '1', time: '09:00' }] };
  117. const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie }, body: J({ t: 'emit', i: 1, event: 'calSave', payload: [fields, dateOf(new Date(now - 259200000)), dateOf(new Date(now + 777600000))] }) });
  118. const j = JSON.parse(await r.text());
  119. if (!j.value || j.value.error) throw new Error('calSave: ' + r.status + ' ' + J(j));
  120. return start.getTime() - 60000;
  121. }
  122. const until = async (t) => { const w = t - Date.now(); if (w > 0) await sleep(w); };
  123. // which notification controls the page shows (C13): ONE consistent state — "Turn on" only while not subscribed, test + off only while subscribed
  124. const vis = (page) => page.evaluate(`(() => { const v = (id) => { const e = document.querySelector(id); return !!e && !e.classList.contains('hidden') && e.getBoundingClientRect().height > 0; }; return { ask: v('#notify-ask'), test: v('#push-test'), off: v('#push-off'), blocked: v('#notify-blocked') }; })()`);
  125. const oneState = (x) => (x.ask && !x.test && !x.off) || (!x.ask && x.test && x.off) || (!x.ask && !x.test && !x.off);
  126. const pushText = (page) => page.evaluate(`(document.querySelector('#push-state') || {}).textContent || ''`);
  127. async function main() {
  128. mkdirSync(join(SCRATCH, 'store', 'sessions'), { recursive: true });
  129. await new Promise(res => fake.listen(FPORT, '127.0.0.1', res));
  130. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(SCRATCH, 'store', 'ident'), port: PORT + 1 });
  131. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]');
  132. APPKEY = await ident.registerApp(alice, 'calendar (push gate)', [BASE]);
  133. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, env: { ...process.env, CALENDAR_PORT: String(PORT), HL_HOST: '127.0.0.1', CALENDAR_SESSIONS: join(SCRATCH, 'store', 'sessions') + '/',
  134. CALENDAR_STORAGE: join(SCRATCH, 'store', 'mpackdb'), CALENDAR_WATCH: '0', CALENDAR_PUBLIC_URL: BASE, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base,
  135. IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret, CALENDAR_PUSH_PUBLIC: PUB, CALENDAR_PUSH_PRIVATE: PRIV, CALENDAR_PUSH_SUBJECT: 'mailto:[email protected]',
  136. CALENDAR_PUSH_EVERY: '0.5', CALENDAR_PUSH_ALLOW_HTTP: '1' }, stdio: ['ignore', 'pipe', 'pipe'] });
  137. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  138. for (let i = 0; ; i++) { try { if ((await fetch(BASE + '/')).ok) break; } catch {} if (i > 600) throw new Error('server did not come up\n' + log); await sleep(250); }
  139. say('app up');
  140. if (process.env.PUSH_GATE_ONLY5) { await first(alice, bob); return; }
  141. let page, text = '';
  142. if (!process.env.PUSH_GATE_ONLY3 && !process.env.PUSH_GATE_ONLY4) {
  143. // ---- 1 ok: subscribed by a real tap, browser closed, the push arrives with the title ----
  144. const sub1 = newAgent('/ok/dev1');
  145. page = await phone(alice, sub1);
  146. await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(() => {});
  147. await tap(page, '#month-title'); await sleep(800);
  148. await shot(page, 'ok-1-before-tap');
  149. await openSettings(page);
  150. const askShown = await page.evaluate(`!document.querySelector('#notify-ask').classList.contains('hidden')`);
  151. say('button offered: ' + askShown + ' (permission ' + await page.evaluate('Notification.permission') + ')');
  152. if (askShown) await tap(page, '#notify-ask');
  153. text = '';
  154. for (let i = 0; i < 40 && !/closed/.test(text); i++) { await sleep(500); text = await pushText(page); }
  155. await shot(page, 'ok-2-subscribed');
  156. if (!/closed/.test(text)) console.log('---- page console\n' + page.dumpConsole().slice(-1500));
  157. check('1 the tap subscribes: the page says reminders also reach it when the calendar is closed', /also reach this device when the calendar is closed/.test(text), J(text));
  158. const v1 = await vis(page);
  159. check('1 subscribed: "Turn on" is hidden, test + off are shown (one state)', !v1.ask && v1.test && v1.off, J(v1));
  160. check('1 subscribe got the app\'s VAPID key and userVisibleOnly', (await page.evaluate('window.__subKey')) === PUB + '|true', await page.evaluate('window.__subKey'));
  161. if (process.env.PUSH_GATE_STOP1 && !/closed/.test(text)) return;
  162. const at1 = await addEvent(page, 'Zahnarzt Push', 150000);
  163. say('reminder at ' + new Date(at1).toTimeString().slice(0, 8) + '; closing the browser');
  164. await browser.close(); browser = null; // the phone's browser is gone: only the server can reach the device now
  165. await until(at1 + 20000);
  166. const got1 = received.filter(x => x.url === '/ok/dev1');
  167. say('fake push service got: ' + J(got1.map(x => ({ late: Math.round((x.at - at1) / 1000), plain: x.plain }))));
  168. check('1 the reminder was pushed to the closed device, once', got1.length === 1, J(got1.map(x => x.plain)));
  169. const p1 = got1[0] && got1[0].plain ? JSON.parse(got1[0].plain) : {};
  170. check('1 the payload (decrypted like a user agent) is the event title and "Starts in 1 minute"', p1.title === 'Zahnarzt Push' && p1.body === 'Starts in 1 minute' && /^[\w-]+:\d+$/.test(p1.tag || ''), J(p1));
  171. check('1 it came at the reminder time (within 15 s)', got1[0] && got1[0].at >= at1 - 1000 && got1[0].at - at1 < 15000, got1[0] && (got1[0].at - at1) + ' ms');
  172. const h = got1[0] ? got1[0].headers : {};
  173. const mm = /^vapid t=([\w-]+)\.([\w-]+)\.([\w-]+), k=([\w-]+)$/.exec(h.authorization || '');
  174. check('1 VAPID: k is the app\'s public key and the JWT verifies; aes128gcm', !!mm && mm[4] === PUB && verify('sha256', Buffer.from(mm[1] + '.' + mm[2]), { key: app.publicKey, dsaEncoding: 'ieee-p1363' }, Buffer.from(mm[3], 'base64url')) && h['content-encoding'] === 'aes128gcm', J(h));
  175. await sleep(4000);
  176. check('1 nothing is sent twice for the same reminder', received.filter(x => x.url === '/ok/dev1').length === 1, String(received.length));
  177. // ---- 2 gone: the service answers 410 → the subscription is dropped (no second push for the next reminder) ----
  178. const sub2 = newAgent('/gone/dev2');
  179. page = await phone(bob, sub2);
  180. await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(() => {});
  181. await tap(page, '#month-title'); await sleep(800);
  182. await openSettings(page);
  183. await tap(page, '#notify-ask');
  184. text = ''; for (let i = 0; i < 40 && !/closed/.test(text); i++) { await sleep(500); text = await pushText(page); }
  185. const a = await addEvent(page, 'Gone one', 150000);
  186. const b = await addEvent(page, 'Gone two', 150000 + 70000);
  187. await browser.close(); browser = null;
  188. await until(b + 20000);
  189. const got2 = received.filter(x => x.url === '/gone/dev2');
  190. say('gone device saw: ' + J(got2.map(x => x.plain)));
  191. check('2 the first reminder went to the dead subscription (410)', got2.length >= 1 && JSON.parse(got2[0].plain).title === 'Gone one', J(got2.map(x => x.plain)));
  192. check('2 after the 410 the subscription is dropped: the next reminder is not sent to it', got2.length === 1, J(got2.map(x => x.plain)));
  193. }
  194. // ---- 3 shown again + off: a device that already allowed notifications is subscribed when the app is shown again (no tap); "Turn off on this device"
  195. // unsubscribes it and the server drops it: the reminder is not pushed to it, and a reload does not subscribe it again ----
  196. if (!process.env.PUSH_GATE_ONLY4) {
  197. if (process.env.PUSH_GATE_ONLY3) received.push({ url: '/ok/dev1', plain: 'Off device' });
  198. const sub3 = newAgent('/ok/dev3');
  199. page = await phone(alice, sub3);
  200. await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(() => {});
  201. await page.goto(BASE + '/', { timeout: 120000 }); await hydrated(page); // permission is there before the page loads: no touch at all
  202. await sleep(3000);
  203. // the first `pageshow` comes before the page's components are hydrated (measured: no subscription at load, Hybriel's `on client shown`
  204. // only hears later shows); a tab shown again (visibilitychange → visible) subscribes without any touch
  205. const atLoad = await pushText(page);
  206. await page.evaluate(`document.dispatchEvent(new Event('visibilitychange'))`);
  207. text = ''; for (let i = 0; i < 40 && !/closed/.test(text); i++) { await sleep(500); text = await pushText(page); }
  208. check('3 permission already given: the app shown again subscribes the device without any touch (not yet at first load: "' + atLoad + '")', /also reach this device when the calendar is closed/.test(text), J(text));
  209. await openSettings(page);
  210. await shot(page, 'off-1-on');
  211. const offVisible = await page.evaluate(`(() => { const e = document.querySelector('#push-off'); if (!e || e.classList.contains('hidden')) return null; const r = e.getBoundingClientRect(); return { h: r.height, w: r.width, text: e.textContent }; })()`);
  212. check('3 "Turn off on this device" is shown next to the on-state text, a 44 px tap', !!offVisible && offVisible.h >= 44 && /Turn off on this device/.test(offVisible.text), J(offVisible));
  213. await tap(page, '#push-off'); await sleep(2500);
  214. await shot(page, 'off-2-off');
  215. const unsubs = await page.evaluate('window.__unsub || 0'); text = await pushText(page);
  216. check('3 the tap unsubscribes the browser and the page says reminders show only while open', unsubs === 1 && /while the calendar is open/.test(text), unsubs + ' ' + J(text));
  217. const v3 = await vis(page);
  218. check('3 the control is gone and "Turn on notifications" is offered again (and only it)', v3.ask && !v3.test && !v3.off, J(v3));
  219. // "Turn on" after "off" (the state on caramboleyo's phone showed Turn on + test + off together: the state was read before the off choice was undone)
  220. await tap(page, '#notify-ask');
  221. const seenStates = []; text = '';
  222. for (let i = 0; i < 60 && !/closed/.test(text); i++) { await sleep(150); text = await pushText(page); seenStates.push(await vis(page)); }
  223. check('3 "Turn on" after "off": subscribed again, at no moment two states at once', /closed/.test(text) && seenStates.every(oneState), J(seenStates.filter(x => !oneState(x))));
  224. const v3b = await vis(page);
  225. check('3 after "Turn on" the button is gone and test + off are back', !v3b.ask && v3b.test && v3b.off, J(v3b));
  226. await tap(page, '#push-off'); await sleep(2000);
  227. await page.goto(BASE + '/', { timeout: 120000 }); await hydrated(page); await sleep(6000);
  228. check('3 a reload does not subscribe the device again', !/closed/.test(await pushText(page)) && (await page.evaluate('window.__subKey')) == null, J(await pushText(page)));
  229. const c = await addEvent(page, 'Off device', 150000);
  230. await browser.close(); browser = null;
  231. await until(c + 20000);
  232. const got3 = received.filter(x => x.url === '/ok/dev3');
  233. check('3 after "off" no push reaches that device (its server row is gone)', got3.length === 0, J(got3.map(x => x.plain)));
  234. check('3 the same reminder still reached the owner\'s other device', received.some(x => x.url === '/ok/dev1' && /Off device/.test(x.plain || '')), J(received.map(x => x.url)));
  235. }
  236. // ---- 4 test notification (calendar#12): "Send a test notification" on a subscribed device → ONE push to that device only, ~10 s later,
  237. // with the calendar closed: title "Calendar test", body "Push works on this device" ----
  238. const sub4 = newAgent('/ok/dev4'), sub1 = { endpoint: `http://127.0.0.1:${FPORT}/ok/dev1` };
  239. page = await phone(bob, sub4);
  240. await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(() => {});
  241. await tap(page, '#month-title'); await sleep(800);
  242. await openSettings(page);
  243. if (await page.evaluate(`!document.querySelector('#notify-ask').classList.contains('hidden')`)) await tap(page, '#notify-ask'); // a device that allowed notifications before is subscribed by the first touch already
  244. text = ''; for (let i = 0; i < 40 && !/closed/.test(text); i++) { await sleep(500); text = await pushText(page); }
  245. const testBtn = await page.evaluate(`(() => { const e = document.querySelector('#push-test'); if (!e || e.classList.contains('hidden')) return null; const r = e.getBoundingClientRect(); return { h: r.height, text: e.textContent }; })()`);
  246. await shot(page, 'test-1-button');
  247. check('4 a subscribed device offers "Send a test notification" (44 px tap)', !!testBtn && testBtn.h >= 44 && /Send a test notification/.test(testBtn.text), J(testBtn));
  248. const before4 = received.filter(x => x.url === '/ok/dev4').length;
  249. await tap(page, '#push-test'); const t4 = Date.now();
  250. text = ''; for (let i = 0; i < 20 && !/on its way/.test(text); i++) { await sleep(500); text = await pushText(page); }
  251. await shot(page, 'test-2-sent');
  252. check('4 the page says the test is on its way', /on its way/.test(text), J(text));
  253. await sleep(1500);
  254. check('4 not at once: the phone has time to leave the app (nothing yet after 1.5 s)', received.filter(x => x.url === '/ok/dev4').length === before4);
  255. // abuse: a second tap within 30 s is refused (rate limit per device); bob cannot test alice's device (/ok/dev1) — owner only
  256. await tap(page, '#push-test'); await sleep(1500); text = await pushText(page);
  257. check('4 a second test within 30 s is refused ("wait 30 seconds")', /wait 30 seconds/.test(text), J(text));
  258. const cookie4 = (await page.cookies([BASE])).map(c => c.name + '=' + c.value).join('; ');
  259. const emitTest = async (ep, i) => JSON.parse(await (await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie: cookie4 }, body: J({ t: 'emit', i, event: 'calPushTest', payload: [ep] }) })).text());
  260. const foreign = await emitTest(sub1.endpoint, 7), none = await emitTest('https://example.org/x', 8);
  261. check('4 a test for a device that is not the signed-in user\'s is refused', !!foreign.value && !!foreign.value.error && !!none.value && !!none.value.error, J([foreign, none]));
  262. await browser.close(); browser = null;
  263. await until(t4 + 25000);
  264. const got4 = received.filter(x => x.url === '/ok/dev4').slice(before4);
  265. const p4 = got4[0] && got4[0].plain ? JSON.parse(got4[0].plain) : {};
  266. check('4 ONE test push reached the closed device, 8-20 s after the tap, with title "Calendar test" and body "Push works on this device"', got4.length === 1 && p4.title === 'Calendar test' && p4.body === 'Push works on this device' && got4[0].at - t4 > 8000 && got4[0].at - t4 < 20000, J(got4.map(x => [x.at - t4, x.plain])));
  267. await first(alice, bob);
  268. check('4 no other device got a test (alice\'s dev1 neither)', !received.some(x => x.at >= t4 && x.url !== '/ok/dev4' && /Calendar test/.test(x.plain || '')), J(received.filter(x => x.at >= t4).map(x => x.url)));
  269. }
  270. // ---- 5 FIRST LOOK on a touch phone (C13, caramboleyo's phone): the page is opened and NOT touched (no grid, no month header); straight to the menu, then the
  271. // reminder settings: the notification state must be right at once. No permission yet → only "Turn on"; permission given → subscribed by opening
  272. // the settings (the menu is outside the month view, no pointer event of the month view came) and never "Turn on" + test + off together ----
  273. async function first(alice, bob) {
  274. let page, text = "";
  275. const subA = newAgent('/ok/dev5');
  276. page = await phone(alice, subA); // permission NOT granted: "default"
  277. await page.goto(BASE + '/', { timeout: 120000 }); await hydrated(page); await sleep(1500);
  278. await openSettings(page);
  279. const vA = await vis(page); const tA = await pushText(page);
  280. await shot(page, 'first-1-default');
  281. check('5 first look, no permission yet, nothing touched before: only "Turn on notifications" (no test, no off, no blocked hint)', vA.ask && !vA.test && !vA.off && !vA.blocked && !!tA, J([vA, tA]));
  282. await browser.close(); browser = null;
  283. const subB = newAgent('/ok/dev6');
  284. page = await phone(bob, subB);
  285. await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(() => {});
  286. await page.goto(BASE + '/', { timeout: 120000 }); await hydrated(page); await sleep(1500);
  287. await openSettings(page);
  288. const states = []; text = '';
  289. for (let i = 0; i < 100 && !/closed/.test(text); i++) { text = await pushText(page); states.push(await vis(page)); await sleep(150); }
  290. await shot(page, 'first-2-granted');
  291. check('5 first look, permission given, nothing touched before: opening the settings subscribes the device (no grid touch needed)', /also reach this device when the calendar is closed/.test(text), J(text));
  292. check('5 never "Turn on" together with test / off while it loads', states.every(oneState), J(states.filter(x => !oneState(x))));
  293. const vB = await vis(page);
  294. check('5 settled: "Turn on" hidden, test + off shown', !vB.ask && vB.test && vB.off && !vB.blocked, J(vB));
  295. }
  296. try { await main(); } catch (e) { check('gate ran', false, String(e && e.stack || e)); }
  297. if (failures) console.log('---- server log (tail)\n' + log.slice(-2500));
  298. await stopAll();
  299. console.log(`${passes} passed, ${failures} failed (app ${APP})`);
  300. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • f9b8f918Merge branch 'calendar-vendor-day61' into mainAtlas
  • 66341793|||PR Vendor Hybriel day61Atlas
  • 36fc596bMerge branch 'vendor-day59' into mainAtlas
  • b37cc1da|||PR Vendor Hybriel day59Atlas
  • 05665102Merge branch 'vendor-day56' into mainAtlas
  • 687296fb|||PR Vendor Hybriel day56Atlas
  • a6166d4eMerge branch 'hl-standard-3' into mainAtlas
  • 6d0eb3b0|||PR Calendar day add buttons only when signed in (Kunibert minor)Atlas
  • add4b499|||PR Make calendar day actions keyboard accessibleAtlas
  • 79e49b4dMerge branch 'hl-standard' into mainAtlas
  • e9fec7bb|||PR HL-STANDARD clean-up: typed parameters, plain locals, by-reference cacheAtlas
  • eff166a4Re-vendor complete Hybriel plugins and runtime to day44mre
  • cef81394Wait for the DST fixture page instead of an unused socketmre
  • 42434f47Check lazy-session cookies after login with a stored anonymous fixturemre
  • 728e84e3Re-vendor complete Hybriel day41 plugin directoriesmre
  • cbd7ff43Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
  • 59d1da0acalendar: plain declarations instead of needless let in 9 files (calendar#17): 49 declarations that are never reassigned; reassigned ones and the timer closure's p stay letmre
  • f5415cf9calendar: the Style blocks in the language's nested form (calendar#16): rules named after the View's own elements with their children nested, pseudo-classes and @media nested, merged duplicate select rule; same CSS, shots identical in Chrome at 4 sizesmre
  • edb7c947calendar: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 56+4 failing → 60 passedmre
  • bf8cc0fcStyles move into their components: the shell's styles into main.hl, the events and the editors into the month view's Style block; styles.hl keeps only the theme inherit, the accent and the message line; .gitignore ignores a bin symlink too; tests/styles-shots.mjs for the before/after pixel comparemre