@pi-chamber/web 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/bin/cli.js +7 -32
- package/bin/dev-server.js +185 -0
- package/bin/dev-server.test.js +252 -0
- package/bin/lib/DOCUMENTATION.md +19 -0
- package/bin/lib/cli-startup.js +9 -1
- package/bin/lib/cli-startup.test.js +30 -0
- package/bin/lib/commands-serve.js +9 -5
- package/bin/lib/server-runtime.js +6 -0
- package/bin/lib/server-runtime.test.js +313 -0
- package/dist/assets/{DiagramView-CbSxUe1D.js → DiagramView-COHSzZ9Z.js} +1 -1
- package/dist/assets/{DiffView-VyBf4ilo.js → DiffView-BA4LWExp.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-BCvbQ234.js → FileSaveConflictDialog-hRumcJ2e.js} +1 -1
- package/dist/assets/{FilesView-DasA5EU2.js → FilesView-CIx6Bq8l.js} +1 -1
- package/dist/assets/{GitView-DU3mOECp.js → GitView-3Hgk_pVS.js} +3 -3
- package/dist/assets/{JsonTreeView-xZiWDwua.js → JsonTreeView-CVLGj7jk.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-BBwdI2OF.js → MarkdownRendererImpl-CWeQW9_O.js} +1 -1
- package/dist/assets/{PatchDiff-BhKm_JPT.js → PatchDiff-367QPDDL.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-DTGSP_RB.js → SessionSwitcherContent-CbgywSHr.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-CedOB-xC.js → SessionSwitcherDropdown-BAHhqkBZ.js} +2 -2
- package/dist/assets/{SessionUnreadDot-CZSNKram.js → SessionUnreadDot-CvIWGgIi.js} +1 -1
- package/dist/assets/SettingsView-BpGtnBKt.js +2 -0
- package/dist/assets/{SettingsWindow-y33YrpBE.js → SettingsWindow-CN0wm-Fv.js} +1 -1
- package/dist/assets/{ToolOutputDialog-JqIXJWAH.js → ToolOutputDialog-Bkh0DWJn.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-CRi_33jE.js → ToolPartDiffPreview-C_V9k2ob.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-ehLQSR5W.js → VirtualizedFileDiff-CFToyUp4.js} +1 -1
- package/dist/assets/{collapsible-Vypq-nMP.js → collapsible-BXBoS1M4.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-BTfrj_fR.js → computeVirtualFileMetrics-BpbB2xiE.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-Dl6mFfD1.js → contextFileOpenGuard-DsdrIBIY.js} +1 -1
- package/dist/assets/{gitStatusPredicates-LAsJAhCL.js → gitStatusPredicates-KYx0Vs9h.js} +1 -1
- package/dist/assets/{index-OveFsNBm.js → index-CVZfC79h.js} +1 -1
- package/dist/assets/{index-BXX8l7mM.css → index-Ci9OMaKW.css} +1 -1
- package/dist/assets/{index-DvNeSFO9.js → index-DyeT2dc_.js} +7 -7
- package/dist/assets/{isDiffPlainText-CNZohQ4q.js → isDiffPlainText-dBQiDlRy.js} +1 -1
- package/dist/assets/{isFilePlainText-Dz8UubRT.js → isFilePlainText-DWMzO-Ms.js} +1 -1
- package/dist/assets/{main-BsDkATRV.js → main-DkXvFwTR.js} +3 -3
- package/dist/assets/{main-C393Ywhx.js → main-DukaBOy3.js} +2 -2
- package/dist/assets/{markdownCore-Bz9-Y75q.js → markdownCore-BH61OrJ2.js} +1 -1
- package/dist/assets/{miniChat-CWEerp3c.js → miniChat-B1uBoxSn.js} +2 -2
- package/dist/assets/{mobile-YxV9KcxF.js → mobile-DV_RYy3x.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-GrLmBQRb.js → renderElectronMiniChatApp-CA6co_Lh.js} +2 -2
- package/dist/assets/renderMobileApp-CyhFZ_4g.js +11 -0
- package/dist/assets/runtimeEndpointReset-CVoKFaRw.js +53 -0
- package/dist/assets/{runtimeSurface-DUXw4-oa.js → runtimeSurface-CxbVCK7k.js} +1 -1
- package/dist/assets/{useAppFontEffects-ad-lZJ6o.js → useAppFontEffects-HCEusnq7.js} +77 -77
- package/dist/assets/{useFilesViewSearch-C4oOHPml.js → useFilesViewSearch-Cq7IOB7l.js} +1 -1
- package/dist/assets/{usePushVisibilityBeacon-xd8Q10cI.js → usePushVisibilityBeacon-Tvi9uL7v.js} +1 -1
- package/dist/assets/{useSwitcherItems-B6VC7tug.js → useSwitcherItems-DLA7kskG.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B4j3gkaT.js → vendor-codemirror-language-data-zF3O85ti.js} +2 -2
- package/dist/assets/{web-components-B0RFakat.js → web-components-C7g3Hi85.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +8 -3
- package/server/index.js +40 -6
- package/server/lib/notifications/DOCUMENTATION.md +39 -0
- package/server/lib/notifications/delivery-runtime.js +314 -0
- package/server/lib/notifications/delivery-runtime.test.js +85 -0
- package/server/lib/notifications/pi-notification-watcher.js +154 -0
- package/server/lib/notifications/pi-notification-watcher.test.js +84 -0
- package/server/lib/notifications/routes.js +74 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -0
- package/server/lib/pi/session-daemon/pi-runtime-smoke.test.js +466 -0
- package/server/lib/pi/ui-settings-store.js +3 -2
- package/server/lib/server/runtime-requirements.js +193 -0
- package/server/lib/server/runtime-requirements.test.js +295 -0
- package/dist/assets/SettingsView-B5nmu8x4.js +0 -2
- package/dist/assets/renderMobileApp-C29wquBe.js +0 -11
- package/dist/assets/runtimeEndpointReset-DHARMv9w.js +0 -53
package/server/index.js
CHANGED
|
@@ -3,7 +3,9 @@ import compression from 'compression';
|
|
|
3
3
|
import express from 'express';
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import http from 'node:http';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
6
7
|
import os from 'node:os';
|
|
8
|
+
import webPush from 'web-push';
|
|
7
9
|
import path from 'node:path';
|
|
8
10
|
import { fileURLToPath } from 'node:url';
|
|
9
11
|
|
|
@@ -13,6 +15,10 @@ import { createRevocationCoordinator } from './lib/client-auth/principal-tracker
|
|
|
13
15
|
import { resolvePiChamberDataDir } from './lib/pichamber-data-dir.js';
|
|
14
16
|
import { createTunnelService } from './lib/server/tunnel-service.js';
|
|
15
17
|
import { registerPiRuntimeRoutes } from './lib/pi/routes.js';
|
|
18
|
+
import { createPiUiSettingsStore } from './lib/pi/ui-settings-store.js';
|
|
19
|
+
import { createNotificationDeliveryRuntime } from './lib/notifications/delivery-runtime.js';
|
|
20
|
+
import { createPiNotificationWatcher } from './lib/notifications/pi-notification-watcher.js';
|
|
21
|
+
import { registerNotificationRoutes } from './lib/notifications/routes.js';
|
|
16
22
|
import { registerWorkspaceIntegrations } from './lib/workspace/host.js';
|
|
17
23
|
import { createPiSessionDaemonSupervisor } from './lib/pi/session-daemon/supervisor.js';
|
|
18
24
|
import {
|
|
@@ -31,6 +37,7 @@ import {
|
|
|
31
37
|
} from './lib/server/core-routes.js';
|
|
32
38
|
import { createTunnelAuth } from './lib/server/tunnel-auth.js';
|
|
33
39
|
import { createUiAuth } from './lib/ui-auth/ui-auth.js';
|
|
40
|
+
import { assertCurrentRuntimeSupported as defaultAssertCurrentRuntimeSupported } from './lib/server/runtime-requirements.js';
|
|
34
41
|
|
|
35
42
|
const __filename = fileURLToPath(import.meta.url);
|
|
36
43
|
const __dirname = path.dirname(__filename);
|
|
@@ -104,6 +111,11 @@ export async function gracefulShutdown({ exitProcess = false } = {}) {
|
|
|
104
111
|
}
|
|
105
112
|
|
|
106
113
|
export async function startWebUiServer(options = {}) {
|
|
114
|
+
// Enforce the actual current runtime before any resource allocation so
|
|
115
|
+
// direct CLI foreground and Electron in-process hosts are checked via the
|
|
116
|
+
// real process versions. Never probe an external Node binary here: under
|
|
117
|
+
// Bun `process.version` emulates Node and must not mask an old Bun.
|
|
118
|
+
defaultAssertCurrentRuntimeSupported();
|
|
107
119
|
warnIgnoredTunnelOptions(options);
|
|
108
120
|
const port = Number.isInteger(options.port) && options.port >= 0 ? options.port : DEFAULT_PORT;
|
|
109
121
|
const host = typeof options.host === 'string' && options.host.trim() ? options.host.trim() : (process.env.PICHAMBER_HOST || '127.0.0.1');
|
|
@@ -139,6 +151,14 @@ export async function startWebUiServer(options = {}) {
|
|
|
139
151
|
// listen so the profile key uses the bound port; routes observe it through
|
|
140
152
|
// the getter and report unavailable until it exists.
|
|
141
153
|
let piSessionDaemonRuntime = null;
|
|
154
|
+
let notificationWatcher = null;
|
|
155
|
+
const uiSettingsStore = createPiUiSettingsStore();
|
|
156
|
+
const notificationDelivery = createNotificationDeliveryRuntime({
|
|
157
|
+
dataDir: PICHAMBER_DATA_DIR,
|
|
158
|
+
webPush,
|
|
159
|
+
crypto,
|
|
160
|
+
onDesktopNotification: options.onDesktopNotification,
|
|
161
|
+
});
|
|
142
162
|
const tunnelService = createTunnelService({
|
|
143
163
|
dataDir: PICHAMBER_DATA_DIR,
|
|
144
164
|
getPort: () => {
|
|
@@ -201,7 +221,11 @@ export async function startWebUiServer(options = {}) {
|
|
|
201
221
|
getServerId: async () => null,
|
|
202
222
|
getServerLabel: () => os.hostname() || 'PiChamber',
|
|
203
223
|
});
|
|
204
|
-
const piRuntimeRoutes = registerPiRuntimeRoutes(app, {
|
|
224
|
+
const piRuntimeRoutes = registerPiRuntimeRoutes(app, {
|
|
225
|
+
getPiSessionDaemonRuntime: () => piSessionDaemonRuntime,
|
|
226
|
+
uiSettingsStore,
|
|
227
|
+
});
|
|
228
|
+
registerNotificationRoutes(app, { uiAuthController, delivery: notificationDelivery });
|
|
205
229
|
// Cloudflare Tunnel external access (manual token + quick modes).
|
|
206
230
|
const requireTunnelAuth = (req, res, next) => uiAuthController.requireAuth(req, res, next);
|
|
207
231
|
app.get('/api/pichamber/tunnel/status', requireTunnelAuth, async (_req, res) => {
|
|
@@ -242,12 +266,21 @@ export async function startWebUiServer(options = {}) {
|
|
|
242
266
|
profileKey: piSessionDaemonRuntime.paths.profileKey,
|
|
243
267
|
});
|
|
244
268
|
}
|
|
245
|
-
// Warm the
|
|
246
|
-
//
|
|
247
|
-
//
|
|
248
|
-
|
|
249
|
-
|
|
269
|
+
// Warm startup creates the daemon credential before subscriptions can read
|
|
270
|
+
// it. The watcher then owns transport retries independently of browsers so
|
|
271
|
+
// native background push keeps working after reconnects.
|
|
272
|
+
notificationWatcher = createPiNotificationWatcher({
|
|
273
|
+
supervisor: piSessionDaemonRuntime,
|
|
274
|
+
uiSettingsStore,
|
|
275
|
+
delivery: notificationDelivery,
|
|
250
276
|
});
|
|
277
|
+
void piSessionDaemonRuntime.start()
|
|
278
|
+
.catch((error) => {
|
|
279
|
+
console.warn(`[PiSessionDaemon] unavailable: ${error?.code ?? 'DAEMON_UNAVAILABLE'}`);
|
|
280
|
+
})
|
|
281
|
+
.finally(() => {
|
|
282
|
+
if (!stopped) return notificationWatcher?.start();
|
|
283
|
+
});
|
|
251
284
|
const controller = {
|
|
252
285
|
expressApp: app,
|
|
253
286
|
httpServer: server,
|
|
@@ -268,6 +301,7 @@ export async function startWebUiServer(options = {}) {
|
|
|
268
301
|
liveRevocation.dispose();
|
|
269
302
|
piRuntimeRoutes.closeEventStreams();
|
|
270
303
|
await Promise.allSettled([
|
|
304
|
+
notificationWatcher?.stop(),
|
|
271
305
|
workspaceRuntime.shutdown(),
|
|
272
306
|
piSessionDaemonRuntime ? piSessionDaemonRuntime.stop() : Promise.resolve(),
|
|
273
307
|
close(server),
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Notifications
|
|
2
|
+
|
|
3
|
+
## Ownership
|
|
4
|
+
|
|
5
|
+
This module owns server-side notification delivery for Pi session completion and terminal errors.
|
|
6
|
+
It does not model OpenCode questions, permissions, subagents, or tool completion.
|
|
7
|
+
|
|
8
|
+
`pi-notification-watcher.js` maintains one server-owned subscription to the Pi session daemon. A live `busy` or `retry` lifecycle, or an assistant start, opens a turn. The first terminal `idle` emits a completion notification and the first `session.error` or terminal `error` emits an error notification. Duplicate terminal boundaries do nothing. Bootstrap snapshots seed activity but never notify for old settled work. User interruption settles without notifying.
|
|
9
|
+
|
|
10
|
+
The watcher reads `/api/pi/ui-settings` storage before delivery. Notifications require `nativeNotificationsEnabled`; `notifyOnCompletion` and `notifyOnError` gate their respective events.
|
|
11
|
+
|
|
12
|
+
`delivery-runtime.js` fans one generic payload out to:
|
|
13
|
+
|
|
14
|
+
- Electron's native callback when the web server runs inside the desktop app.
|
|
15
|
+
- Browser Web Push subscriptions.
|
|
16
|
+
- Capacitor device tokens through the PiChamber push relay.
|
|
17
|
+
|
|
18
|
+
Payloads contain a fixed completion/error title, the session title when known, an opaque session ID for navigation, and a stable event tag. They never contain prompts, assistant output, tool input/output, provider credentials, or error details.
|
|
19
|
+
|
|
20
|
+
## Routes
|
|
21
|
+
|
|
22
|
+
`routes.js` registers authenticated endpoints:
|
|
23
|
+
|
|
24
|
+
- `GET /api/push/vapid-public-key`
|
|
25
|
+
- `POST` and `DELETE /api/push/subscribe`
|
|
26
|
+
- `POST` and `DELETE /api/push/apns-token`
|
|
27
|
+
- `POST /api/push/visibility`
|
|
28
|
+
|
|
29
|
+
The persisted `notifications.json` file contains VAPID private material, relay signing keys, browser subscriptions, and native device tokens. It is written atomically with owner-only permissions under the PiChamber data directory. Never log its contents.
|
|
30
|
+
|
|
31
|
+
## Mobile relay
|
|
32
|
+
|
|
33
|
+
Native iOS and Android registration uses `@capacitor/push-notifications`. The server binds each token to its per-server signing key and sends signed requests to `https://api.pichamber.dev/v1/push/send` by default. Override with `PICHAMBER_PUSH_RELAY_URL`; set `PICHAMBER_PUSH_RELAY_DISABLED=true` to disable native relay delivery.
|
|
34
|
+
|
|
35
|
+
The app suppresses foreground native banners. A recent visible desktop or browser client suppresses native mobile fanout, avoiding a second device alert while the user is already watching the session.
|
|
36
|
+
|
|
37
|
+
## Failure behavior
|
|
38
|
+
|
|
39
|
+
One failed delivery channel does not block the others. Dead Web Push endpoints are removed after HTTP 404/410. Registration failure is visible to the client. The watcher reconnects to the daemon with its sequence and stream epoch, so replayed terminal events remain deduplicated by the active-turn state.
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { withCrossProcessLock } from '../server/cross-process-lock.js';
|
|
6
|
+
import { signRelayMessage } from '../relay/signing-key.js';
|
|
7
|
+
|
|
8
|
+
const STORE_VERSION = 1;
|
|
9
|
+
const MAX_ENTRIES_PER_CLIENT = 10;
|
|
10
|
+
const MAX_STORED_ENTRIES = 1_000;
|
|
11
|
+
const VISIBILITY_TTL_MS = 30_000;
|
|
12
|
+
const DEFAULT_RELAY_URL = 'https://api.pichamber.dev/v1/push/send';
|
|
13
|
+
|
|
14
|
+
const emptyStore = () => ({
|
|
15
|
+
version: STORE_VERSION,
|
|
16
|
+
subscriptionsByClient: {},
|
|
17
|
+
nativeTokensByClient: {},
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
21
|
+
|
|
22
|
+
const boundEntriesByClient = (entriesByClient) => {
|
|
23
|
+
const newest = Object.entries(entriesByClient)
|
|
24
|
+
.flatMap(([clientId, entries]) => (Array.isArray(entries)
|
|
25
|
+
? entries.map((entry) => ({ clientId, entry }))
|
|
26
|
+
: []))
|
|
27
|
+
.filter(({ entry }) => isRecord(entry))
|
|
28
|
+
.sort((left, right) => (right.entry.updatedAt ?? 0) - (left.entry.updatedAt ?? 0))
|
|
29
|
+
.slice(0, MAX_STORED_ENTRIES);
|
|
30
|
+
const bounded = {};
|
|
31
|
+
for (const { clientId, entry } of newest) {
|
|
32
|
+
(bounded[clientId] ??= []).push(entry);
|
|
33
|
+
}
|
|
34
|
+
return bounded;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export const createNotificationDeliveryRuntime = ({
|
|
38
|
+
dataDir,
|
|
39
|
+
webPush,
|
|
40
|
+
crypto,
|
|
41
|
+
fetch: fetchImpl = globalThis.fetch,
|
|
42
|
+
storeFile = join(dataDir, 'notifications.json'),
|
|
43
|
+
relayUrl = process.env.PICHAMBER_PUSH_RELAY_URL || DEFAULT_RELAY_URL,
|
|
44
|
+
onDesktopNotification,
|
|
45
|
+
}) => {
|
|
46
|
+
const visibilityByClient = new Map();
|
|
47
|
+
let initializedWebPush = false;
|
|
48
|
+
|
|
49
|
+
const readStore = async () => {
|
|
50
|
+
try {
|
|
51
|
+
const parsed = JSON.parse(await readFile(storeFile, 'utf8'));
|
|
52
|
+
if (!isRecord(parsed) || parsed.version !== STORE_VERSION) return emptyStore();
|
|
53
|
+
return {
|
|
54
|
+
version: STORE_VERSION,
|
|
55
|
+
subscriptionsByClient: isRecord(parsed.subscriptionsByClient) ? parsed.subscriptionsByClient : {},
|
|
56
|
+
nativeTokensByClient: isRecord(parsed.nativeTokensByClient) ? parsed.nativeTokensByClient : {},
|
|
57
|
+
...(isRecord(parsed.vapidKeys) ? { vapidKeys: parsed.vapidKeys } : {}),
|
|
58
|
+
...(isRecord(parsed.relaySigningKey) ? { relaySigningKey: parsed.relaySigningKey } : {}),
|
|
59
|
+
};
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (error?.code === 'ENOENT') return emptyStore();
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const writeStore = async (store) => {
|
|
67
|
+
await mkdir(dirname(storeFile), { recursive: true, mode: 0o700 });
|
|
68
|
+
const temporary = `${storeFile}.tmp-${process.pid}-${randomUUID()}`;
|
|
69
|
+
await writeFile(temporary, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
|
|
70
|
+
await rename(temporary, storeFile);
|
|
71
|
+
if (process.platform !== 'win32') await chmod(storeFile, 0o600);
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const mutateStore = (mutate) => withCrossProcessLock(`${storeFile}.lock`, async () => {
|
|
75
|
+
const next = await mutate(await readStore());
|
|
76
|
+
await writeStore(next);
|
|
77
|
+
return next;
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
const getOrCreateVapidKeys = async () => {
|
|
81
|
+
const current = await readStore();
|
|
82
|
+
if (typeof current.vapidKeys?.publicKey === 'string' && typeof current.vapidKeys?.privateKey === 'string') {
|
|
83
|
+
return current.vapidKeys;
|
|
84
|
+
}
|
|
85
|
+
const generated = webPush.generateVAPIDKeys();
|
|
86
|
+
const next = await mutateStore((store) => ({ ...store, vapidKeys: store.vapidKeys ?? generated }));
|
|
87
|
+
return next.vapidKeys;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const ensureWebPush = async () => {
|
|
91
|
+
if (initializedWebPush) return;
|
|
92
|
+
const keys = await getOrCreateVapidKeys();
|
|
93
|
+
webPush.setVapidDetails('mailto:pichamber@localhost', keys.publicKey, keys.privateKey);
|
|
94
|
+
initializedWebPush = true;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const addWebSubscription = async (clientId, input) => {
|
|
98
|
+
await ensureWebPush();
|
|
99
|
+
await mutateStore((store) => {
|
|
100
|
+
const existing = Array.isArray(store.subscriptionsByClient[clientId])
|
|
101
|
+
? store.subscriptionsByClient[clientId]
|
|
102
|
+
: [];
|
|
103
|
+
const entries = existing.filter((entry) => entry?.endpoint !== input.endpoint);
|
|
104
|
+
entries.unshift({ ...input, updatedAt: Date.now() });
|
|
105
|
+
return {
|
|
106
|
+
...store,
|
|
107
|
+
subscriptionsByClient: boundEntriesByClient({
|
|
108
|
+
...store.subscriptionsByClient,
|
|
109
|
+
[clientId]: entries.slice(0, MAX_ENTRIES_PER_CLIENT),
|
|
110
|
+
}),
|
|
111
|
+
};
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const removeWebSubscription = async (clientId, endpoint) => {
|
|
116
|
+
await mutateStore((store) => {
|
|
117
|
+
const existing = Array.isArray(store.subscriptionsByClient[clientId])
|
|
118
|
+
? store.subscriptionsByClient[clientId]
|
|
119
|
+
: [];
|
|
120
|
+
const entries = existing.filter((entry) => entry?.endpoint !== endpoint);
|
|
121
|
+
const subscriptionsByClient = { ...store.subscriptionsByClient };
|
|
122
|
+
if (entries.length > 0) subscriptionsByClient[clientId] = entries;
|
|
123
|
+
else delete subscriptionsByClient[clientId];
|
|
124
|
+
return { ...store, subscriptionsByClient };
|
|
125
|
+
});
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const getOrCreateRelayKey = async () => {
|
|
129
|
+
const current = await readStore();
|
|
130
|
+
if (isRecord(current.relaySigningKey?.privateJwk) && isRecord(current.relaySigningKey?.publicJwk)) {
|
|
131
|
+
return {
|
|
132
|
+
privateKey: crypto.createPrivateKey({ key: current.relaySigningKey.privateJwk, format: 'jwk' }),
|
|
133
|
+
publicJwk: current.relaySigningKey.publicJwk,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const pair = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
|
137
|
+
const generated = {
|
|
138
|
+
privateJwk: pair.privateKey.export({ format: 'jwk' }),
|
|
139
|
+
publicJwk: pair.publicKey.export({ format: 'jwk' }),
|
|
140
|
+
};
|
|
141
|
+
const next = await mutateStore((store) => ({ ...store, relaySigningKey: store.relaySigningKey ?? generated }));
|
|
142
|
+
return {
|
|
143
|
+
privateKey: crypto.createPrivateKey({ key: next.relaySigningKey.privateJwk, format: 'jwk' }),
|
|
144
|
+
publicJwk: next.relaySigningKey.publicJwk,
|
|
145
|
+
};
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const relayPublicJwk = (jwk) => ({ kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y });
|
|
149
|
+
|
|
150
|
+
const registerNativeTokenWithRelay = async (token, platform) => {
|
|
151
|
+
if (!relayUrl || process.env.PICHAMBER_PUSH_RELAY_DISABLED === 'true') return;
|
|
152
|
+
const { privateKey, publicJwk } = await getOrCreateRelayKey();
|
|
153
|
+
const ts = Date.now();
|
|
154
|
+
const sig = signRelayMessage({ crypto }, privateKey, `${ts}.${token}.${platform}`);
|
|
155
|
+
const response = await fetchImpl(relayUrl.replace(/\/send$/, '/register-token'), {
|
|
156
|
+
method: 'POST',
|
|
157
|
+
headers: { 'content-type': 'application/json' },
|
|
158
|
+
body: JSON.stringify({ token, platform, publicKeyJwk: relayPublicJwk(publicJwk), ts, sig }),
|
|
159
|
+
});
|
|
160
|
+
if (!response.ok) throw new Error(`PUSH_RELAY_REGISTRATION_FAILED_${response.status}`);
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const addNativeToken = async (clientId, input) => {
|
|
164
|
+
await mutateStore((store) => {
|
|
165
|
+
const existing = Array.isArray(store.nativeTokensByClient[clientId])
|
|
166
|
+
? store.nativeTokensByClient[clientId]
|
|
167
|
+
: [];
|
|
168
|
+
const entries = existing.filter((entry) => entry?.token !== input.token);
|
|
169
|
+
entries.unshift({ ...input, updatedAt: Date.now() });
|
|
170
|
+
return {
|
|
171
|
+
...store,
|
|
172
|
+
nativeTokensByClient: boundEntriesByClient({
|
|
173
|
+
...store.nativeTokensByClient,
|
|
174
|
+
[clientId]: entries.slice(0, MAX_ENTRIES_PER_CLIENT),
|
|
175
|
+
}),
|
|
176
|
+
};
|
|
177
|
+
});
|
|
178
|
+
await registerNativeTokenWithRelay(input.token, input.platform);
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const removeNativeToken = async (clientId, token) => {
|
|
182
|
+
await mutateStore((store) => {
|
|
183
|
+
const existing = Array.isArray(store.nativeTokensByClient[clientId])
|
|
184
|
+
? store.nativeTokensByClient[clientId]
|
|
185
|
+
: [];
|
|
186
|
+
const entries = existing.filter((entry) => entry?.token !== token);
|
|
187
|
+
const nativeTokensByClient = { ...store.nativeTokensByClient };
|
|
188
|
+
if (entries.length > 0) nativeTokensByClient[clientId] = entries;
|
|
189
|
+
else delete nativeTokensByClient[clientId];
|
|
190
|
+
return { ...store, nativeTokensByClient };
|
|
191
|
+
});
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const removeNativeTokenFromAllClients = async (token) => {
|
|
195
|
+
await mutateStore((store) => {
|
|
196
|
+
const nativeTokensByClient = {};
|
|
197
|
+
for (const [clientId, entries] of Object.entries(store.nativeTokensByClient)) {
|
|
198
|
+
const kept = Array.isArray(entries) ? entries.filter((entry) => entry?.token !== token) : [];
|
|
199
|
+
if (kept.length > 0) nativeTokensByClient[clientId] = kept;
|
|
200
|
+
}
|
|
201
|
+
return { ...store, nativeTokensByClient };
|
|
202
|
+
});
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
const updateVisibility = (clientId, visible, platform) => {
|
|
206
|
+
visibilityByClient.set(clientId, { visible, platform, updatedAt: Date.now() });
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
const isAnyInteractiveClientVisible = () => {
|
|
210
|
+
const now = Date.now();
|
|
211
|
+
for (const [clientId, state] of visibilityByClient) {
|
|
212
|
+
if (now - state.updatedAt > VISIBILITY_TTL_MS) {
|
|
213
|
+
visibilityByClient.delete(clientId);
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (state.visible && state.platform !== 'ios' && state.platform !== 'android') return true;
|
|
217
|
+
}
|
|
218
|
+
return false;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const removeDeadWebEndpoint = async (endpoint) => {
|
|
222
|
+
await mutateStore((store) => {
|
|
223
|
+
const subscriptionsByClient = {};
|
|
224
|
+
for (const [clientId, entries] of Object.entries(store.subscriptionsByClient)) {
|
|
225
|
+
const kept = Array.isArray(entries) ? entries.filter((entry) => entry?.endpoint !== endpoint) : [];
|
|
226
|
+
if (kept.length > 0) subscriptionsByClient[clientId] = kept;
|
|
227
|
+
}
|
|
228
|
+
return { ...store, subscriptionsByClient };
|
|
229
|
+
});
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const sendWebPush = async (payload) => {
|
|
233
|
+
await ensureWebPush();
|
|
234
|
+
const store = await readStore();
|
|
235
|
+
const byEndpoint = new Map();
|
|
236
|
+
for (const entries of Object.values(store.subscriptionsByClient)) {
|
|
237
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
238
|
+
if (typeof entry?.endpoint === 'string') byEndpoint.set(entry.endpoint, entry);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
await Promise.all([...byEndpoint.values()].map(async (entry) => {
|
|
242
|
+
try {
|
|
243
|
+
await webPush.sendNotification({
|
|
244
|
+
endpoint: entry.endpoint,
|
|
245
|
+
keys: { p256dh: entry.p256dh, auth: entry.auth },
|
|
246
|
+
}, JSON.stringify(payload));
|
|
247
|
+
} catch (error) {
|
|
248
|
+
if (error?.statusCode === 404 || error?.statusCode === 410) {
|
|
249
|
+
await removeDeadWebEndpoint(entry.endpoint);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
console.warn(`[Push] delivery failed with status ${error?.statusCode ?? 'unknown'}`);
|
|
253
|
+
}
|
|
254
|
+
}));
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
const sendNativePush = async (payload) => {
|
|
258
|
+
if (!relayUrl || process.env.PICHAMBER_PUSH_RELAY_DISABLED === 'true') return;
|
|
259
|
+
if (isAnyInteractiveClientVisible()) return;
|
|
260
|
+
const store = await readStore();
|
|
261
|
+
const tokens = new Set();
|
|
262
|
+
for (const entries of Object.values(store.nativeTokensByClient)) {
|
|
263
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
264
|
+
if (typeof entry?.token === 'string') tokens.add(entry.token);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (tokens.size === 0) return;
|
|
268
|
+
const list = [...tokens].slice(0, 100);
|
|
269
|
+
const { privateKey, publicJwk } = await getOrCreateRelayKey();
|
|
270
|
+
const ts = Date.now();
|
|
271
|
+
const sig = signRelayMessage({ crypto }, privateKey, `${ts}.${[...list].sort().join(',')}.${payload.title}`);
|
|
272
|
+
const response = await fetchImpl(relayUrl, {
|
|
273
|
+
method: 'POST',
|
|
274
|
+
headers: { 'content-type': 'application/json' },
|
|
275
|
+
body: JSON.stringify({
|
|
276
|
+
tokens: list,
|
|
277
|
+
title: payload.title,
|
|
278
|
+
body: payload.body,
|
|
279
|
+
collapseId: payload.tag?.slice(0, 64),
|
|
280
|
+
data: payload.data,
|
|
281
|
+
publicKeyJwk: relayPublicJwk(publicJwk),
|
|
282
|
+
ts,
|
|
283
|
+
sig,
|
|
284
|
+
}),
|
|
285
|
+
});
|
|
286
|
+
if (!response.ok) {
|
|
287
|
+
console.warn(`[Push relay] delivery failed with status ${response.status}`);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
const result = await response.json().catch(() => null);
|
|
291
|
+
for (const entry of Array.isArray(result?.results) ? result.results : []) {
|
|
292
|
+
if (entry?.drop === true && typeof entry.token === 'string') {
|
|
293
|
+
await removeNativeTokenFromAllClients(entry.token);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
const send = async (payload) => {
|
|
299
|
+
const desktop = typeof onDesktopNotification === 'function'
|
|
300
|
+
? Promise.resolve().then(() => onDesktopNotification(payload))
|
|
301
|
+
: Promise.resolve();
|
|
302
|
+
await Promise.allSettled([desktop, sendWebPush(payload), sendNativePush(payload)]);
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
return {
|
|
306
|
+
getOrCreateVapidKeys,
|
|
307
|
+
addWebSubscription,
|
|
308
|
+
removeWebSubscription,
|
|
309
|
+
addNativeToken,
|
|
310
|
+
removeNativeToken,
|
|
311
|
+
updateVisibility,
|
|
312
|
+
send,
|
|
313
|
+
};
|
|
314
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { createNotificationDeliveryRuntime } from './delivery-runtime.js';
|
|
8
|
+
|
|
9
|
+
const directories = [];
|
|
10
|
+
afterEach(async () => {
|
|
11
|
+
await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })));
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
const setup = async () => {
|
|
15
|
+
const dataDir = await mkdtemp(join(tmpdir(), 'pichamber-notifications-'));
|
|
16
|
+
directories.push(dataDir);
|
|
17
|
+
const sendNotification = vi.fn(async () => undefined);
|
|
18
|
+
const fetch = vi.fn(async () => new Response(JSON.stringify({ results: [] }), { status: 200 }));
|
|
19
|
+
const webPush = {
|
|
20
|
+
generateVAPIDKeys: vi.fn(() => ({ publicKey: 'public-key', privateKey: 'private-key' })),
|
|
21
|
+
setVapidDetails: vi.fn(),
|
|
22
|
+
sendNotification,
|
|
23
|
+
};
|
|
24
|
+
return {
|
|
25
|
+
dataDir,
|
|
26
|
+
fetch,
|
|
27
|
+
sendNotification,
|
|
28
|
+
runtime: createNotificationDeliveryRuntime({ dataDir, webPush, crypto, fetch }),
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
describe('notification delivery runtime', () => {
|
|
33
|
+
it('persists subscriptions privately and fans out one terminal event', async () => {
|
|
34
|
+
const { dataDir, fetch, runtime, sendNotification } = await setup();
|
|
35
|
+
await runtime.addWebSubscription('client-1', {
|
|
36
|
+
endpoint: 'https://push.example/subscription',
|
|
37
|
+
p256dh: 'p256dh',
|
|
38
|
+
auth: 'auth',
|
|
39
|
+
platform: 'web',
|
|
40
|
+
});
|
|
41
|
+
await runtime.addNativeToken('client-1', {
|
|
42
|
+
token: 'native-token',
|
|
43
|
+
platform: 'ios',
|
|
44
|
+
environment: 'production',
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
await runtime.send({
|
|
48
|
+
title: 'Work completed',
|
|
49
|
+
body: 'Session',
|
|
50
|
+
tag: 'pichamber:completion:s1:7',
|
|
51
|
+
data: { type: 'completion', sessionId: 's1' },
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
expect(sendNotification).toHaveBeenCalledTimes(1);
|
|
55
|
+
expect(fetch).toHaveBeenCalledTimes(2);
|
|
56
|
+
expect(fetch.mock.calls[0][0]).toMatch(/register-token$/);
|
|
57
|
+
expect(fetch.mock.calls[1][0]).toMatch(/\/send$/);
|
|
58
|
+
const stored = JSON.parse(await readFile(join(dataDir, 'notifications.json'), 'utf8'));
|
|
59
|
+
expect(stored.subscriptionsByClient['client-1']).toHaveLength(1);
|
|
60
|
+
expect(stored.nativeTokensByClient['client-1']).toHaveLength(1);
|
|
61
|
+
if (process.platform !== 'win32') {
|
|
62
|
+
expect((await stat(join(dataDir, 'notifications.json'))).mode & 0o777).toBe(0o600);
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('suppresses native fanout while an interactive client is visible', async () => {
|
|
67
|
+
const { fetch, runtime } = await setup();
|
|
68
|
+
await runtime.addNativeToken('mobile', {
|
|
69
|
+
token: 'native-token',
|
|
70
|
+
platform: 'ios',
|
|
71
|
+
environment: 'production',
|
|
72
|
+
});
|
|
73
|
+
runtime.updateVisibility('desktop', true, 'desktop');
|
|
74
|
+
|
|
75
|
+
await runtime.send({
|
|
76
|
+
title: 'Work failed',
|
|
77
|
+
body: 'Session',
|
|
78
|
+
tag: 'pichamber:error:s1:9',
|
|
79
|
+
data: { type: 'error', sessionId: 's1' },
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
expect(fetch).toHaveBeenCalledTimes(1);
|
|
83
|
+
expect(fetch.mock.calls[0][0]).toMatch(/register-token$/);
|
|
84
|
+
});
|
|
85
|
+
});
|