calendar
All repositories: gitoria
14.7 KB
// tests/push-twice.mjs — P1: ONE reminder must not show TWICE on a phone. The server pushes it (shown by the service worker); the// person taps or swipes that notification away, opens the calendar: the page must not show the SAME reminder again as "missed"// (it did: the page only knew its own localStorage, not that the server had pushed it).// node tests/push-twice.mjs [app dir] env: PUSH_TWICE_PORT (app, ident +1, fake push service +2, Chrome +4), PUSH_TWICE_SCRATCH// A real headless Chrome as a 390 px phone (fake push service as in tests/push.mjs). 1 the closed device gets ONE push 2 the browser// (same localStorage) is opened again after the reminder time, before the event starts: the page shows NOTHING of that event.// 3 control: a second device WITHOUT push (no subscription) still gets its late reminder from the page (the net stays).import { 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_TWICE_PORT || 8700);const FPORT = PORT + 2, CPORT = PORT + 4;const BASE = `http://127.0.0.1:${PORT}`;const SCRATCH = resolve(process.env.PUSH_TWICE_SCRATCH || join(APP, '.scratch', 'push-twice'));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; const browsers = [];async function stopAll() {for (const b of browsers) { try { await b.close(); } catch {} }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; 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) }; })()`);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: [] });}// the notification controls live in the reminder settings (C13): user menu → "Reminder settings" (a real tap each), the dialog openasync function openSettings(page) {if (await page.evaluate(`document.querySelector('#settingseditor').matches(':popover-open')`)) return;await tap(page, '#settings-open');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; });await sleep(300);}const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 120000, label: 'hydrated' });// 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); };// which notification controls the page shows (C13): ONE consistent state — "Turn on" only while not subscribed, test + off only while subscribedconst 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') }; })()`);const oneState = (x) => (x.ask && !x.test && !x.off) || (!x.ask && x.test && x.off) || (!x.ask && !x.test && !x.off);const pushText = (page) => page.evaluate(`(document.querySelector('#push-state') || {}).textContent || ''`);// a tab of the phone's browser `b` (the browser stays when the tab closes: localStorage and the worker survive, like on a phone)async function phone2(who, sub, b) {const page = await b.newPage();await page.addInitScript(`(() => { window.__shown = []; const o = ServiceWorkerRegistration.prototype.showNotification;ServiceWorkerRegistration.prototype.showNotification = function (t, x) { window.__shown.push({ title: t, body: x && x.body, tag: x && x.tag, at: Date.now() }); return o.call(this, t, x); };${sub ? `const want = ${J({ endpoint: sub.endpoint, expirationTime: null, keys: sub.keys })}; let held = localStorage.getItem('__held') === '1';const mk = () => ({ endpoint: want.endpoint, toJSON: () => want, unsubscribe: () => { localStorage.setItem('__held', '0'); held = false; return Promise.resolve(true); } });PushManager.prototype.subscribe = function (o) { localStorage.setItem('__held', '1'); held = true; return Promise.resolve(mk()); };PushManager.prototype.getSubscription = function () { return Promise.resolve(held ? mk() : null); };` : ''} })();`);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' });await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(() => {});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;}const shownNow = (page) => page.evaluate('window.__shown');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 twice 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 alice: subscribed by a real tap, event 150 s ahead, reminder 1 min before; the browser is closed ----const brA = await launchBrowser({ debugPortRange: [CPORT, CPORT] }); browsers.push(brA);const subA = newAgent('/ok/devA');let page = await phone2(alice, subA, brA);await tap(page, '#month-title'); await sleep(800);await openSettings(page);if (await page.evaluate(`!document.querySelector('#notify-ask').classList.contains('hidden')`)) await tap(page, '#notify-ask');let text = ''; for (let i = 0; i < 40 && !/closed/.test(text); i++) { await sleep(500); text = await pushText(page); }check('1 subscribed (the page says reminders also reach it when closed)', /closed/.test(text), J(text));const at = await addEvent(page, 'Twice check', 150000);say('reminder at ' + new Date(at).toTimeString().slice(0, 8) + '; closing the tab (the browser stays)');await page.close(); brA.pages = brA.pages.filter(p => p !== page);await until(at + 15000);const got = received.filter(x => x.url === '/ok/devA');check('1 the server pushed the reminder to the closed device, once', got.length === 1 && /Twice check/.test(got[0].plain || ''), J(got.map(x => x.plain)));// ---- 2 the phone is opened again (same profile) after the push, before the event starts ----page = await phone2(alice, subA, brA);await page.goto(BASE + '/', { timeout: 120000 }); await hydrated(page);await tap(page, '#month-title'); await sleep(6000);const shown = (await shownNow(page)).filter(n => n.title === 'Twice check');say('page showed: ' + J(shown));check('2 the page does NOT show the reminder the server already pushed (shown twice before P1)', shown.length === 0, J(shown));await page.close(); brA.pages = brA.pages.filter(p => p !== page);check('2 still one push in total', received.filter(x => x.url === '/ok/devA').length === 1, String(received.length));// ---- 3 control: bob has NO push subscription: his page still shows the missed reminder (the net stays) ----const brB = await launchBrowser({ debugPortRange: [CPORT + 1, CPORT + 1] }); browsers.push(brB);page = await phone2(bob, null, brB);await tap(page, '#month-title'); await sleep(800);const atB = await addEvent(page, 'Bob net', 150000);await page.close(); brB.pages = brB.pages.filter(p => p !== page);await until(atB + 10000);page = await phone2(bob, null, brB);await page.goto(BASE + '/', { timeout: 120000 }); await hydrated(page);await tap(page, '#month-title'); await sleep(6000);const shownB = (await shownNow(page)).filter(n => n.title === 'Bob net');check('3 control: a device without push still gets its missed reminder from the page', shownB.length === 1, J(shownB));}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
- 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