gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit92001e5292001e52sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre92001e52/tests/push-twice.mjs

14.8 KB

  1. // tests/push-twice.mjs — P1: ONE reminder must not show TWICE on a phone. The server pushes it (shown by the service worker); the
  2. // person taps or swipes that notification away, opens the calendar: the page must not show the SAME reminder again as "missed"
  3. // (it did: the page only knew its own localStorage, not that the server had pushed it).
  4. // node tests/push-twice.mjs [app dir] env: PUSH_TWICE_PORT (app, ident +1, fake push service +2, Chrome +4), PUSH_TWICE_SCRATCH
  5. // 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
  6. // (same localStorage) is opened again after the reminder time, before the event starts: the page shows NOTHING of that event.
  7. // 3 control: a second device WITHOUT push (no subscription) still gets its late reminder from the page (the net stays).
  8. import { spawn } from 'node:child_process';
  9. import { writeFileSync, existsSync, mkdirSync, rmSync } from 'node:fs';
  10. import { createServer as httpServer } from 'node:http';
  11. import { generateKeyPairSync, createECDH, hkdfSync, createDecipheriv, randomBytes, verify } from 'node:crypto';
  12. import { dirname, join, resolve } from 'node:path';
  13. import { fileURLToPath } from 'node:url';
  14. const HERE = dirname(fileURLToPath(import.meta.url));
  15. const APP = resolve(process.argv[2] || resolve(HERE, '..'));
  16. const PORT = Number(process.env.PUSH_TWICE_PORT || 8700);
  17. const FPORT = PORT + 2, CPORT = PORT + 4;
  18. const BASE = `http://127.0.0.1:${PORT}`;
  19. const SCRATCH = resolve(process.env.PUSH_TWICE_SCRATCH || join(APP, '.scratch', 'push-twice'));
  20. rmSync(SCRATCH, { recursive: true, force: true });
  21. mkdirSync(join(SCRATCH, 'chrome'), { recursive: true });
  22. process.env.TMPDIR = join(SCRATCH, 'chrome');
  23. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  24. const { launchBrowser } = await import('./cdp.mjs');
  25. const { startIdent } = await import('./identkit.mjs');
  26. 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')));
  27. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  28. const J = JSON.stringify;
  29. const pad = (n) => String(n).padStart(2, '0');
  30. const b64 = (b) => Buffer.from(b).toString('base64url');
  31. let failures = 0, passes = 0;
  32. function check(label, ok, detail = '') { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; }
  33. const say = (what) => console.log(`${new Date().toTimeString().slice(0, 8)} ${what}`);
  34. // the app's VAPID pair
  35. const app = generateKeyPairSync('ec', { namedCurve: 'P-256' });
  36. const jwk = app.privateKey.export({ format: 'jwk' });
  37. const PUB = b64(Buffer.concat([Buffer.from([4]), Buffer.from(jwk.x, 'base64url'), Buffer.from(jwk.y, 'base64url')]));
  38. const PRIV = jwk.d;
  39. // the fake push service: a user agent per subscription (its ECDH key and auth secret), decrypting what arrives
  40. const agents = {};
  41. 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) } }; }
  42. const received = [];
  43. function decrypt(path, b) {
  44. const { ua, auth } = agents[path]; const uaPub = ua.getPublicKey();
  45. const salt = b.subarray(0, 16); const idlen = b[20]; const asPub = b.subarray(21, 21 + idlen);
  46. const ikm = Buffer.from(hkdfSync('sha256', ua.computeSecret(asPub), auth, Buffer.concat([Buffer.from('WebPush: info\0'), uaPub, asPub]), 32));
  47. const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16));
  48. const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12));
  49. const rec = b.subarray(21 + idlen);
  50. const d = createDecipheriv('aes-128-gcm', cek, nonce); d.setAuthTag(rec.subarray(rec.length - 16));
  51. const pt = Buffer.concat([d.update(rec.subarray(0, rec.length - 16)), d.final()]);
  52. return pt.subarray(0, pt.lastIndexOf(2)).toString('utf8');
  53. }
  54. const fake = httpServer((q, r) => {
  55. const c = []; q.on('data', d => c.push(d));
  56. q.on('end', () => {
  57. const body = Buffer.concat(c); let plain = null, err = null;
  58. try { plain = decrypt(q.url, body); } catch (e) { err = String(e.message); }
  59. received.push({ at: Date.now(), url: q.url, headers: q.headers, plain, err });
  60. r.statusCode = q.url.startsWith('/gone') ? 410 : 201; r.end('');
  61. });
  62. });
  63. 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';
  64. let ident = null, server = null, log = '', APPKEY = null; const browsers = [];
  65. async function stopAll() {
  66. for (const b of browsers) { try { await b.close(); } catch {} }
  67. if (ident) { try { await ident.stop(); } catch {} ident = null; }
  68. try { fake.close(); } catch {}
  69. 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; }
  70. }
  71. const shot = async (page, name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `${name}.png`), Buffer.from(data, 'base64')); };
  72. async function tap(page, sel) {
  73. 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) }; })()`);
  74. if (!at) throw new Error('tap: no ' + sel);
  75. await page.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: at.x, y: at.y }] });
  76. await page.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
  77. }
  78. // the notification controls live in the reminder settings (C13): user menu → "Reminder settings" (a real tap each), the dialog open
  79. async function openSettings(page) {
  80. if (await page.evaluate(`document.querySelector('#settingseditor').matches(':popover-open')`)) return;
  81. await tap(page, '.user-toggle'); await sleep(400);
  82. await tap(page, '#settings-open');
  83. 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) + '\nmenu open: ' + await page.evaluate(`document.querySelector('#user-menu').matches(':popover-open')`)); throw e; });
  84. await sleep(300);
  85. }
  86. const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 120000, label: 'hydrated' });
  87. // an event starting `ahead` ms from now (rounded up to a whole minute), own reminder 1 minute before → the reminder's instant
  88. async function addEvent(page, title, ahead) {
  89. const zone = await page.evaluate('Intl.DateTimeFormat().resolvedOptions().timeZone');
  90. const now = Date.now();
  91. const start = new Date(Math.ceil((now + ahead) / 60000) * 60000);
  92. const dateOf = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
  93. const cookie = (await page.cookies([BASE])).map(c => c.name + '=' + c.value).join('; ');
  94. 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' }] };
  95. 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))] }) });
  96. const j = JSON.parse(await r.text());
  97. if (!j.value || j.value.error) throw new Error('calSave: ' + r.status + ' ' + J(j));
  98. return start.getTime() - 60000;
  99. }
  100. const until = async (t) => { const w = t - Date.now(); if (w > 0) await sleep(w); };
  101. // which notification controls the page shows (C13): ONE consistent state — "Turn on" only while not subscribed, test + off only while subscribed
  102. 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') }; })()`);
  103. const oneState = (x) => (x.ask && !x.test && !x.off) || (!x.ask && x.test && x.off) || (!x.ask && !x.test && !x.off);
  104. const pushText = (page) => page.evaluate(`(document.querySelector('#push-state') || {}).textContent || ''`);
  105. // a tab of the phone's browser `b` (the browser stays when the tab closes: localStorage and the worker survive, like on a phone)
  106. async function phone2(who, sub, b) {
  107. const page = await b.newPage();
  108. await page.addInitScript(`(() => { window.__shown = []; const o = ServiceWorkerRegistration.prototype.showNotification;
  109. 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); };
  110. ${sub ? `const want = ${J({ endpoint: sub.endpoint, expirationTime: null, keys: sub.keys })}; let held = localStorage.getItem('__held') === '1';
  111. const mk = () => ({ endpoint: want.endpoint, toJSON: () => want, unsubscribe: () => { localStorage.setItem('__held', '0'); held = false; return Promise.resolve(true); } });
  112. PushManager.prototype.subscribe = function (o) { localStorage.setItem('__held', '1'); held = true; return Promise.resolve(mk()); };
  113. PushManager.prototype.getSubscription = function () { return Promise.resolve(held ? mk() : null); };` : ''} })();`);
  114. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 2, mobile: true });
  115. await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  116. await page.send('Emulation.setUserAgentOverride', { userAgent: ANDROID_UA, platform: 'Linux armv8l' });
  117. await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(() => {});
  118. const code = await ident.selectorCode(who, APPKEY, BASE);
  119. await page.goto(BASE + '/login/callback?ident_code=' + code, { timeout: 120000 });
  120. await page.waitForSelector('#logout', { timeout: 60000 });
  121. await hydrated(page);
  122. await page.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { label: 'service worker active', timeout: 60000 });
  123. return page;
  124. }
  125. const shownNow = (page) => page.evaluate('window.__shown');
  126. async function main() {
  127. mkdirSync(join(SCRATCH, 'store', 'sessions'), { recursive: true });
  128. await new Promise(res => fake.listen(FPORT, '127.0.0.1', res));
  129. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(SCRATCH, 'store', 'ident'), port: PORT + 1 });
  130. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]');
  131. APPKEY = await ident.registerApp(alice, 'calendar (push twice gate)', [BASE]);
  132. 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') + '/',
  133. CALENDAR_STORAGE: join(SCRATCH, 'store', 'mpackdb'), CALENDAR_WATCH: '0', CALENDAR_PUBLIC_URL: BASE, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base,
  134. IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret, CALENDAR_PUSH_PUBLIC: PUB, CALENDAR_PUSH_PRIVATE: PRIV, CALENDAR_PUSH_SUBJECT: 'mailto:[email protected]',
  135. CALENDAR_PUSH_EVERY: '0.5', CALENDAR_PUSH_ALLOW_HTTP: '1' }, stdio: ['ignore', 'pipe', 'pipe'] });
  136. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  137. 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); }
  138. say('app up');
  139. // ---- 1 alice: subscribed by a real tap, event 150 s ahead, reminder 1 min before; the browser is closed ----
  140. const brA = await launchBrowser({ debugPortRange: [CPORT, CPORT] }); browsers.push(brA);
  141. const subA = newAgent('/ok/devA');
  142. let page = await phone2(alice, subA, brA);
  143. await tap(page, '#month-title'); await sleep(800);
  144. await openSettings(page);
  145. if (await page.evaluate(`!document.querySelector('#notify-ask').classList.contains('hidden')`)) await tap(page, '#notify-ask');
  146. let text = ''; for (let i = 0; i < 40 && !/closed/.test(text); i++) { await sleep(500); text = await pushText(page); }
  147. check('1 subscribed (the page says reminders also reach it when closed)', /closed/.test(text), J(text));
  148. const at = await addEvent(page, 'Twice check', 150000);
  149. say('reminder at ' + new Date(at).toTimeString().slice(0, 8) + '; closing the tab (the browser stays)');
  150. await page.close(); brA.pages = brA.pages.filter(p => p !== page);
  151. await until(at + 15000);
  152. const got = received.filter(x => x.url === '/ok/devA');
  153. 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)));
  154. // ---- 2 the phone is opened again (same profile) after the push, before the event starts ----
  155. page = await phone2(alice, subA, brA);
  156. await page.goto(BASE + '/', { timeout: 120000 }); await hydrated(page);
  157. await tap(page, '#month-title'); await sleep(6000);
  158. const shown = (await shownNow(page)).filter(n => n.title === 'Twice check');
  159. say('page showed: ' + J(shown));
  160. check('2 the page does NOT show the reminder the server already pushed (shown twice before P1)', shown.length === 0, J(shown));
  161. await page.close(); brA.pages = brA.pages.filter(p => p !== page);
  162. check('2 still one push in total', received.filter(x => x.url === '/ok/devA').length === 1, String(received.length));
  163. // ---- 3 control: bob has NO push subscription: his page still shows the missed reminder (the net stays) ----
  164. const brB = await launchBrowser({ debugPortRange: [CPORT + 1, CPORT + 1] }); browsers.push(brB);
  165. page = await phone2(bob, null, brB);
  166. await tap(page, '#month-title'); await sleep(800);
  167. const atB = await addEvent(page, 'Bob net', 150000);
  168. await page.close(); brB.pages = brB.pages.filter(p => p !== page);
  169. await until(atB + 10000);
  170. page = await phone2(bob, null, brB);
  171. await page.goto(BASE + '/', { timeout: 120000 }); await hydrated(page);
  172. await tap(page, '#month-title'); await sleep(6000);
  173. const shownB = (await shownNow(page)).filter(n => n.title === 'Bob net');
  174. check('3 control: a device without push still gets its missed reminder from the page', shownB.length === 1, J(shownB));
  175. }
  176. try { await main(); } catch (e) { check('gate ran', false, String(e && e.stack || e)); }
  177. if (failures) console.log('---- server log (tail)\n' + log.slice(-2500));
  178. await stopAll();
  179. console.log(`${passes} passed, ${failures} failed (app ${APP})`);
  180. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 92001e52sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • 2dd53dccP1: one reminder shows once: arm() one at a time, the page skips reminders the server already pushed; push-twice gatemre
  • 3a29760aC13 report (handoff)mre
  • 33ab66ffCalendar: notification controls move from the month view into Reminder settings (user menu), one consistent state, state read when the dialog opensmre
  • 682a5b43reports: calendar gate countsmre
  • 876d22b2reports/H1-hydrate.mdmre
  • ef0cae45tests/dst.mjs: wait for hydration instead of a fixed 2.5 s sleep before clicking #gomre
  • d9cadecatests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
  • efa61227re-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • 7808adbecalendar#12: report 011, LOG, STATUS, push-shots-testmre
  • df2e4fa0calendar#12: test push rate limit (1 per 30 s per device), owner-only gate checksmre
  • acb957cfcalendar#12: Send a test notification on a subscribed device (one push in ~10 s, owner's own device), push gate part 4mre
  • 0b222eb8tests: e2e-theme CDP port default from E2E_THEME_CDP_PORT (8756 unchanged)mre
  • 8b8a5abare-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • a69b27f9docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 1a97edfdcalendar mission 010: reminder rows at 390 px (the 7-column month grid no longer catches the reminder lists), gate checks, settings-shots, reportmre
  • 61b21404calendar mission 009: reminder times on hl:time in the browser (lib/push-plan.hl and the Intl code removed), DST gate tests/dst.mjs, E2E script, reportmre
  • 875353c1calendar mission 009: re-vendor Hybriel master 022a3ac1 (int 6 6b396322 hl:time browser side, int 7 65e8ec21; bin sha256 6e0f77d7, plugins whole)mre
  • ce16a4efdeploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • f490bc8cdeploy: Web Push gate tests/push.mjs (PUSH_GATE_PORT)mre