gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainf9b8f918Merge branch 'calendar-vendor-day61' into mainAtlasmain/tests/push-twice.mjs

14.7 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, '#settings-open');
  82. 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; });
  83. await sleep(300);
  84. }
  85. const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 120000, label: 'hydrated' });
  86. // an event starting `ahead` ms from now (rounded up to a whole minute), own reminder 1 minute before → the reminder's instant
  87. async function addEvent(page, title, ahead) {
  88. const zone = await page.evaluate('Intl.DateTimeFormat().resolvedOptions().timeZone');
  89. const now = Date.now();
  90. const start = new Date(Math.ceil((now + ahead) / 60000) * 60000);
  91. const dateOf = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
  92. const cookie = (await page.cookies([BASE])).map(c => c.name + '=' + c.value).join('; ');
  93. 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' }] };
  94. 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))] }) });
  95. const j = JSON.parse(await r.text());
  96. if (!j.value || j.value.error) throw new Error('calSave: ' + r.status + ' ' + J(j));
  97. return start.getTime() - 60000;
  98. }
  99. const until = async (t) => { const w = t - Date.now(); if (w > 0) await sleep(w); };
  100. // which notification controls the page shows (C13): ONE consistent state — "Turn on" only while not subscribed, test + off only while subscribed
  101. 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') }; })()`);
  102. const oneState = (x) => (x.ask && !x.test && !x.off) || (!x.ask && x.test && x.off) || (!x.ask && !x.test && !x.off);
  103. const pushText = (page) => page.evaluate(`(document.querySelector('#push-state') || {}).textContent || ''`);
  104. // a tab of the phone's browser `b` (the browser stays when the tab closes: localStorage and the worker survive, like on a phone)
  105. async function phone2(who, sub, b) {
  106. const page = await b.newPage();
  107. await page.addInitScript(`(() => { window.__shown = []; const o = ServiceWorkerRegistration.prototype.showNotification;
  108. 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); };
  109. ${sub ? `const want = ${J({ endpoint: sub.endpoint, expirationTime: null, keys: sub.keys })}; let held = localStorage.getItem('__held') === '1';
  110. const mk = () => ({ endpoint: want.endpoint, toJSON: () => want, unsubscribe: () => { localStorage.setItem('__held', '0'); held = false; return Promise.resolve(true); } });
  111. PushManager.prototype.subscribe = function (o) { localStorage.setItem('__held', '1'); held = true; return Promise.resolve(mk()); };
  112. PushManager.prototype.getSubscription = function () { return Promise.resolve(held ? mk() : null); };` : ''} })();`);
  113. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 2, mobile: true });
  114. await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  115. await page.send('Emulation.setUserAgentOverride', { userAgent: ANDROID_UA, platform: 'Linux armv8l' });
  116. await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(() => {});
  117. const code = await ident.selectorCode(who, APPKEY, BASE);
  118. await page.goto(BASE + '/login/callback?ident_code=' + code, { timeout: 120000 });
  119. await page.waitForSelector('#logout', { timeout: 60000 });
  120. await hydrated(page);
  121. await page.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { label: 'service worker active', timeout: 60000 });
  122. return page;
  123. }
  124. const shownNow = (page) => page.evaluate('window.__shown');
  125. async function main() {
  126. mkdirSync(join(SCRATCH, 'store', 'sessions'), { recursive: true });
  127. await new Promise(res => fake.listen(FPORT, '127.0.0.1', res));
  128. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(SCRATCH, 'store', 'ident'), port: PORT + 1 });
  129. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]');
  130. APPKEY = await ident.registerApp(alice, 'calendar (push twice gate)', [BASE]);
  131. 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') + '/',
  132. CALENDAR_STORAGE: join(SCRATCH, 'store', 'mpackdb'), CALENDAR_WATCH: '0', CALENDAR_PUBLIC_URL: BASE, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base,
  133. IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret, CALENDAR_PUSH_PUBLIC: PUB, CALENDAR_PUSH_PRIVATE: PRIV, CALENDAR_PUSH_SUBJECT: 'mailto:[email protected]',
  134. CALENDAR_PUSH_EVERY: '0.5', CALENDAR_PUSH_ALLOW_HTTP: '1' }, stdio: ['ignore', 'pipe', 'pipe'] });
  135. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  136. 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); }
  137. say('app up');
  138. // ---- 1 alice: subscribed by a real tap, event 150 s ahead, reminder 1 min before; the browser is closed ----
  139. const brA = await launchBrowser({ debugPortRange: [CPORT, CPORT] }); browsers.push(brA);
  140. const subA = newAgent('/ok/devA');
  141. let page = await phone2(alice, subA, brA);
  142. await tap(page, '#month-title'); await sleep(800);
  143. await openSettings(page);
  144. if (await page.evaluate(`!document.querySelector('#notify-ask').classList.contains('hidden')`)) await tap(page, '#notify-ask');
  145. let text = ''; for (let i = 0; i < 40 && !/closed/.test(text); i++) { await sleep(500); text = await pushText(page); }
  146. check('1 subscribed (the page says reminders also reach it when closed)', /closed/.test(text), J(text));
  147. const at = await addEvent(page, 'Twice check', 150000);
  148. say('reminder at ' + new Date(at).toTimeString().slice(0, 8) + '; closing the tab (the browser stays)');
  149. await page.close(); brA.pages = brA.pages.filter(p => p !== page);
  150. await until(at + 15000);
  151. const got = received.filter(x => x.url === '/ok/devA');
  152. 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)));
  153. // ---- 2 the phone is opened again (same profile) after the push, before the event starts ----
  154. page = await phone2(alice, subA, brA);
  155. await page.goto(BASE + '/', { timeout: 120000 }); await hydrated(page);
  156. await tap(page, '#month-title'); await sleep(6000);
  157. const shown = (await shownNow(page)).filter(n => n.title === 'Twice check');
  158. say('page showed: ' + J(shown));
  159. check('2 the page does NOT show the reminder the server already pushed (shown twice before P1)', shown.length === 0, J(shown));
  160. await page.close(); brA.pages = brA.pages.filter(p => p !== page);
  161. check('2 still one push in total', received.filter(x => x.url === '/ok/devA').length === 1, String(received.length));
  162. // ---- 3 control: bob has NO push subscription: his page still shows the missed reminder (the net stays) ----
  163. const brB = await launchBrowser({ debugPortRange: [CPORT + 1, CPORT + 1] }); browsers.push(brB);
  164. page = await phone2(bob, null, brB);
  165. await tap(page, '#month-title'); await sleep(800);
  166. const atB = await addEvent(page, 'Bob net', 150000);
  167. await page.close(); brB.pages = brB.pages.filter(p => p !== page);
  168. await until(atB + 10000);
  169. page = await phone2(bob, null, brB);
  170. await page.goto(BASE + '/', { timeout: 120000 }); await hydrated(page);
  171. await tap(page, '#month-title'); await sleep(6000);
  172. const shownB = (await shownNow(page)).filter(n => n.title === 'Bob net');
  173. check('3 control: a device without push still gets its missed reminder from the page', shownB.length === 1, J(shownB));
  174. }
  175. try { await main(); } catch (e) { check('gate ran', false, String(e && e.stack || e)); }
  176. if (failures) console.log('---- server log (tail)\n' + log.slice(-2500));
  177. await stopAll();
  178. console.log(`${passes} passed, ${failures} failed (app ${APP})`);
  179. 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