calendar
All repositories: gitoria
14.4 KB
// tests/push.mjs — calendar#9 part 2 (mission 008): WEB PUSH, a reminder reaches a device whose calendar is CLOSED.// node tests/push.mjs [app dir] env: PUSH_GATE_PORT (app, default 8700; ident +1; the fake push service +2; Chrome +4),// PUSH_GATE_SCRATCH. A real headless Chrome as a 390 px phone, own ident, own server + storage, VAPID keys made here.// The FAKE PUSH SERVICE is a local http server that decrypts like a user agent (ECDH with the subscription's private key,// RFC 8291; the approach of hybriel tests/core-ast/web-tickets.mjs #173): it answers 201 at /ok/*, 410 at /gone/*.// Headless Chrome cannot reach a real push service, so the browser's `PushManager.subscribe` is replaced by one that answers// the subscription made here (the page's own code — subscribePush, the button, the server emit — is the real one).// 1 ok tap "Turn on notifications" → the page says it is subscribed; the browser is then CLOSED; at the reminder time// the fake service gets ONE encrypted push: VAPID header with the app's key, payload = event title + "Starts in 1 minute"// 2 gone a device whose service answers 410 gets the first push, and none after it (the subscription is dropped)// 3 late a reminder that came due while the device was away is not lost: a second event's reminder is sent once onlyimport { spawn } from 'node:child_process';import { writeFileSync, existsSync, mkdirSync, rmSync } from 'node:fs';import { createServer as httpServer } from 'node:http';import { generateKeyPairSync, createECDH, hkdfSync, createDecipheriv, randomBytes, verify } from 'node:crypto';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(process.argv[2] || resolve(HERE, '..'));const PORT = Number(process.env.PUSH_GATE_PORT || 8700);const FPORT = PORT + 2, CPORT = PORT + 4;const BASE = `http://127.0.0.1:${PORT}`;const SCRATCH = resolve(process.env.PUSH_GATE_SCRATCH || join(APP, '.scratch', 'push-gate'));rmSync(SCRATCH, { recursive: true, force: true });mkdirSync(join(SCRATCH, 'chrome'), { recursive: true });process.env.TMPDIR = join(SCRATCH, 'chrome');if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';const { launchBrowser } = await import('./cdp.mjs');const { startIdent } = await import('./identkit.mjs');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')));const sleep = (ms) => new Promise(r => setTimeout(r, ms));const J = JSON.stringify;const pad = (n) => String(n).padStart(2, '0');const b64 = (b) => Buffer.from(b).toString('base64url');let failures = 0, passes = 0;function check(label, ok, detail = '') { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; }const say = (what) => console.log(`${new Date().toTimeString().slice(0, 8)} ${what}`);// the app's VAPID pairconst app = generateKeyPairSync('ec', { namedCurve: 'P-256' });const jwk = app.privateKey.export({ format: 'jwk' });const PUB = b64(Buffer.concat([Buffer.from([4]), Buffer.from(jwk.x, 'base64url'), Buffer.from(jwk.y, 'base64url')]));const PRIV = jwk.d;// the fake push service: a user agent per subscription (its ECDH key and auth secret), decrypting what arrivesconst agents = {};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) } }; }const received = [];function decrypt(path, b) {const { ua, auth } = agents[path]; const uaPub = ua.getPublicKey();const salt = b.subarray(0, 16); const idlen = b[20]; const asPub = b.subarray(21, 21 + idlen);const ikm = Buffer.from(hkdfSync('sha256', ua.computeSecret(asPub), auth, Buffer.concat([Buffer.from('WebPush: info\0'), uaPub, asPub]), 32));const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16));const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12));const rec = b.subarray(21 + idlen);const d = createDecipheriv('aes-128-gcm', cek, nonce); d.setAuthTag(rec.subarray(rec.length - 16));const pt = Buffer.concat([d.update(rec.subarray(0, rec.length - 16)), d.final()]);return pt.subarray(0, pt.lastIndexOf(2)).toString('utf8');}const fake = httpServer((q, r) => {const c = []; q.on('data', d => c.push(d));q.on('end', () => {const body = Buffer.concat(c); let plain = null, err = null;try { plain = decrypt(q.url, body); } catch (e) { err = String(e.message); }received.push({ at: Date.now(), url: q.url, headers: q.headers, plain, err });r.statusCode = q.url.startsWith('/gone') ? 410 : 201; r.end('');});});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';let ident = null, server = null, log = '', APPKEY = null, browser = null;async function stopAll() {if (browser) { try { await browser.close(); } catch {} browser = null; }if (ident) { try { await ident.stop(); } catch {} ident = null; }try { fake.close(); } catch {}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; }}const shot = async (page, name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `${name}.png`), Buffer.from(data, 'base64')); };async function tap(page, sel) {const at = await page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return null; const r = e.getBoundingClientRect(); return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }; })()`);if (!at) throw new Error('tap: no ' + sel);await page.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: at.x, y: at.y }] });await page.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });}const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 120000, label: 'hydrated' });// a signed-in phone of `who`; `sub` is what the (replaced) browser subscribe answersasync function phone(who, sub) {browser = await launchBrowser({ debugPortRange: [CPORT, CPORT] });const page = await browser.newPage();await page.addInitScript(`PushManager.prototype.subscribe = function (o) { window.__subKey = String(o.applicationServerKey) + '|' + o.userVisibleOnly; return Promise.resolve({ toJSON: () => (${J({ endpoint: sub.endpoint, expirationTime: null, keys: sub.keys })}) }); };`);await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 2, mobile: true });await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });await page.send('Emulation.setUserAgentOverride', { userAgent: ANDROID_UA, platform: 'Linux armv8l' });const code = await ident.selectorCode(who, APPKEY, BASE);await page.goto(BASE + '/login/callback?ident_code=' + code, { timeout: 120000 });await page.waitForSelector('#logout', { timeout: 60000 });await hydrated(page);await page.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { label: 'service worker active', timeout: 60000 });return page;}// an event starting `ahead` ms from now (rounded up to a whole minute), own reminder 1 minute before → the reminder's instantasync function addEvent(page, title, ahead) {const zone = await page.evaluate('Intl.DateTimeFormat().resolvedOptions().timeZone');const now = Date.now();const start = new Date(Math.ceil((now + ahead) / 60000) * 60000);const dateOf = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;const cookie = (await page.cookies([BASE])).map(c => c.name + '=' + c.value).join('; ');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' }] };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))] }) });const j = JSON.parse(await r.text());if (!j.value || j.value.error) throw new Error('calSave: ' + r.status + ' ' + J(j));return start.getTime() - 60000;}const until = async (t) => { const w = t - Date.now(); if (w > 0) await sleep(w); };const pushText = (page) => page.evaluate(`(document.querySelector('#push-state') || {}).textContent || ''`);async function main() {mkdirSync(join(SCRATCH, 'store', 'sessions'), { recursive: true });await new Promise(res => fake.listen(FPORT, '127.0.0.1', res));ident = await startIdent({ identDir: IDENT_DIR, workDir: join(SCRATCH, 'store', 'ident'), port: PORT + 1 });const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]');APPKEY = await ident.registerApp(alice, 'calendar (push gate)', [BASE]);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') + '/',CALENDAR_STORAGE: join(SCRATCH, 'store', 'mpackdb'), CALENDAR_WATCH: '0', CALENDAR_PUBLIC_URL: BASE, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base,IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret, CALENDAR_PUSH_PUBLIC: PUB, CALENDAR_PUSH_PRIVATE: PRIV, CALENDAR_PUSH_SUBJECT: 'mailto:[email protected]',CALENDAR_PUSH_EVERY: '0.5', CALENDAR_PUSH_ALLOW_HTTP: '1' }, stdio: ['ignore', 'pipe', 'pipe'] });server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);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); }say('app up');// ---- 1 ok: subscribed by a real tap, browser closed, the push arrives with the title ----const sub1 = newAgent('/ok/dev1');let page = await phone(alice, sub1);await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(() => {});await tap(page, '#month-title'); await sleep(800);await shot(page, 'ok-1-before-tap');const askShown = await page.evaluate(`!document.querySelector('#notify-ask').classList.contains('hidden')`);say('button offered: ' + askShown + ' (permission ' + await page.evaluate('Notification.permission') + ')');if (askShown) await tap(page, '#notify-ask');let text = '';for (let i = 0; i < 40 && !/closed/.test(text); i++) { await sleep(500); text = await pushText(page); }await shot(page, 'ok-2-subscribed');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));check('1 subscribe got the app\'s VAPID key and userVisibleOnly', (await page.evaluate('window.__subKey')) === PUB + '|true', await page.evaluate('window.__subKey'));const at1 = await addEvent(page, 'Zahnarzt Push', 150000);say('reminder at ' + new Date(at1).toTimeString().slice(0, 8) + '; closing the browser');await browser.close(); browser = null; // the phone's browser is gone: only the server can reach the device nowawait until(at1 + 20000);const got1 = received.filter(x => x.url === '/ok/dev1');say('fake push service got: ' + J(got1.map(x => ({ late: Math.round((x.at - at1) / 1000), plain: x.plain }))));check('1 the reminder was pushed to the closed device, once', got1.length === 1, J(got1.map(x => x.plain)));const p1 = got1[0] && got1[0].plain ? JSON.parse(got1[0].plain) : {};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));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');const h = got1[0] ? got1[0].headers : {};const mm = /^vapid t=([\w-]+)\.([\w-]+)\.([\w-]+), k=([\w-]+)$/.exec(h.authorization || '');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));await sleep(4000);check('1 nothing is sent twice for the same reminder', received.filter(x => x.url === '/ok/dev1').length === 1, String(received.length));// ---- 2 gone: the service answers 410 → the subscription is dropped (no second push for the next reminder) ----const sub2 = newAgent('/gone/dev2');page = await phone(bob, sub2);await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(() => {});await tap(page, '#month-title'); await sleep(800);await tap(page, '#notify-ask');text = ''; for (let i = 0; i < 40 && !/closed/.test(text); i++) { await sleep(500); text = await pushText(page); }const a = await addEvent(page, 'Gone one', 150000);const b = await addEvent(page, 'Gone two', 150000 + 70000);await browser.close(); browser = null;await until(b + 20000);const got2 = received.filter(x => x.url === '/gone/dev2');say('gone device saw: ' + J(got2.map(x => x.plain)));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)));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)));}try { await main(); } catch (e) { check('gate ran', false, String(e && e.stack || e)); }if (failures) console.log('---- server log (tail)\n' + log.slice(-2500));await stopAll();console.log(`${passes} passed, ${failures} failed (app ${APP})`);process.exit(failures ? 1 : 0);
Branches
Latest commits
- d063dad3calendar mission 008 (A7): Web Push (WIP): lib/push.hl subscriptions + sender clock, faces calPushSave/calPushOff, button subscribes, VAPID tool, tests/push.mjs; instantOf on hl:timemre
- cf175c80calendar mission 008 (A7): re-vendor Hybriel master 0e3c9830 (bin 9d957fed, plugins whole: hl:crypto Web Push primitives, hl:web sendPush)mre
- 9bf3c38bcalendar mission 008: re-vendor Hybriel f9833544 (gates old = new); Web Push stopped: hl:crypto half missing on mastermre
- 186f969bcalendar mission 007: signed-in gate for the first-pointer race (fails on 3c5604f), README theme section, reportmre
- ba9b4955calendar mission 006: first pointer event no longer re-runs the month (stale overwrite race), gate check, e2e settings cleanup, reportmre
- bd730759calendar mission 006: theme move (WIP): brief, report, LOG, STATUSmre
- b117b153calendar mission 006 WIP: reminder row fields keep 44 px; e2e script flagsmre
- 53e3b0debrowser gate: Log out through the user menu, theme colour rgb(15, 20, 25)mre
- 90bf9e2ecalendar mission 006 WIP: theme dbe3de7, theme shell (AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst), styles cut to the app's own rules, check-theme gate, e2e toolsmre
- 3c5604f9identkit: refuse a taken ident port, cold-start deadline, abort on dead ident, clear no-code error (as notes)mre
- 4996bbe7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
- f5bf0803calendar mission 004: re-vendor Hybriel to the shared static build 0f396652; compose cache volume + tmpfs; notify-paths gate in deploy.sh; gate start waits 150 s; reportmre
- eb86526fmission brief 004mre
- 2f953b16deploy.sh: wait up to DEPLOY_URL_WAIT (120 s) for 200 after the restart, as the other apps (cold compile, hybriel#148)mre
- 9078e1b7calendar mission 003 (2/2): report, LOG, STATUS (cause: timers only in an open, front, touched page; gate old 5/2 new 7/0; Hybriel gaps Web Push + page-shown hook, STOP)mre
- 31ffe910calendar mission 003 (1/2): calendar#9 — missed reminders shown when the app is back, timers set again when it is shownmre
- 26c997d3mission brief 003mre
- c6809c76calendar mission 002: report, LOG, STATUS (test bug; fixed gate 78/0 at 00:30 05:40 12:00 19:59 20:01; 23:30 not run, quota stop)mre
- 00f72783calendar mission 002 (2/2): TEST bug — the reminder steps get their own identity (carol): alice's all-day Vacation (20th-22nd) from the events steps added 2 reminders from the 12th 20:00 to the 19th 23:00; Tokyo check no longer skipped in the Tokyo eveningmre
- 54fb0ce1calendar mission 002 (1/2): gate clock override GATE_CLOCK=HH:MM (this process and every page get Date shifted to that local time today)mre