@classytic/notifications 2.7.0 → 2.9.0

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.
@@ -0,0 +1,1004 @@
1
+ import { n as NotificationError, r as PermanentDeliveryError } from "../errors-CsQZKfec.mjs";
2
+ import { createHash, createPrivateKey, sign } from "node:crypto";
3
+ import http2 from "node:http2";
4
+
5
+ //#region src/push/aps.ts
6
+ /** Whether a message shows anything (title or body). Data-only pushes do not. */
7
+ function isVisible(message) {
8
+ return Boolean(message.title) || Boolean(message.body);
9
+ }
10
+ /** The effective interruption level after the entitlement check. */
11
+ function effectiveLevel(level, options) {
12
+ if (level === "critical" && !options.allowCriticalAlerts) return "time-sensitive";
13
+ return level;
14
+ }
15
+ /**
16
+ * Build `aps` for a message. Visible pushes get an `alert` and a sound (`default` unless the
17
+ * message says otherwise; `null` = silent). Data-only pushes get only `content-available: 1`.
18
+ */
19
+ function buildAps(message, options) {
20
+ const visible = isVisible(message);
21
+ const level = effectiveLevel(message.interruptionLevel, options);
22
+ const aps = {};
23
+ if (visible) {
24
+ aps.alert = {
25
+ ...message.title ? { title: message.title } : {},
26
+ ...message.body ? { body: message.body } : {}
27
+ };
28
+ if (message.sound !== null) {
29
+ const name = message.sound ?? "default";
30
+ aps.sound = level === "critical" ? {
31
+ critical: 1,
32
+ name,
33
+ volume: 1
34
+ } : name;
35
+ }
36
+ if (level) aps["interruption-level"] = level;
37
+ if (message.imageUrl) aps["mutable-content"] = 1;
38
+ }
39
+ if (message.contentAvailable || !visible) aps["content-available"] = 1;
40
+ if (message.threadId) aps["thread-id"] = message.threadId;
41
+ if (message.badge !== void 0) aps.badge = message.badge;
42
+ if (message.category) aps.category = message.category;
43
+ return aps;
44
+ }
45
+ /** APNs header values derived from the message (shared with FCM's `apns.headers`). */
46
+ function apnsHeaderValues(message, nowMs) {
47
+ const visible = isVisible(message);
48
+ const priority = !visible ? "5" : message.priority === "normal" ? "5" : "10";
49
+ return {
50
+ pushType: visible ? "alert" : "background",
51
+ priority,
52
+ ...message.ttlSeconds !== void 0 ? { expiration: message.ttlSeconds === 0 ? "0" : String(Math.floor(nowMs / 1e3) + message.ttlSeconds) } : {}
53
+ };
54
+ }
55
+ /** `apns-collapse-id` / FCM collapse keys are capped at 64 bytes; longer is a caller bug, not truncated. */
56
+ function collapseKeyTooLong(key) {
57
+ return key !== void 0 && Buffer.byteLength(key, "utf8") > 64;
58
+ }
59
+
60
+ //#endregion
61
+ //#region src/push/errors.ts
62
+ /**
63
+ * Push errors. Every message here is built from provider STATUS fields only (HTTP status, the
64
+ * provider's reason code, a token suffix): never key material, never a full device token, never
65
+ * payload text. A provider's own error body is parsed for its reason code and then dropped,
66
+ * because FCM and APNs bodies may echo the token.
67
+ *
68
+ * @module @classytic/notifications/push
69
+ */
70
+ /**
71
+ * The device token will never work again. Permanent (`retryable: false`): the service does not
72
+ * retry it, and the host should delete the device row (the providers' `onInvalidToken` hook and
73
+ * arc-notifications' device channel do).
74
+ */
75
+ var InvalidPushTokenError = class extends PermanentDeliveryError {
76
+ reason;
77
+ provider;
78
+ /** HTTP status the provider answered. */
79
+ status;
80
+ /** Last 6 characters of the token: enough to correlate, useless to an attacker. */
81
+ tokenSuffix;
82
+ /** Structural marker (survives bundling / duplicate copies of this package). */
83
+ invalidToken = true;
84
+ constructor(provider, reason, status, tokenSuffix) {
85
+ super(`${provider} push: device token is ${reason} (status ${status}, token …${tokenSuffix})`, { code: "PUSH_TOKEN_INVALID" });
86
+ this.name = "InvalidPushTokenError";
87
+ this.reason = reason;
88
+ this.provider = provider;
89
+ this.status = status;
90
+ this.tokenSuffix = tokenSuffix;
91
+ }
92
+ };
93
+ /**
94
+ * A failure no retry fixes that is NOT about the token: a payload the provider rejects, a
95
+ * misconfigured topic or sender, a platform with no provider. The device row is kept.
96
+ */
97
+ var PushRejectedError = class extends PermanentDeliveryError {
98
+ provider;
99
+ status;
100
+ /** The provider's reason code (`BadTopic`, `INVALID_ARGUMENT`, ...), or a local one. */
101
+ reason;
102
+ constructor(provider, status, reason, detail) {
103
+ super(`${provider} push rejected: ${status} ${reason}${detail ? ` (${detail})` : ""}`, { code: "PUSH_REJECTED" });
104
+ this.name = "PushRejectedError";
105
+ this.provider = provider;
106
+ this.status = status;
107
+ this.reason = reason;
108
+ }
109
+ };
110
+ /**
111
+ * Credentials are missing, malformed, or refused by the provider. Permanent: retrying with the
112
+ * same credentials cannot succeed (a rotated credential is picked up on the next send anyway).
113
+ * The message names FIELDS, never values.
114
+ */
115
+ var PushCredentialsError = class extends PermanentDeliveryError {
116
+ provider;
117
+ constructor(provider, message) {
118
+ super(`${provider} credentials: ${message}`, { code: "PUSH_CREDENTIALS" });
119
+ this.name = "PushCredentialsError";
120
+ this.provider = provider;
121
+ }
122
+ };
123
+ /**
124
+ * A transient failure (429, 5xx, timeout, connection reset). Retryable; `retryAfterMs` carries the
125
+ * provider's `Retry-After`, which the service's retry loop honours (`retryAfterHint`).
126
+ */
127
+ var TransientPushError = class extends NotificationError {
128
+ retryable = true;
129
+ provider;
130
+ /** HTTP status, or 0 for a network-level failure. */
131
+ status;
132
+ reason;
133
+ retryAfterMs;
134
+ constructor(provider, status, reason, options) {
135
+ super(`${provider} push failed (retryable): ${status || "network"} ${reason}` + (options?.retryAfterMs !== void 0 ? ` (retry after ${options.retryAfterMs} ms)` : ""), {
136
+ code: "PUSH_TRANSIENT",
137
+ ...options?.cause ? { cause: options.cause } : {}
138
+ });
139
+ this.name = "TransientPushError";
140
+ this.provider = provider;
141
+ this.status = status;
142
+ this.reason = reason;
143
+ if (options?.retryAfterMs !== void 0) this.retryAfterMs = options.retryAfterMs;
144
+ }
145
+ };
146
+ /** Structural check: is this an invalid-token error (from any copy of this package)? */
147
+ function isInvalidPushTokenError(err) {
148
+ return err !== null && typeof err === "object" && (err.invalidToken === true || err.code === "PUSH_TOKEN_INVALID");
149
+ }
150
+
151
+ //#endregion
152
+ //#region src/push/jwt.ts
153
+ /**
154
+ * Compact JWS signing over `node:crypto` (no library): RS256 for Google's OAuth2 service-account
155
+ * grant, ES256 for APNs provider tokens. Only signing lives here; providers never verify tokens.
156
+ *
157
+ * @module @classytic/notifications/push
158
+ */
159
+ const b64url = (input) => Buffer.from(input).toString("base64url");
160
+ /**
161
+ * Sign `header.claims` with `key`. ES256 signatures are emitted in the JOSE `r||s` form
162
+ * (`ieee-p1363`), which is what Apple requires; DER would be rejected.
163
+ */
164
+ function signJwt(alg, key, claims, headerExtra = {}) {
165
+ const header = b64url(JSON.stringify({
166
+ alg,
167
+ ...headerExtra
168
+ }));
169
+ const body = b64url(JSON.stringify(claims));
170
+ const input = Buffer.from(`${header}.${body}`);
171
+ const signature = alg === "ES256" ? sign("sha256", input, {
172
+ key,
173
+ dsaEncoding: "ieee-p1363"
174
+ }) : sign("sha256", input, key);
175
+ return `${header}.${body}.${b64url(signature)}`;
176
+ }
177
+ /** Short, non-reversible fingerprint (hex) of any string: for cache keys and safe log fields. */
178
+ function fingerprint(value, length = 16) {
179
+ return createHash("sha256").update(value).digest("hex").slice(0, length);
180
+ }
181
+
182
+ //#endregion
183
+ //#region src/push/credentials.ts
184
+ /**
185
+ * Push credentials: shapes, validation, and the per-provider resolver.
186
+ *
187
+ * Providers never read the environment. The host passes `credentials` as a value or a FUNCTION;
188
+ * the function is called on every send (make it cheap: return a cached object) and its result is
189
+ * compared by `version` (or, without one, by a fingerprint of the fields). A change re-validates,
190
+ * re-imports the key, and drops cached access/provider tokens, so a rotated key applies on the
191
+ * next send without a restart.
192
+ *
193
+ * Validation errors name FIELDS, never values. Key material lives only in memory: the PEM string
194
+ * the source returned and the `KeyObject` imported from it.
195
+ *
196
+ * @module @classytic/notifications/push
197
+ */
198
+ const GOOGLE_TOKEN_URI = "https://oauth2.googleapis.com/token";
199
+ const APPLE_ID = /^[A-Z0-9]{10}$/;
200
+ const BUNDLE_ID = /^[A-Za-z0-9.-]{1,155}$/;
201
+ const EMAIL = /^[^\s@]+@[^\s@]+$/;
202
+ const PROJECT_ID = /^[a-z0-9][a-z0-9-:.]{3,62}$/;
203
+ function str(obj, ...keys) {
204
+ for (const key of keys) {
205
+ const value = obj[key];
206
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
207
+ }
208
+ }
209
+ /** `\n` escapes (an env var or a JSON copy) become real newlines; surrounding space is dropped. */
210
+ function normalizePem(pem) {
211
+ return pem.replace(/\\n/g, "\n").trim();
212
+ }
213
+ function importKey(provider, pem) {
214
+ try {
215
+ return createPrivateKey(normalizePem(pem));
216
+ } catch {
217
+ throw new PushCredentialsError(provider, "privateKey is not a readable PEM private key");
218
+ }
219
+ }
220
+ /**
221
+ * Accept a Google service-account file in any of the forms hosts store it: the JSON object
222
+ * (snake_case as downloaded, or camelCase), its JSON text, or the base64 of that text.
223
+ */
224
+ function parseFcmServiceAccount(input, version) {
225
+ let obj;
226
+ if (typeof input === "string") {
227
+ const text = input.trim().startsWith("{") ? input : Buffer.from(input.trim(), "base64").toString("utf8");
228
+ try {
229
+ obj = JSON.parse(text);
230
+ } catch {
231
+ throw new PushCredentialsError("fcm", "service account is neither JSON nor base64 of JSON");
232
+ }
233
+ } else obj = input;
234
+ if (obj === null || typeof obj !== "object") throw new PushCredentialsError("fcm", "service account must be an object");
235
+ const projectId = str(obj, "projectId", "project_id");
236
+ const clientEmail = str(obj, "clientEmail", "client_email");
237
+ const privateKey = str(obj, "privateKey", "private_key");
238
+ const privateKeyId = str(obj, "privateKeyId", "private_key_id");
239
+ const tokenUri = str(obj, "tokenUri", "token_uri");
240
+ const v = version ?? str(obj, "version");
241
+ return validateFcmCredentials({
242
+ projectId: projectId ?? "",
243
+ clientEmail: clientEmail ?? "",
244
+ privateKey: privateKey ?? "",
245
+ ...privateKeyId ? { privateKeyId } : {},
246
+ ...tokenUri ? { tokenUri } : {},
247
+ ...v ? { version: v } : {}
248
+ });
249
+ }
250
+ /** Check shape and key type; returns a normalized copy. Throws {@link PushCredentialsError}. */
251
+ function validateFcmCredentials(creds) {
252
+ if (creds === null || typeof creds !== "object") throw new PushCredentialsError("fcm", "credentials must be an object");
253
+ const missing = [
254
+ "projectId",
255
+ "clientEmail",
256
+ "privateKey"
257
+ ].filter((k) => typeof creds[k] !== "string" || creds[k].trim() === "");
258
+ if (missing.length) throw new PushCredentialsError("fcm", `missing ${missing.join(", ")}`);
259
+ if (!PROJECT_ID.test(creds.projectId)) throw new PushCredentialsError("fcm", "projectId is malformed");
260
+ if (!EMAIL.test(creds.clientEmail)) throw new PushCredentialsError("fcm", "clientEmail is malformed");
261
+ if (creds.tokenUri !== void 0 && !/^https?:\/\//.test(creds.tokenUri)) throw new PushCredentialsError("fcm", "tokenUri must be an http(s) URL");
262
+ if (importKey("fcm", creds.privateKey).asymmetricKeyType !== "rsa") throw new PushCredentialsError("fcm", "privateKey must be an RSA key (service-account private_key)");
263
+ return {
264
+ ...creds,
265
+ privateKey: normalizePem(creds.privateKey)
266
+ };
267
+ }
268
+ /** Check shape and key type (EC P-256); returns a normalized copy. Throws {@link PushCredentialsError}. */
269
+ function validateApnsCredentials(creds) {
270
+ if (creds === null || typeof creds !== "object") throw new PushCredentialsError("apns", "credentials must be an object");
271
+ const missing = [
272
+ "keyId",
273
+ "teamId",
274
+ "privateKey",
275
+ "bundleId"
276
+ ].filter((k) => typeof creds[k] !== "string" || creds[k].trim() === "");
277
+ if (missing.length) throw new PushCredentialsError("apns", `missing ${missing.join(", ")}`);
278
+ if (!APPLE_ID.test(creds.keyId)) throw new PushCredentialsError("apns", "keyId must be 10 characters (A-Z, 0-9)");
279
+ if (!APPLE_ID.test(creds.teamId)) throw new PushCredentialsError("apns", "teamId must be 10 characters (A-Z, 0-9)");
280
+ if (!BUNDLE_ID.test(creds.bundleId)) throw new PushCredentialsError("apns", "bundleId is malformed");
281
+ if (creds.environment !== void 0 && creds.environment !== "production" && creds.environment !== "sandbox") throw new PushCredentialsError("apns", "environment must be \"production\" or \"sandbox\"");
282
+ const key = importKey("apns", creds.privateKey);
283
+ if (key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") throw new PushCredentialsError("apns", "privateKey must be an EC P-256 key (the .p8 file)");
284
+ return {
285
+ ...creds,
286
+ privateKey: normalizePem(creds.privateKey)
287
+ };
288
+ }
289
+ /** A stable cache key for a credential value: its `version`, else a hash of every field. */
290
+ function credentialsFingerprint(creds) {
291
+ const version = creds.version;
292
+ if (typeof version === "string" && version !== "") return `v:${version}`;
293
+ const entries = Object.entries(creds).sort(([a], [b]) => a < b ? -1 : 1);
294
+ return `h:${fingerprint(JSON.stringify(entries), 32)}`;
295
+ }
296
+ /**
297
+ * Resolve-per-send, derive-on-change. `onRotate` runs when the fingerprint moves (drop cached
298
+ * tokens, reconnect). A source that throws something other than a credentials error (the
299
+ * integrations store is down) surfaces as retryable.
300
+ */
301
+ function createCredentialResolver(provider, source, validate, derive, onRotate) {
302
+ if (source === null || source === void 0) throw new PushCredentialsError(provider, "credentials option is required");
303
+ let current;
304
+ return { async resolve() {
305
+ let raw;
306
+ try {
307
+ raw = typeof source === "function" ? await source() : source;
308
+ } catch (err) {
309
+ if (err instanceof PushCredentialsError || err?.retryable === false) throw err;
310
+ throw new TransientPushError(provider, 0, "credentials-unavailable", { ...err instanceof Error ? { cause: err } : {} });
311
+ }
312
+ if (raw === null || typeof raw !== "object") throw new PushCredentialsError(provider, "credentials source returned nothing");
313
+ const fp = credentialsFingerprint(raw);
314
+ if (current && current.fingerprint === fp) return current;
315
+ const creds = validate(raw);
316
+ const next = {
317
+ creds,
318
+ derived: derive(creds),
319
+ fingerprint: fp
320
+ };
321
+ const previous = current;
322
+ current = next;
323
+ onRotate?.(next, previous);
324
+ return next;
325
+ } };
326
+ }
327
+
328
+ //#endregion
329
+ //#region src/push/internal.ts
330
+ /** Run the dead-token hook, swallowing its failure (cleanup must not change the outcome). */
331
+ async function reportInvalid(handler, token, reason) {
332
+ if (!handler) return;
333
+ try {
334
+ await handler(token, reason);
335
+ } catch {}
336
+ }
337
+ /** The redacted event fields for a failed send, from the typed error. */
338
+ function failureEvent(err) {
339
+ if (err instanceof InvalidPushTokenError) return {
340
+ outcome: "invalid-token",
341
+ status: err.status,
342
+ reason: err.reason
343
+ };
344
+ if (err instanceof PushCredentialsError) return {
345
+ outcome: "credentials",
346
+ status: 0,
347
+ reason: "credentials"
348
+ };
349
+ if (err instanceof PushRejectedError) return {
350
+ outcome: "rejected",
351
+ status: err.status,
352
+ reason: err.reason
353
+ };
354
+ if (err instanceof TransientPushError) return {
355
+ outcome: "transient",
356
+ status: err.status,
357
+ reason: err.reason,
358
+ ...err.retryAfterMs !== void 0 ? { retryAfterMs: err.retryAfterMs } : {}
359
+ };
360
+ return {
361
+ outcome: "transient",
362
+ status: 0,
363
+ reason: "unknown"
364
+ };
365
+ }
366
+ /** Last 6 characters, for messages and logs. */
367
+ function tokenSuffix(token) {
368
+ return token.length <= 6 ? "***" : token.slice(-6);
369
+ }
370
+ /** Non-reversible token hash for joining log rows. */
371
+ function tokenHash(token) {
372
+ return fingerprint(token, 16);
373
+ }
374
+ /**
375
+ * `Retry-After` as milliseconds: delta-seconds or an HTTP-date. Unparseable or negative values
376
+ * are ignored. Capped at one hour so a hostile or broken header cannot park a queue for days.
377
+ */
378
+ function parseRetryAfter(value, now) {
379
+ const raw = Array.isArray(value) ? value[0] : value;
380
+ if (raw === void 0 || raw === null || raw === "") return void 0;
381
+ const trimmed = String(raw).trim();
382
+ let ms;
383
+ if (/^\d+$/.test(trimmed)) ms = Number(trimmed) * 1e3;
384
+ else {
385
+ const at = Date.parse(trimmed);
386
+ if (Number.isNaN(at)) return void 0;
387
+ ms = at - now;
388
+ }
389
+ if (!Number.isFinite(ms) || ms < 0) return void 0;
390
+ return Math.min(ms, 36e5);
391
+ }
392
+ /** A counting semaphore: at most `limit` sends in flight per provider instance. */
393
+ function createGate(limit) {
394
+ if (!Number.isInteger(limit) || limit < 1) throw new Error(`push: maxConcurrency must be a positive integer`);
395
+ let active = 0;
396
+ const waiting = [];
397
+ return async (fn) => {
398
+ if (active >= limit) await new Promise((resolve) => waiting.push(resolve));
399
+ active++;
400
+ try {
401
+ return await fn();
402
+ } finally {
403
+ active--;
404
+ waiting.shift()?.();
405
+ }
406
+ };
407
+ }
408
+ /**
409
+ * Per-process back-pressure after a 429 / 503 with `Retry-After`: until the deadline every send
410
+ * fails fast as retryable with the remaining wait, instead of hammering a provider that already
411
+ * said "not now". Not a circuit breaker: it never opens on its own judgement, only on the
412
+ * provider's explicit instruction, and it closes by itself when the time passes.
413
+ */
414
+ function createCooldown(now) {
415
+ let until = 0;
416
+ return {
417
+ /** Remaining ms of an active cool-down, or 0. */
418
+ remaining() {
419
+ const left = until - now();
420
+ return left > 0 ? left : 0;
421
+ },
422
+ hold(ms) {
423
+ until = Math.max(until, now() + ms);
424
+ }
425
+ };
426
+ }
427
+
428
+ //#endregion
429
+ //#region src/push/fcm.ts
430
+ const FCM_ENDPOINT = "https://fcm.googleapis.com";
431
+ const FCM_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
432
+ /** FCM data rules: string values only, no reserved keys. */
433
+ const RESERVED_DATA_KEY = /^(from|notification|message_type)$|^(google|gcm)/i;
434
+ const TOKEN_SHAPE = /^[^\s]{1,4096}$/;
435
+ /** Build the FCM v1 `message` object. Exported for tests and for hosts that inspect payloads. */
436
+ function buildFcmMessage(message, options, nowMs) {
437
+ const visible = isVisible(message);
438
+ const headers = apnsHeaderValues(message, nowMs);
439
+ const android = { priority: (message.priority ?? (visible ? "high" : "normal")) === "high" ? "HIGH" : "NORMAL" };
440
+ if (message.ttlSeconds !== void 0) android.ttl = `${message.ttlSeconds}s`;
441
+ if (message.collapseKey) android.collapseKey = message.collapseKey;
442
+ if (visible) {
443
+ const notification = {};
444
+ if (message.collapseKey) notification.tag = message.collapseKey;
445
+ if (message.badge !== void 0) notification.notificationCount = message.badge;
446
+ if (message.channelId) notification.channelId = message.channelId;
447
+ if (message.sound !== null) notification.sound = message.sound ?? "default";
448
+ if (message.category) notification.clickAction = message.category;
449
+ if (Object.keys(notification).length) android.notification = notification;
450
+ }
451
+ const apnsHeaders = {
452
+ "apns-priority": headers.priority,
453
+ "apns-push-type": headers.pushType,
454
+ ...message.collapseKey ? { "apns-collapse-id": message.collapseKey } : {},
455
+ ...headers.expiration !== void 0 ? { "apns-expiration": headers.expiration } : {}
456
+ };
457
+ return {
458
+ token: message.token,
459
+ ...visible ? { notification: {
460
+ ...message.title ? { title: message.title } : {},
461
+ ...message.body ? { body: message.body } : {},
462
+ ...message.imageUrl ? { image: message.imageUrl } : {}
463
+ } } : {},
464
+ ...message.data && Object.keys(message.data).length ? { data: message.data } : {},
465
+ android,
466
+ apns: {
467
+ headers: apnsHeaders,
468
+ payload: { aps: buildAps(message, options) }
469
+ }
470
+ };
471
+ }
472
+ function checkMessage(message) {
473
+ if (typeof message.token !== "string" || !TOKEN_SHAPE.test(message.token)) throw new PushRejectedError("fcm", 0, "invalid-token-format", "token must be a non-empty string without spaces");
474
+ if (collapseKeyTooLong(message.collapseKey)) throw new PushRejectedError("fcm", 0, "collapse-key-too-long", "collapseKey exceeds 64 bytes");
475
+ for (const [key, value] of Object.entries(message.data ?? {})) {
476
+ if (typeof value !== "string") throw new PushRejectedError("fcm", 0, "invalid-data", `data.${key} must be a string`);
477
+ if (RESERVED_DATA_KEY.test(key)) throw new PushRejectedError("fcm", 0, "invalid-data", `data.${key} is reserved by FCM`);
478
+ }
479
+ }
480
+ /** Pull the codes out of an FCM error body; the free-text message is inspected, never kept. */
481
+ function parseFcmError(text) {
482
+ try {
483
+ const err = JSON.parse(text).error ?? {};
484
+ let errorCode;
485
+ let tokenNamed = typeof err.message === "string" && /registration token/i.test(err.message);
486
+ for (const detail of err.details ?? []) {
487
+ if (typeof detail.errorCode === "string") errorCode = detail.errorCode;
488
+ if (detail.fieldViolations?.some((v) => v.field === "message.token")) tokenNamed = true;
489
+ }
490
+ const perDevice = typeof err.message === "string" && /device/i.test(err.message);
491
+ return {
492
+ ...err.status ? { status: err.status } : {},
493
+ ...errorCode ? { errorCode } : {},
494
+ tokenNamed,
495
+ perDevice
496
+ };
497
+ } catch {
498
+ return {
499
+ tokenNamed: false,
500
+ perDevice: false
501
+ };
502
+ }
503
+ }
504
+ function fcmProvider(options) {
505
+ const now = options.now ?? Date.now;
506
+ const doFetch = options.fetch ?? globalThis.fetch;
507
+ if (typeof doFetch !== "function") throw new Error("fcmProvider: no fetch implementation (Node 18+ or options.fetch)");
508
+ const endpoint = (options.endpoint ?? "https://fcm.googleapis.com").replace(/\/+$/, "");
509
+ const timeoutMs = options.timeoutMs ?? 1e4;
510
+ const gate = createGate(options.maxConcurrency ?? 100);
511
+ const cooldown = createCooldown(now);
512
+ let access;
513
+ let refreshing;
514
+ const resolver = createCredentialResolver("fcm", options.credentials, validateFcmCredentials, (creds) => importKey("fcm", creds.privateKey), () => {
515
+ access = void 0;
516
+ });
517
+ const emit = (event, token) => {
518
+ if (!options.onDelivery) return;
519
+ try {
520
+ options.onDelivery({
521
+ provider: "fcm",
522
+ tokenSuffix: tokenSuffix(token),
523
+ tokenHash: tokenHash(token),
524
+ ...event
525
+ });
526
+ } catch {}
527
+ };
528
+ async function request(url, init) {
529
+ try {
530
+ return await doFetch(url, {
531
+ ...init,
532
+ signal: AbortSignal.timeout(timeoutMs)
533
+ });
534
+ } catch (err) {
535
+ const timedOut = err?.name === "TimeoutError";
536
+ throw new TransientPushError("fcm", 0, timedOut ? "timeout" : "network", { ...err instanceof Error ? { cause: err } : {} });
537
+ }
538
+ }
539
+ async function fetchAccessToken(resolved) {
540
+ const { creds, derived: key } = resolved;
541
+ const tokenUri = creds.tokenUri ?? "https://oauth2.googleapis.com/token";
542
+ const iat = Math.floor(now() / 1e3);
543
+ const assertion = signJwt("RS256", key, {
544
+ iss: creds.clientEmail,
545
+ scope: FCM_SCOPE,
546
+ aud: tokenUri,
547
+ iat,
548
+ exp: iat + 3600
549
+ }, {
550
+ typ: "JWT",
551
+ ...creds.privateKeyId ? { kid: creds.privateKeyId } : {}
552
+ });
553
+ const res = await request(tokenUri, {
554
+ method: "POST",
555
+ headers: { "content-type": "application/x-www-form-urlencoded" },
556
+ body: new URLSearchParams({
557
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
558
+ assertion
559
+ }).toString()
560
+ });
561
+ const text = await res.text();
562
+ if (!res.ok) {
563
+ if (res.status === 429 || res.status >= 500) {
564
+ const retryAfterMs = parseRetryAfter(res.headers.get("retry-after"), now());
565
+ throw new TransientPushError("fcm", res.status, "token-endpoint", retryAfterMs !== void 0 ? { retryAfterMs } : {});
566
+ }
567
+ let code = "refused";
568
+ try {
569
+ code = String(JSON.parse(text).error ?? code);
570
+ } catch {}
571
+ throw new PushCredentialsError("fcm", `token endpoint refused the service account (${res.status} ${code})`);
572
+ }
573
+ let parsed;
574
+ try {
575
+ parsed = JSON.parse(text);
576
+ } catch {
577
+ throw new TransientPushError("fcm", res.status, "token-endpoint-malformed");
578
+ }
579
+ if (typeof parsed.access_token !== "string" || parsed.access_token === "") throw new TransientPushError("fcm", res.status, "token-endpoint-malformed");
580
+ const expiresIn = typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : 3600;
581
+ return {
582
+ token: parsed.access_token,
583
+ expiresAt: now() + expiresIn * 1e3,
584
+ fingerprint: resolved.fingerprint
585
+ };
586
+ }
587
+ /** Cached token, or ONE shared refresh for every concurrent caller. */
588
+ async function accessToken(resolved, force) {
589
+ if (!force && access && access.fingerprint === resolved.fingerprint && now() < access.expiresAt - 6e4) return access.token;
590
+ if (refreshing && refreshing.fingerprint === resolved.fingerprint) return (await refreshing.promise).token;
591
+ const promise = fetchAccessToken(resolved);
592
+ const entry = {
593
+ fingerprint: resolved.fingerprint,
594
+ promise
595
+ };
596
+ refreshing = entry;
597
+ try {
598
+ const fresh = await promise;
599
+ access = fresh;
600
+ return fresh.token;
601
+ } finally {
602
+ if (refreshing === entry) refreshing = void 0;
603
+ }
604
+ }
605
+ async function invalid(token, reason, status) {
606
+ await reportInvalid(options.onInvalidToken, token, reason);
607
+ throw new InvalidPushTokenError("fcm", reason, status, tokenSuffix(token));
608
+ }
609
+ async function sendOnce(message, started) {
610
+ const waitMs = cooldown.remaining();
611
+ if (waitMs > 0) throw new TransientPushError("fcm", 429, "cooling-down", { retryAfterMs: waitMs });
612
+ const resolved = await resolver.resolve();
613
+ const body = JSON.stringify({
614
+ ...options.validateOnly ? { validate_only: true } : {},
615
+ message: buildFcmMessage(message, options, now())
616
+ });
617
+ const url = `${endpoint}/v1/projects/${encodeURIComponent(resolved.creds.projectId)}/messages:send`;
618
+ for (let attempt = 0; attempt < 2; attempt++) {
619
+ const res = await request(url, {
620
+ method: "POST",
621
+ headers: {
622
+ authorization: `Bearer ${await accessToken(resolved, attempt > 0)}`,
623
+ "content-type": "application/json; charset=utf-8"
624
+ },
625
+ body
626
+ });
627
+ const text = await res.text();
628
+ if (res.ok) {
629
+ let messageId = "fcm";
630
+ try {
631
+ messageId = String(JSON.parse(text).name ?? messageId);
632
+ } catch {}
633
+ emit({
634
+ outcome: "sent",
635
+ status: res.status,
636
+ messageId,
637
+ latencyMs: now() - started,
638
+ ...platformOf(message)
639
+ }, message.token);
640
+ return { messageId };
641
+ }
642
+ const err = parseFcmError(text);
643
+ const reason = err.errorCode ?? err.status ?? String(res.status);
644
+ if (res.status === 401 && err.errorCode !== "THIRD_PARTY_AUTH_ERROR") {
645
+ access = void 0;
646
+ if (attempt === 0) continue;
647
+ throw new PushCredentialsError("fcm", "access token refused twice (401 UNAUTHENTICATED)");
648
+ }
649
+ if (err.errorCode === "UNREGISTERED" || res.status === 404 && err.status === "NOT_FOUND") return invalid(message.token, "unregistered", res.status);
650
+ if ((err.errorCode === "INVALID_ARGUMENT" || err.status === "INVALID_ARGUMENT") && err.tokenNamed) return invalid(message.token, "invalid-token", res.status);
651
+ if (res.status === 403 && err.errorCode !== "SENDER_ID_MISMATCH") throw new PushCredentialsError("fcm", `service account lacks permission to send (403 ${reason})`);
652
+ if (res.status === 429 || res.status >= 500) {
653
+ const retryAfterMs = parseRetryAfter(res.headers.get("retry-after"), now());
654
+ if (retryAfterMs !== void 0 && !err.perDevice) cooldown.hold(retryAfterMs);
655
+ throw new TransientPushError("fcm", res.status, reason, retryAfterMs !== void 0 ? { retryAfterMs } : {});
656
+ }
657
+ throw new PushRejectedError("fcm", res.status, reason);
658
+ }
659
+ /* c8 ignore next */
660
+ throw new TransientPushError("fcm", 0, "unreachable");
661
+ }
662
+ return { async send(message) {
663
+ const started = now();
664
+ try {
665
+ checkMessage(message);
666
+ return await gate(() => sendOnce(message, started));
667
+ } catch (err) {
668
+ emit({
669
+ ...failureEvent(err),
670
+ latencyMs: now() - started,
671
+ ...platformOf(message)
672
+ }, message.token);
673
+ throw err;
674
+ }
675
+ } };
676
+ }
677
+ function platformOf(message) {
678
+ return message.platform ? { platform: message.platform } : {};
679
+ }
680
+
681
+ //#endregion
682
+ //#region src/push/apns.ts
683
+ const APNS_HOSTS = {
684
+ production: "https://api.push.apple.com",
685
+ sandbox: "https://api.sandbox.push.apple.com"
686
+ };
687
+ /** Default provider-token lifetime: inside Apple's 20 to 60 minute window with margin. */
688
+ const APNS_TOKEN_TTL_MS = 3e6;
689
+ const MIN_TTL_MS = 12e5;
690
+ const MAX_TTL_MS = 36e5;
691
+ const MAX_PAYLOAD_BYTES = 4096;
692
+ const DEVICE_TOKEN = /^[0-9a-fA-F]{16,400}$/;
693
+ /** The APNs JSON payload for a message. Exported for tests and payload inspection. */
694
+ function buildApnsPayload(message, options) {
695
+ const custom = { ...message.data ?? {} };
696
+ if (message.imageUrl) custom.imageUrl = message.imageUrl;
697
+ return {
698
+ ...custom,
699
+ aps: buildAps(message, options)
700
+ };
701
+ }
702
+ function apnsProvider(options) {
703
+ const now = options.now ?? Date.now;
704
+ const tokenTtlMs = options.tokenTtlMs ?? 3e6;
705
+ if (tokenTtlMs < MIN_TTL_MS || tokenTtlMs >= MAX_TTL_MS) throw new Error("apnsProvider: tokenTtlMs must be at least 20 minutes and under 60 minutes (Apple)");
706
+ if (options.host && !options.host.startsWith("https://") && !options.allowPlaintext) throw new Error("apnsProvider: host must be https:// (allowPlaintext is for tests only)");
707
+ const timeoutMs = options.requestTimeoutMs ?? 1e4;
708
+ const gate = createGate(options.maxConcurrency ?? 500);
709
+ const cooldown = createCooldown(now);
710
+ const connect = options.connect ?? ((authority, connectOptions) => http2.connect(authority, connectOptions));
711
+ let providerToken;
712
+ const sessions = /* @__PURE__ */ new Map();
713
+ const resolver = createCredentialResolver("apns", options.credentials, validateApnsCredentials, (creds) => importKey("apns", creds.privateKey), (next) => {
714
+ providerToken = void 0;
715
+ const keep = authorityOf(next.creds);
716
+ for (const [authority, entry] of sessions) if (authority !== keep) {
717
+ sessions.delete(authority);
718
+ entry.session.close();
719
+ }
720
+ });
721
+ function authorityOf(creds) {
722
+ return options.host ?? APNS_HOSTS[creds.environment ?? "production"];
723
+ }
724
+ function bearer(resolved, force) {
725
+ const t = now();
726
+ if (!force && providerToken && providerToken.fingerprint === resolved.fingerprint && t - providerToken.issuedAt < tokenTtlMs) return providerToken.token;
727
+ const token = signJwt("ES256", resolved.derived, {
728
+ iss: resolved.creds.teamId,
729
+ iat: Math.floor(t / 1e3)
730
+ }, { kid: resolved.creds.keyId });
731
+ providerToken = {
732
+ token,
733
+ issuedAt: t,
734
+ fingerprint: resolved.fingerprint
735
+ };
736
+ return token;
737
+ }
738
+ function sessionFor(authority) {
739
+ const existing = sessions.get(authority);
740
+ if (existing && !existing.session.closed && !existing.session.destroyed) return existing;
741
+ const session = connect(authority, options.connectOptions);
742
+ const entry = {
743
+ session,
744
+ active: 0
745
+ };
746
+ const drop = () => {
747
+ if (sessions.get(authority) === entry) sessions.delete(authority);
748
+ };
749
+ session.on("error", drop);
750
+ session.on("goaway", drop);
751
+ session.on("close", drop);
752
+ session.unref();
753
+ sessions.set(authority, entry);
754
+ return entry;
755
+ }
756
+ function post(authority, headers, body) {
757
+ return new Promise((resolve, reject) => {
758
+ let entry;
759
+ let stream;
760
+ try {
761
+ entry = sessionFor(authority);
762
+ stream = entry.session.request(headers);
763
+ } catch (err) {
764
+ reject(new TransientPushError("apns", 0, "network", err instanceof Error ? { cause: err } : {}));
765
+ return;
766
+ }
767
+ if (entry.active++ === 0) entry.session.ref();
768
+ let settled = false;
769
+ const finish = (fn) => {
770
+ if (settled) return;
771
+ settled = true;
772
+ if (--entry.active === 0 && !entry.session.destroyed) entry.session.unref();
773
+ fn();
774
+ };
775
+ let status = 0;
776
+ let apnsId;
777
+ let retryAfter;
778
+ let raw = "";
779
+ stream.setEncoding("utf8");
780
+ stream.setTimeout(timeoutMs, () => {
781
+ stream.close(http2.constants.NGHTTP2_CANCEL);
782
+ finish(() => reject(new TransientPushError("apns", 0, "timeout")));
783
+ });
784
+ stream.on("response", (h) => {
785
+ status = Number(h[":status"] ?? 0);
786
+ const id = h["apns-id"];
787
+ apnsId = Array.isArray(id) ? id[0] : id;
788
+ retryAfter = h["retry-after"];
789
+ });
790
+ stream.on("data", (chunk) => {
791
+ if (raw.length < 4096) raw += chunk;
792
+ });
793
+ stream.on("error", (err) => {
794
+ finish(() => reject(new TransientPushError("apns", 0, "network", { cause: err })));
795
+ });
796
+ stream.on("end", () => {
797
+ let reason;
798
+ if (raw) try {
799
+ const parsed = JSON.parse(raw);
800
+ if (typeof parsed.reason === "string") reason = parsed.reason;
801
+ } catch {
802
+ reason = void 0;
803
+ }
804
+ finish(() => resolve({
805
+ status,
806
+ ...apnsId ? { apnsId } : {},
807
+ ...reason ? { reason } : {},
808
+ ...retryAfter !== void 0 ? { retryAfter } : {}
809
+ }));
810
+ });
811
+ stream.end(body);
812
+ });
813
+ }
814
+ const emit = (event, token) => {
815
+ if (!options.onDelivery) return;
816
+ try {
817
+ options.onDelivery({
818
+ provider: "apns",
819
+ tokenSuffix: tokenSuffix(token),
820
+ tokenHash: tokenHash(token),
821
+ ...event
822
+ });
823
+ } catch {}
824
+ };
825
+ async function invalid(token, reason, status) {
826
+ await reportInvalid(options.onInvalidToken, token, reason);
827
+ throw new InvalidPushTokenError("apns", reason, status, tokenSuffix(token));
828
+ }
829
+ function checkMessage(message) {
830
+ if (typeof message.token !== "string" || !DEVICE_TOKEN.test(message.token)) throw new PushRejectedError("apns", 0, "invalid-token-format", "APNs device tokens are hex strings");
831
+ if (collapseKeyTooLong(message.collapseKey)) throw new PushRejectedError("apns", 0, "collapse-key-too-long", "collapseKey exceeds 64 bytes");
832
+ if (message.data && "aps" in message.data) throw new PushRejectedError("apns", 0, "invalid-data", "data.aps is reserved by APNs");
833
+ const body = JSON.stringify(buildApnsPayload(message, options));
834
+ if (Buffer.byteLength(body, "utf8") > MAX_PAYLOAD_BYTES) throw new PushRejectedError("apns", 0, "payload-too-large", "payload exceeds 4096 bytes");
835
+ return body;
836
+ }
837
+ async function sendOnce(message, body, started) {
838
+ const waitMs = cooldown.remaining();
839
+ if (waitMs > 0) throw new TransientPushError("apns", 429, "cooling-down", { retryAfterMs: waitMs });
840
+ const resolved = await resolver.resolve();
841
+ const authority = authorityOf(resolved.creds);
842
+ const values = apnsHeaderValues(message, now());
843
+ for (let attempt = 0; attempt < 2; attempt++) {
844
+ const res = await post(authority, {
845
+ ":method": "POST",
846
+ ":path": `/3/device/${message.token}`,
847
+ authorization: `bearer ${bearer(resolved, attempt > 0)}`,
848
+ "apns-topic": resolved.creds.bundleId,
849
+ "apns-push-type": values.pushType,
850
+ "apns-priority": values.priority,
851
+ ...values.expiration !== void 0 ? { "apns-expiration": values.expiration } : {},
852
+ ...message.collapseKey ? { "apns-collapse-id": message.collapseKey } : {},
853
+ "content-type": "application/json"
854
+ }, body);
855
+ if (res.status === 200) {
856
+ const messageId = res.apnsId ?? "apns";
857
+ emit({
858
+ outcome: "sent",
859
+ status: 200,
860
+ messageId,
861
+ latencyMs: now() - started,
862
+ ...message.platform ? { platform: message.platform } : {}
863
+ }, message.token);
864
+ return { messageId };
865
+ }
866
+ const reason = res.reason ?? String(res.status);
867
+ if (res.status === 410 || res.reason === "Unregistered") return invalid(message.token, "unregistered", res.status);
868
+ if (res.reason === "BadDeviceToken") return invalid(message.token, "bad-device-token", res.status);
869
+ if (res.status === 403) {
870
+ if (res.reason === "ExpiredProviderToken" || res.reason === "InvalidProviderToken") {
871
+ providerToken = void 0;
872
+ if (attempt === 0) continue;
873
+ }
874
+ throw new PushCredentialsError("apns", `Apple refused the provider token (403 ${reason})`);
875
+ }
876
+ if (res.status === 429 || res.status >= 500) {
877
+ const retryAfterMs = parseRetryAfter(res.retryAfter, now());
878
+ if (res.reason === "TooManyProviderTokenUpdates") cooldown.hold(retryAfterMs ?? 6e4);
879
+ else if (res.status >= 500 && retryAfterMs !== void 0) cooldown.hold(retryAfterMs);
880
+ throw new TransientPushError("apns", res.status, reason, retryAfterMs !== void 0 ? { retryAfterMs } : {});
881
+ }
882
+ throw new PushRejectedError("apns", res.status, reason);
883
+ }
884
+ /* c8 ignore next */
885
+ throw new TransientPushError("apns", 0, "unreachable");
886
+ }
887
+ return {
888
+ async send(message) {
889
+ const started = now();
890
+ try {
891
+ const body = checkMessage(message);
892
+ return await gate(() => sendOnce(message, body, started));
893
+ } catch (err) {
894
+ emit({
895
+ ...failureEvent(err),
896
+ latencyMs: now() - started,
897
+ ...message.platform ? { platform: message.platform } : {}
898
+ }, message.token);
899
+ throw err;
900
+ }
901
+ },
902
+ async close() {
903
+ const open = [...sessions.values()];
904
+ sessions.clear();
905
+ await Promise.all(open.map(({ session }) => new Promise((resolve) => {
906
+ if (session.closed || session.destroyed) return resolve();
907
+ session.on("close", () => resolve());
908
+ session.close();
909
+ })));
910
+ }
911
+ };
912
+ }
913
+
914
+ //#endregion
915
+ //#region src/push/router.ts
916
+ function pushRouter(options) {
917
+ const table = {
918
+ ...options.android ? { android: options.android } : {},
919
+ ...options.ios ? { ios: options.ios } : {},
920
+ ...options.web ? { web: options.web } : {}
921
+ };
922
+ const platforms = Object.keys(table);
923
+ if (platforms.length === 0) throw new Error("pushRouter: configure at least one platform provider");
924
+ return {
925
+ platforms,
926
+ async send(message) {
927
+ const platform = message.platform ?? options.defaultPlatform;
928
+ if (!platform) throw new PushRejectedError("router", 0, "platform-missing", "message.platform is required");
929
+ const provider = table[platform];
930
+ if (!provider) throw new PushRejectedError("router", 0, "platform-disabled", `no provider for ${platform}`);
931
+ return provider.send(message.platform ? message : {
932
+ ...message,
933
+ platform
934
+ });
935
+ },
936
+ async close() {
937
+ const distinct = new Set(Object.values(table));
938
+ await Promise.all([...distinct].map((p) => p.close?.()));
939
+ }
940
+ };
941
+ }
942
+
943
+ //#endregion
944
+ //#region src/push/payload.ts
945
+ /**
946
+ * Opaque id or enum: letters, digits, `_ - . :`, 1 to 64 characters (`task_offer`,
947
+ * `order.created`, an ObjectId, a UUID). No spaces, so no sentence or name fits.
948
+ */
949
+ const OPAQUE_ID = /^[A-Za-z0-9_.:-]{1,64}$/;
950
+ function check(options, data) {
951
+ const pattern = options.valuePattern ?? OPAQUE_ID;
952
+ const allowed = /* @__PURE__ */ new Set(["type", ...options.allowedKeys]);
953
+ const out = {};
954
+ for (const [key, value] of Object.entries(data)) {
955
+ if (value === void 0) continue;
956
+ if (!allowed.has(key)) throw new PushRejectedError("router", 0, "content-not-allowed", `data.${key} is not allowed in a content-free push`);
957
+ if (typeof value !== "string" || !pattern.test(value)) throw new PushRejectedError("router", 0, "content-not-allowed", `data.${key} must be an opaque id`);
958
+ out[key] = value;
959
+ }
960
+ if (!out.type) throw new PushRejectedError("router", 0, "content-not-allowed", "data.type is required");
961
+ if (options.types && !options.types.includes(out.type)) throw new PushRejectedError("router", 0, "content-not-allowed", "data.type is not a known push type");
962
+ return out;
963
+ }
964
+ /**
965
+ * Build content-free messages. `title` should be GENERIC ("New task offered to you"), already in
966
+ * the device's language; omit it for a silent data-only push.
967
+ */
968
+ function createContentFreeBuilder(options) {
969
+ return (input) => {
970
+ const data = check(options, {
971
+ ...input.refs ?? {},
972
+ type: input.type
973
+ });
974
+ const title = input.title ?? "";
975
+ return {
976
+ title,
977
+ body: "",
978
+ data,
979
+ contentAvailable: title === ""
980
+ };
981
+ };
982
+ }
983
+ /**
984
+ * Wrap a provider so ONLY content-free messages pass: empty body, no image, data limited to the
985
+ * allowed keys and opaque values. Anything else is a permanent `PushRejectedError` before any
986
+ * network call.
987
+ */
988
+ function contentFreeOnly(provider, options) {
989
+ return {
990
+ async send(message) {
991
+ if (message.body) throw new PushRejectedError("router", 0, "content-not-allowed", "a content-free push has no body");
992
+ if (message.imageUrl) throw new PushRejectedError("router", 0, "content-not-allowed", "a content-free push has no image");
993
+ const data = check(options, message.data ?? {});
994
+ return provider.send({
995
+ ...message,
996
+ data
997
+ });
998
+ },
999
+ ...provider.close ? { close: () => provider.close?.() } : {}
1000
+ };
1001
+ }
1002
+
1003
+ //#endregion
1004
+ export { APNS_HOSTS, APNS_TOKEN_TTL_MS, FCM_ENDPOINT, FCM_SCOPE, GOOGLE_TOKEN_URI, InvalidPushTokenError, OPAQUE_ID, PushCredentialsError, PushRejectedError, TransientPushError, apnsProvider, buildApnsPayload, buildAps, buildFcmMessage, contentFreeOnly, createContentFreeBuilder, credentialsFingerprint, effectiveLevel, fcmProvider, fingerprint, isInvalidPushTokenError, normalizePem, parseFcmServiceAccount, parseRetryAfter, pushRouter, signJwt, tokenHash, tokenSuffix, validateApnsCredentials, validateFcmCredentials };