@deep-podder/dsh-remote-mobile 0.0.0-stage → 0.0.6

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/push.js ADDED
@@ -0,0 +1,531 @@
1
+ // Real Web Push for the phone companion: VAPID (RFC 8292) + aes128gcm (RFC 8291).
2
+ //
3
+ // Zero dependencies: only `node:crypto` and the global `fetch` (Node >= 22). The
4
+ // Host server creates one service, persists its state inside the pairing state
5
+ // file (`push` field, mode 0600) and hands it to the bridge broadcast paths so a
6
+ // backgrounded phone's service worker is notified while the page is frozen.
7
+ //
8
+ // Security notes:
9
+ // - The VAPID private key lives only in memory and in the 0600 state file. It is
10
+ // never logged, never returned by an HTTP endpoint and never sent to a phone.
11
+ // - `sendNotification` never throws, and never logs the endpoint or the payload:
12
+ // only the HTTP status / `gone` flag is observable to callers.
13
+ // - Subscriptions are `https:` endpoints. Loopback `http:` endpoints are accepted
14
+ // only when `allowInsecureLoopback` is set, which exists for the deterministic
15
+ // `dev/push-check.mjs` harness; the Host server never enables it.
16
+ import {
17
+ createCipheriv,
18
+ createHmac,
19
+ createPrivateKey,
20
+ createPublicKey,
21
+ createSign,
22
+ diffieHellman,
23
+ generateKeyPairSync,
24
+ randomBytes,
25
+ } from 'node:crypto'
26
+
27
+ const VAPID_SUBJECT = 'mailto:dsh-remote-mobile@example.com'
28
+ const VAPID_JWT_LIFETIME_SECONDS = 12 * 60 * 60
29
+ const PUSH_TTL_SECONDS = 300
30
+
31
+ const P256_PUBLIC_BYTES = 65
32
+ const AUTH_SECRET_BYTES = 16
33
+ const AES_GCM_NONCE_BYTES = 12
34
+ const RECORD_SIZE = 4096
35
+ const MAX_SUBSCRIPTIONS = 16
36
+ const MAX_ENDPOINT_CHARS = 4096
37
+ const MAX_PAYLOAD_BYTES = 3800
38
+ const SEND_TIMEOUT_MS = 10_000
39
+
40
+ // RFC 8291 § 3.3/3.4 and RFC 8188 § 2.2 info strings (the trailing NUL is part
41
+ // of the protocol, not a string terminator).
42
+ const HKDF_AUTH_INFO = Buffer.from('WebPush: info\x00', 'utf8')
43
+ const HKDF_CEK_INFO = Buffer.from('Content-Encoding: aes128gcm\x00', 'utf8')
44
+ const HKDF_NONCE_INFO = Buffer.from('Content-Encoding: nonce\x00', 'utf8')
45
+
46
+ function base64url(buffer) {
47
+ return Buffer.from(buffer).toString('base64url')
48
+ }
49
+
50
+ /**
51
+ * Decode an unpadded base64url string of exactly `expectedBytes` octets.
52
+ * @returns {Buffer|null} null for anything that is not a well-formed value.
53
+ */
54
+ function decodeBase64url(value, expectedBytes) {
55
+ if (typeof value !== 'string' || value.length === 0) return null
56
+ const compact = value.replace(/=+$/u, '')
57
+ if (compact.length === 0 || !/^[A-Za-z0-9_-]+$/u.test(compact)) return null
58
+ const buffer = Buffer.from(compact, 'base64url')
59
+ if (expectedBytes !== undefined && buffer.length !== expectedBytes) return null
60
+ return buffer
61
+ }
62
+
63
+ /** Raw uncompressed P-256 point (0x04 || X || Y) for a KeyObject. */
64
+ function rawPublicFromKey(keyObject) {
65
+ const jwk = keyObject.export({ format: 'jwk' })
66
+ if (typeof jwk.x !== 'string' || typeof jwk.y !== 'string') throw new Error('not a P-256 public key')
67
+ return Buffer.concat([Buffer.from([0x04]), Buffer.from(jwk.x, 'base64url'), Buffer.from(jwk.y, 'base64url')])
68
+ }
69
+
70
+ /** KeyObject for a raw uncompressed P-256 point. */
71
+ function publicKeyFromRaw(raw) {
72
+ const jwk = {
73
+ kty: 'EC',
74
+ crv: 'P-256',
75
+ x: base64url(raw.subarray(1, 33)),
76
+ y: base64url(raw.subarray(33, 65)),
77
+ }
78
+ return createPublicKey({ key: jwk, format: 'jwk' })
79
+ }
80
+
81
+ function hkdfExtract(salt, inputKeyMaterial) {
82
+ return createHmac('sha256', salt).update(inputKeyMaterial).digest()
83
+ }
84
+
85
+ function hkdfExpand(pseudoRandomKey, info, length) {
86
+ const chunks = []
87
+ let previous = Buffer.alloc(0)
88
+ let produced = 0
89
+ let counter = 1
90
+ while (produced < length) {
91
+ previous = createHmac('sha256', pseudoRandomKey)
92
+ .update(Buffer.concat([previous, info, Buffer.from([counter])]))
93
+ .digest()
94
+ chunks.push(previous)
95
+ produced += previous.length
96
+ counter += 1
97
+ }
98
+ return Buffer.concat(chunks).subarray(0, length)
99
+ }
100
+
101
+ /**
102
+ * Encrypt one payload per RFC 8291 (aes128gcm content coding, RFC 8188).
103
+ * Exported for the deterministic dev check; the service uses it internally.
104
+ * @param {string|Buffer} uaPublic subscription `keys.p256dh` (base64url or raw bytes)
105
+ * @param {string|Buffer} authSecret subscription `keys.auth` (base64url or raw bytes)
106
+ * @param {Buffer|string} plaintext serialized JSON payload
107
+ * @returns {{ body: Buffer, salt: Buffer, asPublic: Buffer }}
108
+ */
109
+ export function encryptPayload(uaPublic, authSecret, plaintext, options = {}) {
110
+ const uaRaw = typeof uaPublic === 'string'
111
+ ? decodeBase64url(uaPublic, P256_PUBLIC_BYTES)
112
+ : Buffer.from(uaPublic ?? [])
113
+ const auth = typeof authSecret === 'string'
114
+ ? decodeBase64url(authSecret, AUTH_SECRET_BYTES)
115
+ : Buffer.from(authSecret ?? [])
116
+ if (uaRaw === null || uaRaw.length !== P256_PUBLIC_BYTES || uaRaw[0] !== 0x04) {
117
+ throw new Error('invalid p256dh')
118
+ }
119
+ if (auth === null || auth.length !== AUTH_SECRET_BYTES) throw new Error('invalid auth secret')
120
+ const payload = Buffer.isBuffer(plaintext) ? plaintext : Buffer.from(String(plaintext), 'utf8')
121
+
122
+ // Optional deterministic inputs exist only for the RFC 8291 test vector in
123
+ // the dev check; production calls pass no options and get fresh randomness.
124
+ const givenEphemeral = options !== null && typeof options === 'object' ? options.ephemeralPrivateKey : undefined
125
+ const ephemeralPrivate = givenEphemeral !== undefined && givenEphemeral !== null
126
+ ? (typeof givenEphemeral === 'object' && givenEphemeral.type === 'private'
127
+ ? givenEphemeral
128
+ : createPrivateKey(givenEphemeral))
129
+ : generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).privateKey
130
+ const asPublic = rawPublicFromKey(createPublicKey(ephemeralPrivate))
131
+ const shared = diffieHellman({ privateKey: ephemeralPrivate, publicKey: publicKeyFromRaw(uaRaw) })
132
+
133
+ // RFC 8291 § 3.3: IKM = HKDF(auth_secret, ecdh_secret, "WebPush: info\0" || ua_public || as_public)
134
+ const inputKeyMaterial = hkdfExpand(
135
+ hkdfExtract(auth, shared),
136
+ Buffer.concat([HKDF_AUTH_INFO, uaRaw, asPublic]),
137
+ 32,
138
+ )
139
+
140
+ // RFC 8291 § 3.4: per-message salt, then CEK and nonce from the same PRK.
141
+ const salt = options !== null && typeof options === 'object' && Buffer.isBuffer(options.salt)
142
+ ? Buffer.from(options.salt)
143
+ : randomBytes(16)
144
+ const prk = hkdfExtract(salt, inputKeyMaterial)
145
+ const cek = hkdfExpand(prk, HKDF_CEK_INFO, 16)
146
+ const nonce = hkdfExpand(prk, HKDF_NONCE_INFO, AES_GCM_NONCE_BYTES)
147
+
148
+ // RFC 8188 header: salt(16) || rs(4, big-endian) || idlen(1) || keyid(as_public).
149
+ const header = Buffer.alloc(16 + 4 + 1 + P256_PUBLIC_BYTES)
150
+ salt.copy(header, 0)
151
+ header.writeUInt32BE(RECORD_SIZE, 16)
152
+ header.writeUInt8(P256_PUBLIC_BYTES, 20)
153
+ asPublic.copy(header, 21)
154
+
155
+ // One record: the JSON payload followed by the 0x02 last-record delimiter.
156
+ // The RFC 8291 example confirms a single-record push uses an EMPTY AEAD AAD;
157
+ // adding the header as AAD yields a wrong authentication tag and the browser
158
+ // silently drops the message after accepting it from the push service.
159
+ const plaintextRecord = Buffer.concat([payload, Buffer.from([0x02])])
160
+ const cipher = createCipheriv('aes-128-gcm', cek, nonce)
161
+ const ciphertext = Buffer.concat([cipher.update(plaintextRecord), cipher.final(), cipher.getAuthTag()])
162
+
163
+ return { body: Buffer.concat([header, ciphertext]), salt, asPublic }
164
+ }
165
+
166
+ /**
167
+ * Build a VAPID JWT (RFC 8292 § 2) for one push endpoint.
168
+ * Exported for the deterministic dev check.
169
+ * @param {{endpoint: string, privateKeyJwk: object, subject?: string,
170
+ * lifetimeSeconds?: number, now?: number}} options
171
+ * @returns {string} compact JWS (`<header>.<claims>.<signature>`)
172
+ */
173
+ export function buildVapidJwt(options = {}) {
174
+ const {
175
+ endpoint,
176
+ privateKeyJwk,
177
+ subject = VAPID_SUBJECT,
178
+ lifetimeSeconds = VAPID_JWT_LIFETIME_SECONDS,
179
+ now = Date.now(),
180
+ } = options
181
+ if (typeof endpoint !== 'string') throw new Error('endpoint required')
182
+ const audience = new URL(endpoint).origin
183
+ const header = base64url(JSON.stringify({ typ: 'JWT', alg: 'ES256' }))
184
+ const claims = base64url(JSON.stringify({
185
+ aud: audience,
186
+ exp: Math.floor(now / 1000) + Math.max(1, Math.floor(Number(lifetimeSeconds) || VAPID_JWT_LIFETIME_SECONDS)),
187
+ sub: subject,
188
+ }))
189
+ const signingInput = `${header}.${claims}`
190
+ const signature = createSign('SHA256')
191
+ .update(signingInput)
192
+ .sign({ key: createPrivateKey({ key: privateKeyJwk, format: 'jwk' }), dsaEncoding: 'ieee-p1363' })
193
+ if (signature.length !== 64) throw new Error('unexpected ECDSA signature length')
194
+ return `${signingInput}.${base64url(signature)}`
195
+ }
196
+
197
+ function isLoopbackHost(hostname) {
198
+ return hostname === '127.0.0.1'
199
+ || hostname === 'localhost'
200
+ || hostname === '::1'
201
+ || hostname === '[::1]'
202
+ }
203
+
204
+ /**
205
+ * Push services this Host is willing to POST to. Browser PushSubscriptions come
206
+ * from a small set of provider families; accepting an arbitrary `https:` URL
207
+ * would turn the Host into a request proxy for whoever holds a pairing cookie
208
+ * (and let it read a bounded slice of the upstream response). Suffix matching
209
+ * keeps provider edge/regional hosts working. A self-hosted push relay can opt
210
+ * in through `allowedEndpointSuffixes` (the server maps
211
+ * `PA_REMOTE_MOBILE_PUSH_HOSTS` to it).
212
+ */
213
+ const PUSH_ENDPOINT_SUFFIXES = [
214
+ 'fcm.googleapis.com',
215
+ 'android.googleapis.com',
216
+ 'updates.push.services.mozilla.com',
217
+ 'push.services.mozilla.com',
218
+ 'notify.windows.com',
219
+ 'push.apple.com',
220
+ ]
221
+
222
+ function isPushServiceHost(hostname, extraSuffixes) {
223
+ const host = String(hostname ?? '').toLowerCase()
224
+ if (host.length === 0) return false
225
+ for (const suffix of [...PUSH_ENDPOINT_SUFFIXES, ...extraSuffixes]) {
226
+ if (host === suffix || host.endsWith(`.${suffix}`)) return true
227
+ }
228
+ return false
229
+ }
230
+
231
+ /** Normalize an operator-supplied suffix list (`fcm.googleapis.com,push.example`). */
232
+ function normalizeSuffixList(value) {
233
+ if (!Array.isArray(value)) return []
234
+ const out = []
235
+ for (const entry of value) {
236
+ if (typeof entry !== 'string') continue
237
+ const suffix = entry.trim().toLowerCase().replace(/^\.+/u, '')
238
+ if (suffix.length === 0 || suffix.length > 253) continue
239
+ if (!/^[a-z0-9.-]+$/u.test(suffix)) continue
240
+ if (!out.includes(suffix)) out.push(suffix)
241
+ }
242
+ return out
243
+ }
244
+
245
+ /**
246
+ * Validate + canonicalize one browser PushSubscription shape.
247
+ * @returns {{endpoint: string, keys: {p256dh: string, auth: string}}|null}
248
+ */
249
+ function normalizeSubscription(raw, allowInsecureLoopback, allowedEndpointSuffixes = []) {
250
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
251
+ if (typeof raw.endpoint !== 'string' || raw.endpoint.length === 0 || raw.endpoint.length > MAX_ENDPOINT_CHARS) {
252
+ return null
253
+ }
254
+ let url
255
+ try {
256
+ url = new URL(raw.endpoint)
257
+ } catch {
258
+ return null
259
+ }
260
+ const secure = url.protocol === 'https:'
261
+ const loopbackDev = allowInsecureLoopback && url.protocol === 'http:' && isLoopbackHost(url.hostname)
262
+ if (!secure && !loopbackDev) return null
263
+ if (!loopbackDev && !isPushServiceHost(url.hostname, allowedEndpointSuffixes)) return null
264
+ if (url.username.length > 0 || url.password.length > 0) return null
265
+ if (url.hash.length > 0) return null
266
+ if (raw.keys === null || typeof raw.keys !== 'object' || Array.isArray(raw.keys)) return null
267
+ const p256dh = decodeBase64url(raw.keys.p256dh, P256_PUBLIC_BYTES)
268
+ const auth = decodeBase64url(raw.keys.auth, AUTH_SECRET_BYTES)
269
+ if (p256dh === null || p256dh[0] !== 0x04 || auth === null) return null
270
+ return {
271
+ endpoint: url.toString(),
272
+ keys: { p256dh: base64url(p256dh), auth: base64url(auth) },
273
+ }
274
+ }
275
+
276
+ function generateVapid() {
277
+ const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
278
+ return {
279
+ publicKey: base64url(rawPublicFromKey(publicKey)),
280
+ privateKeyJwk: privateKey.export({ format: 'jwk' }),
281
+ privateKeyObject: privateKey,
282
+ }
283
+ }
284
+
285
+ /** Restore a VAPID pair from persisted state, or null when it is unusable. */
286
+ function restoreVapid(state) {
287
+ if (state === null || typeof state !== 'object' || Array.isArray(state)) return null
288
+ if (typeof state.publicKey !== 'string') return null
289
+ const raw = decodeBase64url(state.publicKey, P256_PUBLIC_BYTES)
290
+ if (raw === null || raw[0] !== 0x04) return null
291
+ const privateKeyJwk = state.privateKey
292
+ if (privateKeyJwk === null || typeof privateKeyJwk !== 'object' || Array.isArray(privateKeyJwk)) return null
293
+ if (privateKeyJwk.kty !== 'EC' || privateKeyJwk.crv !== 'P-256') return null
294
+ if (typeof privateKeyJwk.x !== 'string' || typeof privateKeyJwk.y !== 'string' || typeof privateKeyJwk.d !== 'string') {
295
+ return null
296
+ }
297
+ let privateKeyObject
298
+ try {
299
+ privateKeyObject = createPrivateKey({ key: privateKeyJwk, format: 'jwk' })
300
+ } catch {
301
+ return null
302
+ }
303
+ let derived
304
+ try {
305
+ derived = rawPublicFromKey(createPublicKey(privateKeyObject))
306
+ } catch {
307
+ return null
308
+ }
309
+ if (!derived.equals(raw)) return null
310
+ return { publicKey: base64url(derived), privateKeyJwk, privateKeyObject }
311
+ }
312
+
313
+ function copySubscription(item) {
314
+ return {
315
+ deviceId: item.deviceId,
316
+ endpoint: item.endpoint,
317
+ keys: { p256dh: item.keys.p256dh, auth: item.keys.auth },
318
+ createdAt: item.createdAt,
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Create the Web Push service used by the Host server.
324
+ *
325
+ * @param {object} [options]
326
+ * @param {object} [options.log] logger with optional `debug`/`warn`; keys and
327
+ * endpoints are never logged
328
+ * @param {object|null} [options.state] previously exported state (`vapid` +
329
+ * `subscriptions`, the `push` field of the pairing state file)
330
+ * @param {boolean} [options.allowInsecureLoopback] test-only: accept loopback
331
+ * `http:` endpoints (the Host server never sets this)
332
+ * @param {number} [options.maxSubscriptions] override the 16-subscription cap
333
+ * @param {string[]} [options.allowedEndpointSuffixes] extra push-service host
334
+ * suffixes (self-hosted relays); known provider hosts are always allowed
335
+ * @param {string} [options.subject] VAPID `sub` contact (defaults to the
336
+ * placeholder mailto; operators should set a real one)
337
+ */
338
+ export function createPushService(options = {}) {
339
+ const log = options.log ?? console
340
+ const allowInsecureLoopback = options.allowInsecureLoopback === true
341
+ const maxSubscriptions = Number.isInteger(options.maxSubscriptions) && options.maxSubscriptions > 0
342
+ ? options.maxSubscriptions
343
+ : MAX_SUBSCRIPTIONS
344
+ const allowedEndpointSuffixes = normalizeSuffixList(options.allowedEndpointSuffixes)
345
+ const vapidSubject = typeof options.subject === 'string' && options.subject.trim().length > 0
346
+ ? options.subject.trim().slice(0, 200)
347
+ : VAPID_SUBJECT
348
+
349
+ let vapid = restoreVapid(options.state?.vapid ?? null)
350
+ /** @type {Array<{deviceId: string, endpoint: string, keys: {p256dh: string, auth: string}, createdAt: number}>} */
351
+ let subscriptions = []
352
+
353
+ function importSubscriptions(list) {
354
+ subscriptions = []
355
+ if (!Array.isArray(list)) return
356
+ for (const item of list) {
357
+ if (subscriptions.length >= maxSubscriptions) break
358
+ if (item === null || typeof item !== 'object') continue
359
+ if (typeof item.deviceId !== 'string' || item.deviceId.length === 0 || item.deviceId.length > 64) continue
360
+ const normalized = normalizeSubscription(item, allowInsecureLoopback, allowedEndpointSuffixes)
361
+ if (normalized === null) continue
362
+ if (subscriptions.some((existing) => existing.endpoint === normalized.endpoint)) continue
363
+ subscriptions.push({
364
+ deviceId: item.deviceId,
365
+ endpoint: normalized.endpoint,
366
+ keys: normalized.keys,
367
+ createdAt: Number(item.createdAt) || Date.now(),
368
+ })
369
+ }
370
+ }
371
+
372
+ if (vapid === null) vapid = generateVapid()
373
+ importSubscriptions(options.state?.subscriptions)
374
+
375
+ function removeEndpoint(endpoint) {
376
+ const before = subscriptions.length
377
+ subscriptions = subscriptions.filter((item) => item.endpoint !== endpoint)
378
+ return before - subscriptions.length
379
+ }
380
+
381
+ function removeDevice(deviceId) {
382
+ if (typeof deviceId !== 'string' || deviceId.length === 0) return 0
383
+ const before = subscriptions.length
384
+ subscriptions = subscriptions.filter((item) => item.deviceId !== deviceId)
385
+ return before - subscriptions.length
386
+ }
387
+
388
+ /** Register (or refresh) one browser PushSubscription for a paired device. */
389
+ function addSubscription(deviceId, subscription) {
390
+ if (typeof deviceId !== 'string' || deviceId.length === 0 || deviceId.length > 64) {
391
+ return { ok: false, error: 'invalid-device' }
392
+ }
393
+ const normalized = normalizeSubscription(subscription, allowInsecureLoopback, allowedEndpointSuffixes)
394
+ if (normalized === null) return { ok: false, error: 'invalid-subscription' }
395
+ const existing = subscriptions.find((item) => item.endpoint === normalized.endpoint)
396
+ if (existing !== undefined) {
397
+ existing.deviceId = deviceId
398
+ existing.keys = normalized.keys
399
+ existing.createdAt = Date.now()
400
+ return { ok: true, subscription: copySubscription(existing) }
401
+ }
402
+ if (subscriptions.length >= maxSubscriptions) return { ok: false, error: 'too-many-subscriptions' }
403
+ const record = {
404
+ deviceId,
405
+ endpoint: normalized.endpoint,
406
+ keys: normalized.keys,
407
+ createdAt: Date.now(),
408
+ }
409
+ subscriptions.push(record)
410
+ return { ok: true, subscription: copySubscription(record) }
411
+ }
412
+
413
+ /**
414
+ * Remove a subscription by endpoint (string or `{ endpoint }`) or, for a bare
415
+ * device id, every subscription of that device. Returns how many were removed.
416
+ */
417
+ function removeSubscription(value) {
418
+ if (typeof value === 'string' && /^https?:\/\//u.test(value)) return removeEndpoint(value)
419
+ if (value !== null && typeof value === 'object' && typeof value.endpoint === 'string') {
420
+ return removeEndpoint(value.endpoint)
421
+ }
422
+ if (typeof value === 'string') return removeDevice(value)
423
+ return 0
424
+ }
425
+
426
+ /** Stored subscriptions (optionally for one device), keys included for sending. */
427
+ function listSubscriptions(deviceId) {
428
+ const source = typeof deviceId === 'string'
429
+ ? subscriptions.filter((item) => item.deviceId === deviceId)
430
+ : subscriptions
431
+ return source.map(copySubscription)
432
+ }
433
+
434
+ /** Drop subscriptions whose paired device no longer exists. */
435
+ function pruneToDevices(deviceIds) {
436
+ const known = deviceIds instanceof Set ? deviceIds : new Set(Array.isArray(deviceIds) ? deviceIds : [])
437
+ const before = subscriptions.length
438
+ subscriptions = subscriptions.filter((item) => known.has(item.deviceId))
439
+ return before - subscriptions.length
440
+ }
441
+
442
+ /**
443
+ * Encrypt + POST one notification. Never throws and never logs the endpoint or
444
+ * the payload.
445
+ * @returns {Promise<{ok: boolean, status: number, gone?: boolean, error?: string}>}
446
+ */
447
+ async function sendNotification(subscription, payloadObject) {
448
+ const normalized = normalizeSubscription(subscription, allowInsecureLoopback, allowedEndpointSuffixes)
449
+ if (normalized === null) return { ok: false, status: 0, error: 'invalid-subscription' }
450
+ let plaintext
451
+ try {
452
+ plaintext = Buffer.from(JSON.stringify(payloadObject ?? {}), 'utf8')
453
+ } catch {
454
+ return { ok: false, status: 0, error: 'invalid-payload' }
455
+ }
456
+ if (plaintext.length === 0 || plaintext.length > MAX_PAYLOAD_BYTES) {
457
+ return { ok: false, status: 0, error: 'payload-too-large' }
458
+ }
459
+ try {
460
+ const { body } = encryptPayload(normalized.keys.p256dh, normalized.keys.auth, plaintext)
461
+ const authorization = buildVapidJwt({ endpoint: normalized.endpoint, privateKeyJwk: vapid.privateKeyJwk, subject: vapidSubject })
462
+ const response = await fetch(normalized.endpoint, {
463
+ method: 'POST',
464
+ headers: {
465
+ TTL: String(PUSH_TTL_SECONDS),
466
+ 'Content-Encoding': 'aes128gcm',
467
+ 'Content-Type': 'application/octet-stream',
468
+ Authorization: `WebPush ${authorization}`,
469
+ // Not required for aes128gcm but harmless and expected by some old
470
+ // gateways (RFC 8292 § 2.1 legacy VAPID header form).
471
+ // RFC 8292 legacy VAPID header form: FCM requires the application
472
+ // server key under `p256ecdsa` (not the subscription's `p256dh`).
473
+ 'Crypto-Key': `p256ecdsa=${vapid.publicKey}`,
474
+ },
475
+ body,
476
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
477
+ })
478
+ const status = response.status
479
+ // The (tiny) error body names the push-service failure, e.g.
480
+ // UnauthorizedRegistration; it is bounded and never logged.
481
+ const detail = await response.text().catch(() => '')
482
+ if (status === 201 || status === 202) return { ok: true, status }
483
+ if (status === 404 || status === 410) {
484
+ removeEndpoint(normalized.endpoint)
485
+ return { ok: false, gone: true, status }
486
+ }
487
+ return { ok: false, status, detail: detail.slice(0, 300) }
488
+ } catch (error) {
489
+ log.debug?.(`remote-mobile: push send failed (${error?.name ?? 'Error'})`)
490
+ return { ok: false, status: 0, error: 'network' }
491
+ }
492
+ }
493
+
494
+ function exportState() {
495
+ return {
496
+ vapid: { publicKey: vapid.publicKey, privateKey: vapid.privateKeyJwk },
497
+ subscriptions: subscriptions.map(copySubscription),
498
+ }
499
+ }
500
+
501
+ function importState(state) {
502
+ if (state === null || typeof state !== 'object' || Array.isArray(state)) return
503
+ const restored = restoreVapid(state.vapid ?? null)
504
+ if (restored !== null) vapid = restored
505
+ importSubscriptions(state.subscriptions)
506
+ if (vapid === null) vapid = generateVapid()
507
+ }
508
+
509
+ return {
510
+ /** base64url raw uncompressed P-256 point for `applicationServerKey`. */
511
+ publicKey: () => vapid.publicKey,
512
+ addSubscription,
513
+ removeSubscription,
514
+ removeDevice,
515
+ subscriptions: listSubscriptions,
516
+ count: () => subscriptions.length,
517
+ hasSubscriptions: () => subscriptions.length > 0,
518
+ pruneToDevices,
519
+ sendNotification,
520
+ /** JWT for one endpoint (exposed for diagnostics; sendNotification uses it). */
521
+ buildVapidJwt: (endpoint, now = Date.now()) => buildVapidJwt({
522
+ endpoint,
523
+ privateKeyJwk: vapid.privateKeyJwk,
524
+ now,
525
+ }),
526
+ exportState,
527
+ importState,
528
+ }
529
+ }
530
+
531
+
package/qr.js ADDED
@@ -0,0 +1,49 @@
1
+ // QR rendering for the pairing URL. Wraps the vendored MIT encoder so the
2
+ // server can return a compact, crisp SVG without any network dependency.
3
+ import qrcode from './vendor/qrcode.js'
4
+
5
+ function escapeXml(value) {
6
+ return String(value)
7
+ .replaceAll('&', '&amp;')
8
+ .replaceAll('<', '&lt;')
9
+ .replaceAll('>', '&gt;')
10
+ .replaceAll('"', '&quot;')
11
+ }
12
+
13
+ /**
14
+ * Render `text` as a QR code SVG string.
15
+ * @param {string} text
16
+ * @param {{ cellSize?: number, margin?: number, dark?: string, light?: string }} [options]
17
+ * @returns {string}
18
+ */
19
+ export function qrSvg(text, options = {}) {
20
+ const cellSize = options.cellSize ?? 6
21
+ const margin = options.margin ?? 2
22
+ const dark = options.dark ?? '#0B0D12'
23
+ const light = options.light ?? '#FFFFFF'
24
+ const code = qrcode(0, 'M')
25
+ code.addData(text, 'Byte')
26
+ code.make()
27
+ const count = code.getModuleCount()
28
+ const size = count * cellSize + margin * 2
29
+ const parts = []
30
+ for (let row = 0; row < count; row += 1) {
31
+ let col = 0
32
+ while (col < count) {
33
+ if (!code.isDark(row, col)) {
34
+ col += 1
35
+ continue
36
+ }
37
+ let run = 1
38
+ while (col + run < count && code.isDark(row, col + run)) run += 1
39
+ parts.push(`M${margin + col * cellSize},${margin + row * cellSize}h${run * cellSize}v${cellSize}h-${run * cellSize}z`)
40
+ col += run
41
+ }
42
+ }
43
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" shape-rendering="crispEdges" role="img" aria-label="Pairing QR code"><rect width="${size}" height="${size}" fill="${escapeXml(light)}"/><path d="${parts.join('')}" fill="${escapeXml(dark)}"/></svg>`
44
+ }
45
+
46
+ /** A data URI form for embedding in an `<img>` without inlining raw SVG. */
47
+ export function qrDataUri(text, options = {}) {
48
+ return `data:image/svg+xml;base64,${Buffer.from(qrSvg(text, options), 'utf8').toString('base64')}`
49
+ }