@aglyn/tenant-data-admin 1.0.0-beta.264 → 1.0.0-beta.268

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.
Files changed (41) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/host-console-link.d.ts +25 -0
  3. package/src/lib/server/host-console-link.js +47 -0
  4. package/src/lib/server/host-console-link.js.map +1 -0
  5. package/src/lib/server/host-email-tokens.js +25 -2
  6. package/src/lib/server/host-email-tokens.js.map +1 -1
  7. package/src/lib/server/mobile-push-switch.d.ts +2 -0
  8. package/src/lib/server/mobile-push-switch.js.map +1 -1
  9. package/src/lib/server/notifications.d.ts +10 -4
  10. package/src/lib/server/notifications.js +34 -9
  11. package/src/lib/server/notifications.js.map +1 -1
  12. package/src/lib/server/operator-alerts.d.ts +11 -0
  13. package/src/lib/server/operator-alerts.js +29 -7
  14. package/src/lib/server/operator-alerts.js.map +1 -1
  15. package/src/lib/server/org-member-notice.d.ts +10 -0
  16. package/src/lib/server/org-member-notice.js +6 -1
  17. package/src/lib/server/org-member-notice.js.map +1 -1
  18. package/src/lib/server/organizations.js +8 -1
  19. package/src/lib/server/organizations.js.map +1 -1
  20. package/src/lib/server/push-apns.d.ts +7 -2
  21. package/src/lib/server/push-apns.js +8 -4
  22. package/src/lib/server/push-apns.js.map +1 -1
  23. package/src/lib/server/push-delivery.d.ts +5 -0
  24. package/src/lib/server/push-delivery.js +9 -4
  25. package/src/lib/server/push-delivery.js.map +1 -1
  26. package/src/lib/server/push-fcm.d.ts +8 -1
  27. package/src/lib/server/push-fcm.js +11 -3
  28. package/src/lib/server/push-fcm.js.map +1 -1
  29. package/src/lib/server/rate-limit-store.d.ts +12 -4
  30. package/src/lib/server/rate-limit-store.js +19 -4
  31. package/src/lib/server/rate-limit-store.js.map +1 -1
  32. package/src/lib/server/render-monitor.d.ts +36 -5
  33. package/src/lib/server/render-monitor.js +81 -22
  34. package/src/lib/server/render-monitor.js.map +1 -1
  35. package/src/lib/server/render-system-email.js +7 -1
  36. package/src/lib/server/render-system-email.js.map +1 -1
  37. package/src/lib/server/risk-notice.js +23 -1
  38. package/src/lib/server/risk-notice.js.map +1 -1
  39. package/src/lib/server/staff-alert-email.d.ts +10 -0
  40. package/src/lib/server/staff-alert-email.js +10 -3
  41. package/src/lib/server/staff-alert-email.js.map +1 -1
@@ -33,6 +33,7 @@
33
33
  * Server-only, imported by `push-delivery.ts` only when a device is on APNs.
34
34
  */
35
35
  import { type KeyObject } from 'node:crypto';
36
+ import type { NotificationSound } from '@aglyn/aglyn/app-utils/notification-sounds';
36
37
  import type { PushMessage, PushOutcome, PushTransport } from './push-delivery';
37
38
  export declare const APNS_HOSTS: {
38
39
  readonly production: "https://api.push.apple.com";
@@ -56,8 +57,12 @@ export declare function parseApnsKey(raw: string): KeyObject;
56
57
  export declare function apnsCredentials(env: Record<string, string | undefined>): ApnsCredentials | null;
57
58
  /** An ES256 provider token: `{alg, kid}.{iss, iat}`, signed raw (r‖s), as APNs requires. */
58
59
  export declare function apnsProviderToken(credentials: ApnsCredentials, nowMs: number): string;
59
- /** The APNs payload: the alert, the default sound, and the tap data beside `aps`. */
60
- export declare function apnsPayload(message: PushMessage): string;
60
+ /**
61
+ * The APNs payload: the alert, the person's picked sound and the tap data
62
+ * beside `aps`. The sound names a file in the app's bundle; a build that
63
+ * does not ship it yet plays the system sound instead.
64
+ */
65
+ export declare function apnsPayload(message: PushMessage, sound?: NotificationSound): string;
61
66
  export declare function apnsOutcome(response: ApnsResponse): PushOutcome;
62
67
  export interface ApnsTransportOptions {
63
68
  credentials: ApnsCredentials;
@@ -79,7 +79,12 @@ export function apnsCredentials(env) {
79
79
  });
80
80
  return `${header}.${claims}.${base64url(signature)}`;
81
81
  }
82
- /** The APNs payload: the alert, the default sound, and the tap data beside `aps`. */ export function apnsPayload(message) {
82
+ /**
83
+ * The APNs payload: the alert, the person's picked sound and the tap data
84
+ * beside `aps`. The sound names a file in the app's bundle; a build that
85
+ * does not ship it yet plays the system sound instead.
86
+ */ export function apnsPayload(message, sound) {
87
+ var _ref;
83
88
  return JSON.stringify(_extends({
84
89
  aps: {
85
90
  alert: _extends({
@@ -87,7 +92,7 @@ export function apnsCredentials(env) {
87
92
  }, message.body ? {
88
93
  body: message.body
89
94
  } : {}),
90
- sound: 'default'
95
+ sound: (_ref = sound == null ? void 0 : sound.apple) != null ? _ref : 'default'
91
96
  }
92
97
  }, message.data));
93
98
  }
@@ -168,7 +173,6 @@ export function createApnsTransport(options) {
168
173
  request: options.request,
169
174
  close: ()=>undefined
170
175
  } : http2Requester();
171
- const body = apnsPayload(message);
172
176
  const outcomes = new Array(targets.length).fill('failed');
173
177
  try {
174
178
  for(let start = 0; start < targets.length; start += CONCURRENCY){
@@ -185,7 +189,7 @@ export function createApnsTransport(options) {
185
189
  // why native pushes arrived late or never while the console showed them at once.
186
190
  'apns-priority': '10',
187
191
  'content-type': 'application/json'
188
- }, body);
192
+ }, apnsPayload(message, target.sound));
189
193
  // An expired or refused provider token is ours to mint again, not the device's fault.
190
194
  if (response.status === 403) cached = null;
191
195
  outcomes[start + offset] = apnsOutcome(response);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/push-apns.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Apple Push Notification service, sent directly (AGL-3651): HTTP/2 to\n * `api.push.apple.com` (or `api.sandbox.push.apple.com` for a development\n * build's token), authenticated with a provider token, an ES256 JWT signed\n * with the team's APNs key.\n *\n * APNS_KEY_P8 the `.p8` key: PEM text, or that PEM (or its DER) base64-encoded\n * APNS_KEY_ID the key's 10-character id\n * APNS_TEAM_ID the Apple Developer team id\n *\n * Without all three the transport is off: a device on APNs is skipped and\n * that is logged once per process. A provider token is reused for up to 50\n * minutes (Apple refuses one older than an hour, and one refreshed more often\n * than every 20). A `410`, `BadDeviceToken` or `Unregistered` answer means the\n * token is gone, and the row is pruned.\n *\n * Server-only, imported by `push-delivery.ts` only when a device is on APNs.\n */\n\nimport { createPrivateKey, sign, type KeyObject } from 'node:crypto'\nimport { connect, type ClientHttp2Session } from 'node:http2'\nimport type { PushMessage, PushOutcome, PushTarget, PushTransport } from './push-delivery'\n\nexport const APNS_HOSTS = {\n production: 'https://api.push.apple.com',\n sandbox: 'https://api.sandbox.push.apple.com',\n} as const\n\n/** A provider token is reused for at most this long. */\nexport const APNS_TOKEN_TTL_MS = 50 * 60 * 1000\n\n/** Requests in flight at once on one connection. */\nconst CONCURRENCY = 20\n\nexport interface ApnsCredentials {\n key: KeyObject\n keyId: string\n teamId: string\n}\n\nexport interface ApnsResponse {\n status: number\n body: string\n}\n\n/** One HTTP/2 POST to an APNs origin; injectable for tests. */\nexport type ApnsRequest = (origin: string, headers: Record<string, string>, body: string) => Promise<ApnsResponse>\n\nconst base64url = (input: Buffer | string) => Buffer.from(input).toString('base64url')\n\n/** The `.p8` key from `APNS_KEY_P8`: PEM, base64 of the PEM, or base64 of the DER. */\nexport function parseApnsKey(raw: string): KeyObject {\n const text = raw.trim().replace(/\\\\n/g, '\\n')\n if (text.includes('-----BEGIN')) return createPrivateKey(text)\n const decoded = Buffer.from(text, 'base64')\n const asText = decoded.toString('utf8')\n if (asText.includes('-----BEGIN')) return createPrivateKey(asText)\n return createPrivateKey({ key: decoded, format: 'der', type: 'pkcs8' })\n}\n\nexport function apnsCredentials(env: Record<string, string | undefined>): ApnsCredentials | null {\n const raw = env['APNS_KEY_P8']?.trim()\n const keyId = env['APNS_KEY_ID']?.trim()\n const teamId = env['APNS_TEAM_ID']?.trim()\n if (!raw || !keyId || !teamId) return null\n return { key: parseApnsKey(raw), keyId, teamId }\n}\n\n/** An ES256 provider token: `{alg, kid}.{iss, iat}`, signed raw (r‖s), as APNs requires. */\nexport function apnsProviderToken(credentials: ApnsCredentials, nowMs: number): string {\n const header = base64url(JSON.stringify({ alg: 'ES256', kid: credentials.keyId }))\n const claims = base64url(JSON.stringify({ iss: credentials.teamId, iat: Math.floor(nowMs / 1000) }))\n const signature = sign('sha256', Buffer.from(`${header}.${claims}`), {\n key: credentials.key,\n dsaEncoding: 'ieee-p1363',\n })\n return `${header}.${claims}.${base64url(signature)}`\n}\n\n/** The APNs payload: the alert, the default sound, and the tap data beside `aps`. */\nexport function apnsPayload(message: PushMessage): string {\n return JSON.stringify({\n aps: {\n alert: { title: message.title, ...(message.body ? { body: message.body } : {}) },\n sound: 'default',\n },\n ...message.data,\n })\n}\n\nconst GONE = new Set(['BadDeviceToken', 'Unregistered', 'DeviceTokenNotForTopic'])\n\nexport function apnsOutcome(response: ApnsResponse): PushOutcome {\n if (response.status === 200) return 'sent'\n if (response.status === 410) return 'prune'\n let reason = ''\n try {\n reason = String(JSON.parse(response.body)?.reason ?? '')\n } catch {\n // An unreadable body is a failure, not a verdict on the token.\n }\n return GONE.has(reason) ? 'prune' : 'failed'\n}\n\n/** The default request: one HTTP/2 session per origin for the life of a send. */\nfunction http2Requester(): { request: ApnsRequest; close: () => void } {\n const sessions = new Map<string, ClientHttp2Session>()\n const session = (origin: string) => {\n let open = sessions.get(origin)\n if (!open || open.closed || open.destroyed) {\n open = connect(origin)\n open.on('error', () => undefined)\n sessions.set(origin, open)\n }\n return open\n }\n const request: ApnsRequest = (origin, headers, body) =>\n new Promise((resolve, reject) => {\n const stream = session(origin).request({ ':method': 'POST', ...headers })\n let status = 0\n let text = ''\n stream.setEncoding('utf8')\n stream.setTimeout(15_000, () => stream.close())\n stream.on('response', (head) => {\n status = Number(head[':status'] ?? 0)\n })\n stream.on('data', (chunk: string) => {\n text += chunk\n })\n stream.on('end', () => resolve({ status, body: text }))\n stream.on('error', reject)\n stream.end(body)\n })\n return {\n request,\n close: () => {\n for (const open of sessions.values()) open.close()\n sessions.clear()\n },\n }\n}\n\nexport interface ApnsTransportOptions {\n credentials: ApnsCredentials\n /** Injected in tests; the default opens HTTP/2 sessions per send. */\n request?: ApnsRequest\n now?: () => number\n}\n\nexport function createApnsTransport(options: ApnsTransportOptions): PushTransport {\n const now = options.now ?? Date.now\n let cached: { token: string; at: number } | null = null\n const providerToken = () => {\n const at = now()\n if (!cached || at - cached.at >= APNS_TOKEN_TTL_MS) cached = { token: apnsProviderToken(options.credentials, at), at }\n return cached.token\n }\n return {\n async send(targets: readonly PushTarget[], message: PushMessage): Promise<PushOutcome[]> {\n const { request, close } = options.request\n ? { request: options.request, close: () => undefined }\n : http2Requester()\n const body = apnsPayload(message)\n const outcomes: PushOutcome[] = new Array(targets.length).fill('failed')\n try {\n for (let start = 0; start < targets.length; start += CONCURRENCY) {\n const batch = targets.slice(start, start + CONCURRENCY)\n await Promise.all(\n batch.map(async (target, offset) => {\n try {\n const response = await request(\n APNS_HOSTS[target.apnsEnvironment ?? 'production'],\n {\n ':path': `/3/device/${target.token}`,\n authorization: `bearer ${providerToken()}`,\n 'apns-topic': target.topic,\n 'apns-push-type': 'alert',\n // 10 for every alert: 5 lets the device hold, batch or drop it to save power, which is\n // why native pushes arrived late or never while the console showed them at once.\n 'apns-priority': '10',\n 'content-type': 'application/json',\n },\n body,\n )\n // An expired or refused provider token is ours to mint again, not the device's fault.\n if (response.status === 403) cached = null\n outcomes[start + offset] = apnsOutcome(response)\n } catch {\n outcomes[start + offset] = 'failed'\n }\n }),\n )\n }\n } finally {\n close()\n }\n return outcomes\n },\n }\n}\n\nlet warnedMissingKey = false\nlet configured: { transport: PushTransport } | null = null\n\n/**\n * The deployment's APNs transport from `APNS_*`, or null — logged once —\n * when they are not set.\n */\nexport function apnsTransport(env: Record<string, string | undefined> = process.env): PushTransport | null {\n if (configured) return configured.transport\n const credentials = apnsCredentials(env)\n if (!credentials) {\n if (!warnedMissingKey) {\n warnedMissingKey = true\n console.warn('push: APNS_KEY_P8, APNS_KEY_ID and APNS_TEAM_ID are not all set; iOS and macOS devices are skipped')\n }\n return null\n }\n configured = { transport: createApnsTransport({ credentials }) }\n return configured.transport\n}\n"],"names":["createPrivateKey","sign","connect","APNS_HOSTS","production","sandbox","APNS_TOKEN_TTL_MS","CONCURRENCY","base64url","input","Buffer","from","toString","parseApnsKey","raw","text","trim","replace","includes","decoded","asText","key","format","type","apnsCredentials","env","keyId","teamId","apnsProviderToken","credentials","nowMs","header","JSON","stringify","alg","kid","claims","iss","iat","Math","floor","signature","dsaEncoding","apnsPayload","message","aps","alert","title","body","sound","data","GONE","Set","apnsOutcome","response","status","reason","String","parse","has","http2Requester","sessions","Map","session","origin","open","get","closed","destroyed","on","undefined","set","request","headers","Promise","resolve","reject","stream","setEncoding","setTimeout","close","head","Number","chunk","end","values","clear","createApnsTransport","options","now","Date","cached","providerToken","at","token","send","targets","outcomes","Array","length","fill","start","batch","slice","all","map","target","offset","apnsEnvironment","authorization","topic","warnedMissingKey","configured","apnsTransport","process","transport","console","warn"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;CAiBC,GAED,SAASA,gBAAgB,EAAEC,IAAI,QAAwB,cAAa;AACpE,SAASC,OAAO,QAAiC,aAAY;AAG7D,OAAO,MAAMC,aAAa;IACxBC,YAAY;IACZC,SAAS;AACX,EAAU;AAEV,sDAAsD,GACtD,OAAO,MAAMC,oBAAoB,KAAK,KAAK,KAAI;AAE/C,kDAAkD,GAClD,MAAMC,cAAc;AAgBpB,MAAMC,YAAY,CAACC,QAA2BC,OAAOC,IAAI,CAACF,OAAOG,QAAQ,CAAC;AAE1E,oFAAoF,GACpF,OAAO,SAASC,aAAaC,GAAW;IACtC,MAAMC,OAAOD,IAAIE,IAAI,GAAGC,OAAO,CAAC,QAAQ;IACxC,IAAIF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AAQC;wBACvB,IAAI;gCAEWD;4BADb,MAAMpD,WAAW,MAAMkB,QACrBrE,UAAU,EAACuG,0BAAAA,OAAOE,eAAe,YAAtBF,0BAA0B,aAAa,EAClD;gCACE,SAAS,CAAC,UAAU,EAAEA,OAAOZ,KAAK,EAAE;gCACpCe,eAAe,CAAC,OAAO,EAAEjB,iBAAiB;gCAC1C,cAAcc,OAAOI,KAAK;gCAC1B,kBAAkB;gCAClB,uFAAuF;gCACvF,iFAAiF;gCACjF,iBAAiB;gCACjB,gBAAgB;4BAClB,GACA9D;4BAEF,sFAAsF;4BACtF,IAAIM,SAASC,MAAM,KAAK,KAAKoC,SAAS;4BACtCM,QAAQ,CAACI,QAAQM,OAAO,GAAGtD,YAAYC;wBACzC,EAAE,eAAM;4BACN2C,QAAQ,CAACI,QAAQM,OAAO,GAAG;wBAC7B;oBACF;gBAEJ;YACF,SAAU;gBACR3B;YACF;YACA,OAAOiB;QACT;IACF;AACF;AAEA,IAAIc,mBAAmB;AACvB,IAAIC,aAAkD;AAEtD;;;CAGC,GACD,OAAO,SAASC,cAAcxF,MAA0CyF,QAAQzF,GAAG;IACjF,IAAIuF,YAAY,OAAOA,WAAWG,SAAS;IAC3C,MAAMtF,cAAcL,gBAAgBC;IACpC,IAAI,CAACI,aAAa;QAChB,IAAI,CAACkF,kBAAkB;YACrBA,mBAAmB;YACnBK,QAAQC,IAAI,CAAC;QACf;QACA,OAAO;IACT;IACAL,aAAa;QAAEG,WAAW5B,oBAAoB;YAAE1D;QAAY;IAAG;IAC/D,OAAOmF,WAAWG,SAAS;AAC7B"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/push-apns.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Apple Push Notification service, sent directly (AGL-3651): HTTP/2 to\n * `api.push.apple.com` (or `api.sandbox.push.apple.com` for a development\n * build's token), authenticated with a provider token, an ES256 JWT signed\n * with the team's APNs key.\n *\n * APNS_KEY_P8 the `.p8` key: PEM text, or that PEM (or its DER) base64-encoded\n * APNS_KEY_ID the key's 10-character id\n * APNS_TEAM_ID the Apple Developer team id\n *\n * Without all three the transport is off: a device on APNs is skipped and\n * that is logged once per process. A provider token is reused for up to 50\n * minutes (Apple refuses one older than an hour, and one refreshed more often\n * than every 20). A `410`, `BadDeviceToken` or `Unregistered` answer means the\n * token is gone, and the row is pruned.\n *\n * Server-only, imported by `push-delivery.ts` only when a device is on APNs.\n */\n\nimport { createPrivateKey, sign, type KeyObject } from 'node:crypto'\nimport { connect, type ClientHttp2Session } from 'node:http2'\nimport type { NotificationSound } from '@aglyn/aglyn/app-utils/notification-sounds'\nimport type { PushMessage, PushOutcome, PushTarget, PushTransport } from './push-delivery'\n\nexport const APNS_HOSTS = {\n production: 'https://api.push.apple.com',\n sandbox: 'https://api.sandbox.push.apple.com',\n} as const\n\n/** A provider token is reused for at most this long. */\nexport const APNS_TOKEN_TTL_MS = 50 * 60 * 1000\n\n/** Requests in flight at once on one connection. */\nconst CONCURRENCY = 20\n\nexport interface ApnsCredentials {\n key: KeyObject\n keyId: string\n teamId: string\n}\n\nexport interface ApnsResponse {\n status: number\n body: string\n}\n\n/** One HTTP/2 POST to an APNs origin; injectable for tests. */\nexport type ApnsRequest = (origin: string, headers: Record<string, string>, body: string) => Promise<ApnsResponse>\n\nconst base64url = (input: Buffer | string) => Buffer.from(input).toString('base64url')\n\n/** The `.p8` key from `APNS_KEY_P8`: PEM, base64 of the PEM, or base64 of the DER. */\nexport function parseApnsKey(raw: string): KeyObject {\n const text = raw.trim().replace(/\\\\n/g, '\\n')\n if (text.includes('-----BEGIN')) return createPrivateKey(text)\n const decoded = Buffer.from(text, 'base64')\n const asText = decoded.toString('utf8')\n if (asText.includes('-----BEGIN')) return createPrivateKey(asText)\n return createPrivateKey({ key: decoded, format: 'der', type: 'pkcs8' })\n}\n\nexport function apnsCredentials(env: Record<string, string | undefined>): ApnsCredentials | null {\n const raw = env['APNS_KEY_P8']?.trim()\n const keyId = env['APNS_KEY_ID']?.trim()\n const teamId = env['APNS_TEAM_ID']?.trim()\n if (!raw || !keyId || !teamId) return null\n return { key: parseApnsKey(raw), keyId, teamId }\n}\n\n/** An ES256 provider token: `{alg, kid}.{iss, iat}`, signed raw (r‖s), as APNs requires. */\nexport function apnsProviderToken(credentials: ApnsCredentials, nowMs: number): string {\n const header = base64url(JSON.stringify({ alg: 'ES256', kid: credentials.keyId }))\n const claims = base64url(JSON.stringify({ iss: credentials.teamId, iat: Math.floor(nowMs / 1000) }))\n const signature = sign('sha256', Buffer.from(`${header}.${claims}`), {\n key: credentials.key,\n dsaEncoding: 'ieee-p1363',\n })\n return `${header}.${claims}.${base64url(signature)}`\n}\n\n/**\n * The APNs payload: the alert, the person's picked sound and the tap data\n * beside `aps`. The sound names a file in the app's bundle; a build that\n * does not ship it yet plays the system sound instead.\n */\nexport function apnsPayload(message: PushMessage, sound?: NotificationSound): string {\n return JSON.stringify({\n aps: {\n alert: { title: message.title, ...(message.body ? { body: message.body } : {}) },\n sound: sound?.apple ?? 'default',\n },\n ...message.data,\n })\n}\n\nconst GONE = new Set(['BadDeviceToken', 'Unregistered', 'DeviceTokenNotForTopic'])\n\nexport function apnsOutcome(response: ApnsResponse): PushOutcome {\n if (response.status === 200) return 'sent'\n if (response.status === 410) return 'prune'\n let reason = ''\n try {\n reason = String(JSON.parse(response.body)?.reason ?? '')\n } catch {\n // An unreadable body is a failure, not a verdict on the token.\n }\n return GONE.has(reason) ? 'prune' : 'failed'\n}\n\n/** The default request: one HTTP/2 session per origin for the life of a send. */\nfunction http2Requester(): { request: ApnsRequest; close: () => void } {\n const sessions = new Map<string, ClientHttp2Session>()\n const session = (origin: string) => {\n let open = sessions.get(origin)\n if (!open || open.closed || open.destroyed) {\n open = connect(origin)\n open.on('error', () => undefined)\n sessions.set(origin, open)\n }\n return open\n }\n const request: ApnsRequest = (origin, headers, body) =>\n new Promise((resolve, reject) => {\n const stream = session(origin).request({ ':method': 'POST', ...headers })\n let status = 0\n let text = ''\n stream.setEncoding('utf8')\n stream.setTimeout(15_000, () => stream.close())\n stream.on('response', (head) => {\n status = Number(head[':status'] ?? 0)\n })\n stream.on('data', (chunk: string) => {\n text += chunk\n })\n stream.on('end', () => resolve({ status, body: text }))\n stream.on('error', reject)\n stream.end(body)\n })\n return {\n request,\n close: () => {\n for (const open of sessions.values()) open.close()\n sessions.clear()\n },\n }\n}\n\nexport interface ApnsTransportOptions {\n credentials: ApnsCredentials\n /** Injected in tests; the default opens HTTP/2 sessions per send. */\n request?: ApnsRequest\n now?: () => number\n}\n\nexport function createApnsTransport(options: ApnsTransportOptions): PushTransport {\n const now = options.now ?? Date.now\n let cached: { token: string; at: number } | null = null\n const providerToken = () => {\n const at = now()\n if (!cached || at - cached.at >= APNS_TOKEN_TTL_MS) cached = { token: apnsProviderToken(options.credentials, at), at }\n return cached.token\n }\n return {\n async send(targets: readonly PushTarget[], message: PushMessage): Promise<PushOutcome[]> {\n const { request, close } = options.request\n ? { request: options.request, close: () => undefined }\n : http2Requester()\n const outcomes: PushOutcome[] = new Array(targets.length).fill('failed')\n try {\n for (let start = 0; start < targets.length; start += CONCURRENCY) {\n const batch = targets.slice(start, start + CONCURRENCY)\n await Promise.all(\n batch.map(async (target, offset) => {\n try {\n const response = await request(\n APNS_HOSTS[target.apnsEnvironment ?? 'production'],\n {\n ':path': `/3/device/${target.token}`,\n authorization: `bearer ${providerToken()}`,\n 'apns-topic': target.topic,\n 'apns-push-type': 'alert',\n // 10 for every alert: 5 lets the device hold, batch or drop it to save power, which is\n // why native pushes arrived late or never while the console showed them at once.\n 'apns-priority': '10',\n 'content-type': 'application/json',\n },\n apnsPayload(message, target.sound),\n )\n // An expired or refused provider token is ours to mint again, not the device's fault.\n if (response.status === 403) cached = null\n outcomes[start + offset] = apnsOutcome(response)\n } catch {\n outcomes[start + offset] = 'failed'\n }\n }),\n )\n }\n } finally {\n close()\n }\n return outcomes\n },\n }\n}\n\nlet warnedMissingKey = false\nlet configured: { transport: PushTransport } | null = null\n\n/**\n * The deployment's APNs transport from `APNS_*`, or null — logged once —\n * when they are not set.\n */\nexport function apnsTransport(env: Record<string, string | undefined> = process.env): PushTransport | null {\n if (configured) return configured.transport\n const credentials = apnsCredentials(env)\n if (!credentials) {\n if (!warnedMissingKey) {\n warnedMissingKey = true\n console.warn('push: APNS_KEY_P8, APNS_KEY_ID and APNS_TEAM_ID are not all set; iOS and macOS devices are skipped')\n }\n return null\n }\n configured = { transport: createApnsTransport({ credentials }) }\n return configured.transport\n}\n"],"names":["createPrivateKey","sign","connect","APNS_HOSTS","production","sandbox","APNS_TOKEN_TTL_MS","CONCURRENCY","base64url","input","Buffer","from","toString","parseApnsKey","raw","text","trim","replace","includes","decoded","asText","key","format","type","apnsCredentials","env","keyId","teamId","apnsProviderToken","credentials","nowMs","header","JSON","stringify","alg","kid","claims","iss","iat","Math","floor","signature","dsaEncoding","apnsPayload","message","sound","aps","alert","title","body","apple","data","GONE","Set","apnsOutcome","response","status","reason","String","parse","has","http2Requester","sessions","Map","session","origin","open","get","closed","destroyed","on","undefined","set","request","headers","Promise","resolve","reject","stream","setEncoding","setTimeout","close","head","Number","chunk","end","values","clear","createApnsTransport","options","now","Date","cached","providerToken","at","token","send","targets","outcomes","Array","length","fill","start","batch","slice","all","map","target","offset","apnsEnvironment","authorization","topic","warnedMissingKey","configured","apnsTransport","process","transport","console","warn"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;CAiBC,GAED,SAASA,gBAAgB,EAAEC,IAAI,QAA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ACI,aAAa;QAChB,IAAI,CAACmF,kBAAkB;YACrBA,mBAAmB;YACnBK,QAAQC,IAAI,CAAC;QACf;QACA,OAAO;IACT;IACAL,aAAa;QAAEG,WAAW5B,oBAAoB;YAAE3D;QAAY;IAAG;IAC/D,OAAOoF,WAAWG,SAAS;AAC7B"}
@@ -30,6 +30,7 @@
30
30
  * transport reports as gone is pruned after the send.
31
31
  */
32
32
  import { type ApnsEnvironment, type MobileDeviceApp, type MobilePushData, type MobilePushTransport } from '@aglyn/aglyn/app-utils/notification-push';
33
+ import { type NotificationSound } from '@aglyn/aglyn/app-utils/notification-sounds';
33
34
  import type { Firestore } from 'firebase-admin/firestore';
34
35
  import type { MobilePushPayload, MobilePushSender } from './mobile-push-switch';
35
36
  /** One device a transport sends to. */
@@ -39,6 +40,8 @@ export interface PushTarget {
39
40
  /** APNs: the app's bundle id, which is the push topic. */
40
41
  topic: string;
41
42
  apnsEnvironment?: ApnsEnvironment;
43
+ /** The sound its person picked; each transport names that platform's file. */
44
+ sound: NotificationSound;
42
45
  }
43
46
  /** What every device of one notification is sent. */
44
47
  export interface PushMessage {
@@ -58,6 +61,8 @@ export interface PushDeliveryDeps {
58
61
  /** Each transport, or null when the deployment has none configured. Resolved only when a device needs it. */
59
62
  transport: (kind: MobilePushTransport) => Promise<PushTransport | null>;
60
63
  now?: () => number;
64
+ /** Each recipient's picked sound id; anyone missing hears the default. */
65
+ sounds?: Readonly<Record<string, string>>;
61
66
  }
62
67
  export interface PushDeliveryResult {
63
68
  sent: number;
@@ -29,6 +29,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
29
29
  * transport, and a device not seen for `MOBILE_DEVICE_STALE_MS`. A token a
30
30
  * transport reports as gone is pruned after the send.
31
31
  */ import { isMobilePushToken, MOBILE_APP_BUNDLES, MOBILE_DEVICE_STALE_MS, MOBILE_DEVICES_COLLECTION, MOBILE_DEVICES_PER_USER, mobilePushData } from "@aglyn/aglyn/app-utils/notification-push";
32
+ import { notificationSound } from "@aglyn/aglyn/app-utils/notification-sounds";
32
33
  import { normalizeNotificationLink } from "@aglyn/aglyn/server";
33
34
  /** The most devices one notification is sent to, whatever the audience. */ const MAX_DEVICES = 1000;
34
35
  /** A stored timestamp as epoch millis, or null when there is none. */ function millis(value) {
@@ -106,6 +107,7 @@ const isApp = (value)=>value === 'aglyn' || value === 'aglyn-pos';
106
107
  const devices = await db.collection('users').doc(uid).collection(MOBILE_DEVICES_COLLECTION).limit(MOBILE_DEVICES_PER_USER).get();
107
108
  for (const device of devices.docs){
108
109
  var _groups_get;
110
+ var _deps_sounds;
109
111
  const transport = device.get('transport');
110
112
  const token = device.get('token');
111
113
  const app = device.get('app');
@@ -126,7 +128,8 @@ const isApp = (value)=>value === 'aglyn' || value === 'aglyn-pos';
126
128
  const target = _extends({
127
129
  token,
128
130
  app,
129
- topic: MOBILE_APP_BUNDLES[app]
131
+ topic: MOBILE_APP_BUNDLES[app],
132
+ sound: notificationSound((_deps_sounds = deps.sounds) == null ? void 0 : _deps_sounds[uid])
130
133
  }, transport === 'apns' && (environment === 'sandbox' || environment === 'production') ? {
131
134
  apnsEnvironment: environment
132
135
  } : {});
@@ -176,11 +179,13 @@ const isApp = (value)=>value === 'aglyn' || value === 'aglyn-pos';
176
179
  if (kind === 'apns') return (await import("./push-apns.js")).apnsTransport();
177
180
  return (await import("./push-fcm.js")).fcmTransport();
178
181
  }
179
- /** The sender `registerNativePushSenders` hands the fan-out. */ export const nativePushSender = async (uids, payload, { db })=>{
180
- await deliverNativePush(uids, payload, {
182
+ /** The sender `registerNativePushSenders` hands the fan-out. */ export const nativePushSender = async (uids, payload, { db, sounds })=>{
183
+ await deliverNativePush(uids, payload, _extends({
181
184
  db,
182
185
  transport: deploymentTransport
183
- });
186
+ }, sounds ? {
187
+ sounds
188
+ } : {}));
184
189
  };
185
190
 
186
191
  //# sourceMappingURL=push-delivery.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/push-delivery.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The native apps' push delivery (AGL-3651): a notification the fan-out\n * wrote goes to each recipient's registered devices, grouped by transport —\n * APNs for iOS and macOS (`push-apns.ts`), FCM for Android (`push-fcm.ts`).\n *\n * Server-only. `registerNativePushSenders` (`native-push.ts`) registers\n * `nativePushSender` with the fan-out and imports this file only when a\n * notification has push recipients, and this file imports each transport\n * only when a device needs it.\n *\n * A row the registry no longer accepts is pruned here: an Expo row from the\n * React Native app, a row with no transport, a token that does not fit its\n * transport, and a device not seen for `MOBILE_DEVICE_STALE_MS`. A token a\n * transport reports as gone is pruned after the send.\n */\n\nimport {\n isMobilePushToken,\n MOBILE_APP_BUNDLES,\n MOBILE_DEVICE_STALE_MS,\n MOBILE_DEVICES_COLLECTION,\n MOBILE_DEVICES_PER_USER,\n mobilePushData,\n type ApnsEnvironment,\n type MobileDeviceApp,\n type MobilePushData,\n type MobilePushTransport,\n} from '@aglyn/aglyn/app-utils/notification-push'\nimport { normalizeNotificationLink } from '@aglyn/aglyn/server'\nimport type { DocumentReference, Firestore } from 'firebase-admin/firestore'\nimport type { MobilePushPayload, MobilePushSender } from './mobile-push-switch'\n\n/** The most devices one notification is sent to, whatever the audience. */\nconst MAX_DEVICES = 1000\n\n/** One device a transport sends to. */\nexport interface PushTarget {\n token: string\n app: MobileDeviceApp\n /** APNs: the app's bundle id, which is the push topic. */\n topic: string\n apnsEnvironment?: ApnsEnvironment\n}\n\n/** What every device of one notification is sent. */\nexport interface PushMessage {\n title: string\n body?: string\n data: MobilePushData\n /** Critical and warning notifications ask the platform to deliver now. */\n urgent: boolean\n}\n\n/** A transport's verdict for each target, in order. `prune`: the token is gone; forget the row. */\nexport type PushOutcome = 'sent' | 'prune' | 'failed'\n\nexport interface PushTransport {\n send(targets: readonly PushTarget[], message: PushMessage): Promise<PushOutcome[]>\n}\n\nexport interface PushDeliveryDeps {\n db: Firestore\n /** Each transport, or null when the deployment has none configured. Resolved only when a device needs it. */\n transport: (kind: MobilePushTransport) => Promise<PushTransport | null>\n now?: () => number\n}\n\nexport interface PushDeliveryResult {\n sent: number\n /** Rows removed: stale, Expo or malformed rows, and tokens a transport reported gone. */\n pruned: number\n failed: number\n /** Devices not sent to because their transport is not configured. */\n skipped: number\n}\n\n/** A stored timestamp as epoch millis, or null when there is none. */\nfunction millis(value: unknown): number | null {\n if (!value) return null\n if (typeof value === 'number') return value\n const withMillis = value as { toMillis?: () => number }\n return typeof withMillis.toMillis === 'function' ? withMillis.toMillis() : null\n}\n\nexport function pushMessage(payload: MobilePushPayload, link: string | undefined): PushMessage {\n return {\n title: payload.title,\n ...(payload.body ? { body: payload.body } : {}),\n data: mobilePushData({ ...payload, link }),\n urgent: payload.level === 'critical' || payload.level === 'warning',\n }\n}\n\n/** The link the app opens: the stored one, rewritten onto today's console routes. */\nasync function pushLink(db: Firestore, payload: MobilePushPayload): Promise<string | undefined> {\n if (!payload.link) return undefined\n if (!payload.orgId) return normalizeNotificationLink(payload.link, {})\n try {\n const [org, host] = await Promise.all([\n db.collection('orgs').doc(payload.orgId).get(),\n payload.hostId ? db.collection('hosts').doc(payload.hostId).get() : Promise.resolve(null),\n ])\n const slug = org.get('slug')\n const subdomain = host?.get('subdomain')\n return normalizeNotificationLink(payload.link, {\n orgSlug: typeof slug === 'string' ? slug : null,\n hostId: payload.hostId ?? null,\n hostSubdomain: typeof subdomain === 'string' ? subdomain : null,\n })\n } catch {\n return normalizeNotificationLink(payload.link, {})\n }\n}\n\nconst isApp = (value: unknown): value is MobileDeviceApp => value === 'aglyn' || value === 'aglyn-pos'\n\n/**\n * The notification types the Aglyn POS app is pushed. The register is not a\n * second inbox: a person who has both apps would otherwise get every\n * workspace notification twice on the same Mac or iPad, so the Aglyn app\n * carries them all and the POS app only what a register needs. None yet.\n */\nexport const POS_PUSH_TYPES: ReadonlySet<string> = new Set<string>()\n\n/** Whether `app` is sent a notification of `type`. */\nexport function appReceivesPush(app: MobileDeviceApp, type: string | undefined): boolean {\n return app === 'aglyn' || (type !== undefined && POS_PUSH_TYPES.has(type))\n}\n\n/**\n * Sends one notification to every live device of `uids`, each through its\n * own transport. Never throws: the console notification is the record, and a\n * push is a courtesy beside it.\n */\nexport async function deliverNativePush(\n uids: readonly string[],\n payload: MobilePushPayload,\n deps: PushDeliveryDeps,\n): Promise<PushDeliveryResult> {\n const result: PushDeliveryResult = { sent: 0, pruned: 0, failed: 0, skipped: 0 }\n if (!uids.length) return result\n const now = (deps.now ?? Date.now)()\n const prune = async (ref: DocumentReference) => {\n await ref.delete().catch(() => undefined)\n result.pruned += 1\n }\n try {\n const { db } = deps\n const groups = new Map<MobilePushTransport, Array<{ target: PushTarget; ref: DocumentReference }>>()\n const seen = new Set<string>()\n let total = 0\n for (const uid of uids) {\n const devices = await db\n .collection('users')\n .doc(uid)\n .collection(MOBILE_DEVICES_COLLECTION)\n .limit(MOBILE_DEVICES_PER_USER)\n .get()\n for (const device of devices.docs) {\n const transport = device.get('transport')\n const token = device.get('token')\n const app = device.get('app')\n if (!isMobilePushToken(transport, token) || !isApp(app)) {\n await prune(device.ref)\n continue\n }\n const lastSeen = millis(device.get('lastSeen'))\n if (lastSeen !== null && now - lastSeen > MOBILE_DEVICE_STALE_MS) {\n await prune(device.ref)\n continue\n }\n if (!appReceivesPush(app, payload.type)) continue\n if (seen.has(token) || total >= MAX_DEVICES) continue\n seen.add(token)\n total += 1\n const environment = device.get('apnsEnvironment')\n const target: PushTarget = {\n token,\n app,\n topic: MOBILE_APP_BUNDLES[app],\n ...(transport === 'apns' && (environment === 'sandbox' || environment === 'production')\n ? { apnsEnvironment: environment }\n : {}),\n }\n const group = groups.get(transport) ?? []\n group.push({ target, ref: device.ref })\n groups.set(transport, group)\n }\n }\n if (!groups.size) return result\n const message = pushMessage(payload, await pushLink(db, payload))\n for (const [kind, entries] of groups) {\n let transport: PushTransport | null = null\n try {\n transport = await deps.transport(kind)\n } catch (error) {\n console.error(`push transport ${kind} failed to load`, error)\n }\n if (!transport) {\n result.skipped += entries.length\n continue\n }\n let outcomes: PushOutcome[]\n try {\n outcomes = await transport.send(\n entries.map((entry) => entry.target),\n message,\n )\n } catch (error) {\n console.error(`push transport ${kind} failed`, error)\n result.failed += entries.length\n continue\n }\n for (const [index, entry] of entries.entries()) {\n const outcome = outcomes[index] ?? 'failed'\n if (outcome === 'sent') result.sent += 1\n else if (outcome === 'prune') await prune(entry.ref)\n else result.failed += 1\n }\n }\n } catch (error) {\n console.error('push delivery failed', error)\n }\n return result\n}\n\n/** The deployment's transports, each imported the first time a device needs it. */\nasync function deploymentTransport(kind: MobilePushTransport): Promise<PushTransport | null> {\n if (kind === 'apns') return (await import('./push-apns')).apnsTransport()\n return (await import('./push-fcm')).fcmTransport()\n}\n\n/** The sender `registerNativePushSenders` hands the fan-out. */\nexport const nativePushSender: MobilePushSender = async (uids, payload, { db }) => {\n await deliverNativePush(uids, payload, { db, transport: deploymentTransport })\n}\n"],"names":["isMobilePushToken","MOBILE_APP_BUNDLES","MOBILE_DEVICE_STALE_MS","MOBILE_DEVICES_COLLECTION","MOBILE_DEVICES_PER_USER","mobilePushData","normalizeNotificationLink","MAX_DEVICES","millis","value","withMillis","toMillis","pushMessage","payload","link","title","body","data","urgent","level","pushLink","db","undefined","orgId","org","host","Promise","all","collection","doc","get","hostId","resolve","slug","subdomain","orgSlug","hostSubdomain","isApp","POS_PUSH_TYPES","Set","appReceivesPush","app","type","has","deliverNativePush","uids","deps","result","sent","pruned","failed","skipped","length","now","Date","prune","ref","delete","catch","groups","Map","seen","total","uid","devices","limit","device","docs","transport","token","lastSeen","add","environment","target","topic","apnsEnvironment","group","push","set","size","message","kind","entries","error","console","outcomes","send","map","entry","index","outcome","deploymentTransport","apnsTransport","fcmTransport","nativePushSender"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED,SACEA,iBAAiB,EACjBC,kBAAkB,EAClBC,sBAAsB,EACtBC,yBAAyB,EACzBC,uBAAuB,EACvBC,cAAc,QAKT,2CAA0C;AACjD,SAASC,yBAAyB,QAAQ,sBAAqB;AAI/D,yEAAyE,GACzE,MAAMC,cAAc;AA2CpB,oEAAoE,GACpE,SAASC,OAAOC,KAAc;IAC5B,IAAI,CAACA,OAAO,OAAO;IACnB,IAAI,OAAOA,UAAU,UAAU,OAAOA;IACtC,MAAMC,aAAaD;IACnB,OAAO,OAAOC,WAAWC,QAAQ,KAAK,aAAaD,WAAWC,QAAQ,KAAK;AAC7E;AAEA,OAAO,SAASC,YAAYC,OAA0B,EAAEC,IAAwB;IAC9E,OAAO;QACLC,OAAOF,QAAQE,KAAK;OAChBF,QAAQG,IAAI,GAAG;QAAEA,MAAMH,QAAQG,IAAI;IAAC,IAAI,CAAC;QAC7CC,MAAMZ,eAAe,aAAKQ;YAASC;;QACnCI,QAAQL,QAAQM,KAAK,KAAK,cAAcN,QAAQM,KAAK,KAAK;;AAE9D;AAEA,mFAAmF,GACnF,eAAeC,SAASC,EAAa,EAAER,OAA0B;IAC/D,IAAI,CAACA,QAAQC,IAAI,EAAE,OAAOQ;IAC1B,IAAI,CAACT,QAAQU,KAAK,EAAE,OAAOjB,0BAA0BO,QAAQC,IAAI,EAAE,CAAC;IACpE,IAAI;YASQD;QARV,MAAM,CAACW,KAAKC,KAAK,GAAG,MAAMC,QAAQC,GAAG,CAAC;YACpCN,GAAGO,UAAU,CAAC,QAAQC,GAAG,CAAChB,QAAQU,KAAK,EAAEO,GAAG;YAC5CjB,QAAQkB,MAAM,GAAGV,GAAGO,UAAU,CAAC,SAASC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D,GAC9D,OAAO,MAAMC,mBAAqC,OAAOjD,MAAMhC,SAAS,EAAEQ,EAAE,EAAE;IAC5E,MAAMuB,kBAAkBC,MAAMhC,SAAS;QAAEQ;QAAI+C,WAAWuB;IAAoB;AAC9E,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/push-delivery.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The native apps' push delivery (AGL-3651): a notification the fan-out\n * wrote goes to each recipient's registered devices, grouped by transport —\n * APNs for iOS and macOS (`push-apns.ts`), FCM for Android (`push-fcm.ts`).\n *\n * Server-only. `registerNativePushSenders` (`native-push.ts`) registers\n * `nativePushSender` with the fan-out and imports this file only when a\n * notification has push recipients, and this file imports each transport\n * only when a device needs it.\n *\n * A row the registry no longer accepts is pruned here: an Expo row from the\n * React Native app, a row with no transport, a token that does not fit its\n * transport, and a device not seen for `MOBILE_DEVICE_STALE_MS`. A token a\n * transport reports as gone is pruned after the send.\n */\n\nimport {\n isMobilePushToken,\n MOBILE_APP_BUNDLES,\n MOBILE_DEVICE_STALE_MS,\n MOBILE_DEVICES_COLLECTION,\n MOBILE_DEVICES_PER_USER,\n mobilePushData,\n type ApnsEnvironment,\n type MobileDeviceApp,\n type MobilePushData,\n type MobilePushTransport,\n} from '@aglyn/aglyn/app-utils/notification-push'\nimport { notificationSound, type NotificationSound } from '@aglyn/aglyn/app-utils/notification-sounds'\nimport { normalizeNotificationLink } from '@aglyn/aglyn/server'\nimport type { DocumentReference, Firestore } from 'firebase-admin/firestore'\nimport type { MobilePushPayload, MobilePushSender } from './mobile-push-switch'\n\n/** The most devices one notification is sent to, whatever the audience. */\nconst MAX_DEVICES = 1000\n\n/** One device a transport sends to. */\nexport interface PushTarget {\n token: string\n app: MobileDeviceApp\n /** APNs: the app's bundle id, which is the push topic. */\n topic: string\n apnsEnvironment?: ApnsEnvironment\n /** The sound its person picked; each transport names that platform's file. */\n sound: NotificationSound\n}\n\n/** What every device of one notification is sent. */\nexport interface PushMessage {\n title: string\n body?: string\n data: MobilePushData\n /** Critical and warning notifications ask the platform to deliver now. */\n urgent: boolean\n}\n\n/** A transport's verdict for each target, in order. `prune`: the token is gone; forget the row. */\nexport type PushOutcome = 'sent' | 'prune' | 'failed'\n\nexport interface PushTransport {\n send(targets: readonly PushTarget[], message: PushMessage): Promise<PushOutcome[]>\n}\n\nexport interface PushDeliveryDeps {\n db: Firestore\n /** Each transport, or null when the deployment has none configured. Resolved only when a device needs it. */\n transport: (kind: MobilePushTransport) => Promise<PushTransport | null>\n now?: () => number\n /** Each recipient's picked sound id; anyone missing hears the default. */\n sounds?: Readonly<Record<string, string>>\n}\n\nexport interface PushDeliveryResult {\n sent: number\n /** Rows removed: stale, Expo or malformed rows, and tokens a transport reported gone. */\n pruned: number\n failed: number\n /** Devices not sent to because their transport is not configured. */\n skipped: number\n}\n\n/** A stored timestamp as epoch millis, or null when there is none. */\nfunction millis(value: unknown): number | null {\n if (!value) return null\n if (typeof value === 'number') return value\n const withMillis = value as { toMillis?: () => number }\n return typeof withMillis.toMillis === 'function' ? withMillis.toMillis() : null\n}\n\nexport function pushMessage(payload: MobilePushPayload, link: string | undefined): PushMessage {\n return {\n title: payload.title,\n ...(payload.body ? { body: payload.body } : {}),\n data: mobilePushData({ ...payload, link }),\n urgent: payload.level === 'critical' || payload.level === 'warning',\n }\n}\n\n/** The link the app opens: the stored one, rewritten onto today's console routes. */\nasync function pushLink(db: Firestore, payload: MobilePushPayload): Promise<string | undefined> {\n if (!payload.link) return undefined\n if (!payload.orgId) return normalizeNotificationLink(payload.link, {})\n try {\n const [org, host] = await Promise.all([\n db.collection('orgs').doc(payload.orgId).get(),\n payload.hostId ? db.collection('hosts').doc(payload.hostId).get() : Promise.resolve(null),\n ])\n const slug = org.get('slug')\n const subdomain = host?.get('subdomain')\n return normalizeNotificationLink(payload.link, {\n orgSlug: typeof slug === 'string' ? slug : null,\n hostId: payload.hostId ?? null,\n hostSubdomain: typeof subdomain === 'string' ? subdomain : null,\n })\n } catch {\n return normalizeNotificationLink(payload.link, {})\n }\n}\n\nconst isApp = (value: unknown): value is MobileDeviceApp => value === 'aglyn' || value === 'aglyn-pos'\n\n/**\n * The notification types the Aglyn POS app is pushed. The register is not a\n * second inbox: a person who has both apps would otherwise get every\n * workspace notification twice on the same Mac or iPad, so the Aglyn app\n * carries them all and the POS app only what a register needs. None yet.\n */\nexport const POS_PUSH_TYPES: ReadonlySet<string> = new Set<string>()\n\n/** Whether `app` is sent a notification of `type`. */\nexport function appReceivesPush(app: MobileDeviceApp, type: string | undefined): boolean {\n return app === 'aglyn' || (type !== undefined && POS_PUSH_TYPES.has(type))\n}\n\n/**\n * Sends one notification to every live device of `uids`, each through its\n * own transport. Never throws: the console notification is the record, and a\n * push is a courtesy beside it.\n */\nexport async function deliverNativePush(\n uids: readonly string[],\n payload: MobilePushPayload,\n deps: PushDeliveryDeps,\n): Promise<PushDeliveryResult> {\n const result: PushDeliveryResult = { sent: 0, pruned: 0, failed: 0, skipped: 0 }\n if (!uids.length) return result\n const now = (deps.now ?? Date.now)()\n const prune = async (ref: DocumentReference) => {\n await ref.delete().catch(() => undefined)\n result.pruned += 1\n }\n try {\n const { db } = deps\n const groups = new Map<MobilePushTransport, Array<{ target: PushTarget; ref: DocumentReference }>>()\n const seen = new Set<string>()\n let total = 0\n for (const uid of uids) {\n const devices = await db\n .collection('users')\n .doc(uid)\n .collection(MOBILE_DEVICES_COLLECTION)\n .limit(MOBILE_DEVICES_PER_USER)\n .get()\n for (const device of devices.docs) {\n const transport = device.get('transport')\n const token = device.get('token')\n const app = device.get('app')\n if (!isMobilePushToken(transport, token) || !isApp(app)) {\n await prune(device.ref)\n continue\n }\n const lastSeen = millis(device.get('lastSeen'))\n if (lastSeen !== null && now - lastSeen > MOBILE_DEVICE_STALE_MS) {\n await prune(device.ref)\n continue\n }\n if (!appReceivesPush(app, payload.type)) continue\n if (seen.has(token) || total >= MAX_DEVICES) continue\n seen.add(token)\n total += 1\n const environment = device.get('apnsEnvironment')\n const target: PushTarget = {\n token,\n app,\n topic: MOBILE_APP_BUNDLES[app],\n sound: notificationSound(deps.sounds?.[uid]),\n ...(transport === 'apns' && (environment === 'sandbox' || environment === 'production')\n ? { apnsEnvironment: environment }\n : {}),\n }\n const group = groups.get(transport) ?? []\n group.push({ target, ref: device.ref })\n groups.set(transport, group)\n }\n }\n if (!groups.size) return result\n const message = pushMessage(payload, await pushLink(db, payload))\n for (const [kind, entries] of groups) {\n let transport: PushTransport | null = null\n try {\n transport = await deps.transport(kind)\n } catch (error) {\n console.error(`push transport ${kind} failed to load`, error)\n }\n if (!transport) {\n result.skipped += entries.length\n continue\n }\n let outcomes: PushOutcome[]\n try {\n outcomes = await transport.send(\n entries.map((entry) => entry.target),\n message,\n )\n } catch (error) {\n console.error(`push transport ${kind} failed`, error)\n result.failed += entries.length\n continue\n }\n for (const [index, entry] of entries.entries()) {\n const outcome = outcomes[index] ?? 'failed'\n if (outcome === 'sent') result.sent += 1\n else if (outcome === 'prune') await prune(entry.ref)\n else result.failed += 1\n }\n }\n } catch (error) {\n console.error('push delivery failed', error)\n }\n return result\n}\n\n/** The deployment's transports, each imported the first time a device needs it. */\nasync function deploymentTransport(kind: MobilePushTransport): Promise<PushTransport | null> {\n if (kind === 'apns') return (await import('./push-apns')).apnsTransport()\n return (await import('./push-fcm')).fcmTransport()\n}\n\n/** The sender `registerNativePushSenders` hands the fan-out. */\nexport const nativePushSender: MobilePushSender = async (uids, payload, { db, sounds }) => {\n await deliverNativePush(uids, payload, { db, transport: deploymentTransport, ...(sounds ? { sounds } : {}) })\n}\n"],"names":["isMobilePushToken","MOBILE_APP_BUNDLES","MOBILE_DEVICE_STALE_MS","MOBILE_DEVICES_COLLECTION","MOBILE_DEVICES_PER_USER","mobilePushData","notificationSound","normalizeNotificationLink","MAX_DEVICES","millis","value","withMillis","toMillis","pushMessage","payload","link","title","body","data","urgent","level","pushLink","db","undefined","orgId","org","host","Promise","all","collection","doc","get","hostId","resolve","slug","subdomain","orgSlug","hostSubdomain","isApp","POS_PUSH_TYPES","Set","appReceivesPush","app","type","has","deliverNativePush","uids","deps","result","sent","pruned","failed","skipped","length","now","Date","prune","ref","delete","catch","groups","Map","seen","total","uid","devices","limit","device","docs","transport","token","lastSeen","add","environment","target","topic","sound","sounds","apnsEnvironment","group","push","set","size","message","kind","entries","error","console","outcomes","send","map","entry","index","outcome","deploymentTransport","apnsTransport","fcmTransport","nativePushSender"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED,SACEA,iBAAiB,EACjBC,kBAAkB,EAClBC,sBAAsB,EACtBC,yBAAyB,EACzBC,uBAAuB,EACvBC,cAAc,QAKT,2CAA0C;AACjD,SAASC,iBAAiB,QAAgC,6CAA4C;AACtG,SAASC,yBAAyB,QAAQ,sBAAqB;AAI/D,yEAAyE,GACzE,MAAMC,cAAc;AA+CpB,oEAAoE,GACpE,SAASC,OAAOC,KAAc;IAC5B,IAAI,CAACA,OAAO,OAAO;IACnB,IAAI,OAAOA,UAAU,UAAU,OAAOA;IACtC,MAAMC,aAAaD;IACnB,OAAO,OAAOC,WAAWC,QAAQ,KAAK,aAAaD,WAAWC,QAAQ,KAAK;AAC7E;AAEA,OAAO,SAASC,YAAYC,OAA0B,EAAEC,IAAwB;IAC9E,OAAO;QACLC,OAAOF,QAAQE,KAAK;OAChBF,QAAQG,IAAI,GAAG;QAAEA,MAAMH,QAAQG,IAAI;IAAC,IAAI,CAAC;QAC7CC,MAAMb,eAAe,aA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D,MAAM,IAAIN,QAAQA,OAAO,GAAI;oBAC9BG;gBAAhB,MAAMK,WAAUL,kBAAAA,QAAQ,CAACI,MAAM,YAAfJ,kBAAmB;gBACnC,IAAIK,YAAY,QAAQ7C,OAAOC,IAAI,IAAI;qBAClC,IAAI4C,YAAY,SAAS,MAAMrC,MAAMmC,MAAMlC,GAAG;qBAC9CT,OAAOG,MAAM,IAAI;YACxB;QACF;IACF,EAAE,OAAOmC,OAAO;QACdC,QAAQD,KAAK,CAAC,wBAAwBA;IACxC;IACA,OAAOtC;AACT;AAEA,iFAAiF,GACjF,eAAe8C,oBAAoBV,IAAyB;IAC1D,IAAIA,SAAS,QAAQ,OAAO,AAAC,CAAA,MAAM,MAAM,CAAC,iBAAa,EAAGW,aAAa;IACvE,OAAO,AAAC,CAAA,MAAM,MAAM,CAAC,gBAAY,EAAGC,YAAY;AAClD;AAEA,8DAA8D,GAC9D,OAAO,MAAMC,mBAAqC,OAAOnD,MAAMhC,SAAS,EAAEQ,EAAE,EAAEuD,MAAM,EAAE;IACpF,MAAMhC,kBAAkBC,MAAMhC,SAAS;QAAEQ;QAAI+C,WAAWyB;OAAyBjB,SAAS;QAAEA;IAAO,IAAI,CAAC;AAC1G,EAAC"}
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import { type BatchResponse, type TokenMessage } from 'firebase-admin/messaging';
18
18
  import './firebase-admin';
19
+ import type { NotificationSound } from '@aglyn/aglyn/app-utils/notification-sounds';
19
20
  import type { PushMessage, PushTransport } from './push-delivery';
20
21
  /** `sendEach` takes at most 500 messages. */
21
22
  export declare const FCM_BATCH = 500;
@@ -23,7 +24,13 @@ export declare const FCM_BATCH = 500;
23
24
  export interface FcmMessaging {
24
25
  sendEach(messages: TokenMessage[]): Promise<BatchResponse>;
25
26
  }
26
- export declare function fcmMessage(token: string, message: PushMessage): TokenMessage;
27
+ /**
28
+ * One device's message. The person's sound is the channel's: an Android
29
+ * channel's sound is fixed when the app creates it, so the app makes one
30
+ * channel per sound and the message names it. A build that has no such
31
+ * channel yet shows it on the manifest's default channel.
32
+ */
33
+ export declare function fcmMessage(token: string, message: PushMessage, sound?: NotificationSound): TokenMessage;
27
34
  export declare function createFcmTransport(messaging: FcmMessaging): PushTransport;
28
35
  /** The deployment's FCM transport, on the firebase-admin default app. */
29
36
  export declare function fcmTransport(): PushTransport;
@@ -33,7 +33,12 @@ const GONE = new Set([
33
33
  'messaging/invalid-registration-token',
34
34
  'messaging/invalid-argument'
35
35
  ]);
36
- export function fcmMessage(token, message) {
36
+ /**
37
+ * One device's message. The person's sound is the channel's: an Android
38
+ * channel's sound is fixed when the app creates it, so the app makes one
39
+ * channel per sound and the message names it. A build that has no such
40
+ * channel yet shows it on the manifest's default channel.
41
+ */ export function fcmMessage(token, message, sound) {
37
42
  return {
38
43
  token,
39
44
  notification: _extends({
@@ -45,7 +50,10 @@ export function fcmMessage(token, message) {
45
50
  data: _extends({}, message.data),
46
51
  android: {
47
52
  priority: 'high',
48
- notification: {
53
+ notification: sound ? {
54
+ sound: sound.android,
55
+ channelId: sound.android
56
+ } : {
49
57
  sound: 'default'
50
58
  }
51
59
  }
@@ -58,7 +66,7 @@ export function createFcmTransport(messaging) {
58
66
  for(let start = 0; start < targets.length; start += FCM_BATCH){
59
67
  const batch = targets.slice(start, start + FCM_BATCH);
60
68
  try {
61
- const { responses } = await messaging.sendEach(batch.map((target)=>fcmMessage(target.token, message)));
69
+ const { responses } = await messaging.sendEach(batch.map((target)=>fcmMessage(target.token, message, target.sound)));
62
70
  for (const [index] of batch.entries()){
63
71
  var _ref;
64
72
  var _response_error;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/push-fcm.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Firebase Cloud Messaging for the Android app (AGL-3651), through\n * firebase-admin's `getMessaging().sendEach` with the project credentials\n * the server already holds, so it needs no secret of its own. The\n * notification is shown by the system; the tap data rides in `data`, and\n * Android delivers it at high priority.\n *\n * A token FCM reports unregistered or invalid is gone, and the row is pruned.\n *\n * Server-only, imported by `push-delivery.ts` only when a device is on FCM.\n */\n\nimport { getApp } from 'firebase-admin/app'\nimport { getMessaging, type BatchResponse, type TokenMessage } from 'firebase-admin/messaging'\nimport './firebase-admin'\nimport type { PushMessage, PushOutcome, PushTarget, PushTransport } from './push-delivery'\n\n/** `sendEach` takes at most 500 messages. */\nexport const FCM_BATCH = 500\n\nconst GONE = new Set([\n 'messaging/registration-token-not-registered',\n 'messaging/invalid-registration-token',\n 'messaging/invalid-argument',\n])\n\n/** The slice of firebase-admin's Messaging this transport uses; injected in tests. */\nexport interface FcmMessaging {\n sendEach(messages: TokenMessage[]): Promise<BatchResponse>\n}\n\nexport function fcmMessage(token: string, message: PushMessage): TokenMessage {\n return {\n token,\n notification: { title: message.title, ...(message.body ? { body: message.body } : {}) },\n // FCM data values are strings; MobilePushData's are.\n data: { ...message.data },\n android: { priority: 'high', notification: { sound: 'default' } },\n }\n}\n\nexport function createFcmTransport(messaging: FcmMessaging): PushTransport {\n return {\n async send(targets: readonly PushTarget[], message: PushMessage): Promise<PushOutcome[]> {\n const outcomes: PushOutcome[] = []\n for (let start = 0; start < targets.length; start += FCM_BATCH) {\n const batch = targets.slice(start, start + FCM_BATCH)\n try {\n const { responses } = await messaging.sendEach(batch.map((target) => fcmMessage(target.token, message)))\n for (const [index] of batch.entries()) {\n const response = responses[index]\n if (response?.success) outcomes.push('sent')\n else outcomes.push(GONE.has(response?.error?.code ?? '') ? 'prune' : 'failed')\n }\n } catch {\n outcomes.push(...batch.map((): PushOutcome => 'failed'))\n }\n }\n return outcomes\n },\n }\n}\n\nlet configured: PushTransport | null = null\n\n/** The deployment's FCM transport, on the firebase-admin default app. */\nexport function fcmTransport(): PushTransport {\n configured ??= createFcmTransport(getMessaging(getApp()))\n return configured\n}\n"],"names":["getApp","getMessaging","FCM_BATCH","GONE","Set","fcmMessage","token","message","notification","title","body","data","android","priority","sound","createFcmTransport","messaging","send","targets","outcomes","start","length","batch","slice","responses","sendEach","map","target","index","entries","response","success","push","has","error","code","configured","fcmTransport"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;CAUC,GAED,SAASA,MAAM,QAAQ,qBAAoB;AAC3C,SAASC,YAAY,QAA+C,2BAA0B;AAC9F,OAAO,sBAAkB;AAGzB,2CAA2C,GAC3C,OAAO,MAAMC,YAAY,IAAG;AAE5B,MAAMC,OAAO,IAAIC,IAAI;IACnB;IACA;IACA;CACD;AAOD,OAAO,SAASC,WAAWC,KAAa,EAAEC,OAAoB;IAC5D,OAAO;QACLD;QACAE,cAAc;YAAEC,OAAOF,QAAQE,KAAK;WAAMF,QAAQG,IAAI,GAAG;YAAEA,MAAMH,QAAQG,IAAI;QAAC,IAAI,CAAC;QACnF,qDAAqD;QACrDC,MAAM,aAAKJ,QAAQI,IAAI;QACvBC,SAAS;YAAEC,UAAU;YAAQL,cAAc;gBAAEM,OAAO;YAAU;QAAE;IAClE;AACF;AAEA,OAAO,SAASC,mBAAmBC,SAAuB;IACxD,OAAO;QACL,MAAMC,MAAKC,OAA8B,EAAEX,OAAoB;YAC7D,MAAMY,WAA0B,EAAE;YAClC,IAAK,IAAIC,QAAQ,GAAGA,QAAQF,QAAQG,MAAM,EAAED,SAASlB,UAAW;gBAC9D,MAAMoB,QAAQJ,QAAQK,KAAK,CAACH,OAAOA,QAAQlB;gBAC3C,IAAI;oBACF,MAAM,EAAEsB,SAAS,EAAE,GAAG,MAAMR,UAAUS,QAAQ,CAACH,MAAMI,GAAG,CAAC,CAACC,SAAWtB,WAAWsB,OAAOrB,KAAK,EAAEC;oBAC9F,KAAK,MAAM,CAACqB,MAAM,IAAIN,MAAMO,OAAO,GAAI;;4BAGTC;wBAF5B,MAAMA,WAAWN,SAAS,CAACI,MAAM;wBACjC,IAAIE,4BAAAA,SAAUC,OAAO,EAAEZ,SAASa,IAAI,CAAC;6BAChCb,SAASa,IAAI,CAAC7B,KAAK8B,GAAG,SAACH,6BAAAA,kBAAAA,SAAUI,KAAK,qBAAfJ,gBAAiBK,IAAI,mBAAI,MAAM,UAAU;oBACvE;gBACF,EAAE,eAAM;oBACNhB,SAASa,IAAI,IAAIV,MAAMI,GAAG,CAAC,IAAmB;gBAChD;YACF;YACA,OAAOP;QACT;IACF;AACF;AAEA,IAAIiB,aAAmC;AAEvC,uEAAuE,GACvE,OAAO,SAASC;IACdD,qBAAAA,aAAAA,aAAerB,mBAAmBd,aAAaD;IAC/C,OAAOoC;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/push-fcm.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Firebase Cloud Messaging for the Android app (AGL-3651), through\n * firebase-admin's `getMessaging().sendEach` with the project credentials\n * the server already holds, so it needs no secret of its own. The\n * notification is shown by the system; the tap data rides in `data`, and\n * Android delivers it at high priority.\n *\n * A token FCM reports unregistered or invalid is gone, and the row is pruned.\n *\n * Server-only, imported by `push-delivery.ts` only when a device is on FCM.\n */\n\nimport { getApp } from 'firebase-admin/app'\nimport { getMessaging, type BatchResponse, type TokenMessage } from 'firebase-admin/messaging'\nimport './firebase-admin'\nimport type { NotificationSound } from '@aglyn/aglyn/app-utils/notification-sounds'\nimport type { PushMessage, PushOutcome, PushTarget, PushTransport } from './push-delivery'\n\n/** `sendEach` takes at most 500 messages. */\nexport const FCM_BATCH = 500\n\nconst GONE = new Set([\n 'messaging/registration-token-not-registered',\n 'messaging/invalid-registration-token',\n 'messaging/invalid-argument',\n])\n\n/** The slice of firebase-admin's Messaging this transport uses; injected in tests. */\nexport interface FcmMessaging {\n sendEach(messages: TokenMessage[]): Promise<BatchResponse>\n}\n\n/**\n * One device's message. The person's sound is the channel's: an Android\n * channel's sound is fixed when the app creates it, so the app makes one\n * channel per sound and the message names it. A build that has no such\n * channel yet shows it on the manifest's default channel.\n */\nexport function fcmMessage(token: string, message: PushMessage, sound?: NotificationSound): TokenMessage {\n return {\n token,\n notification: { title: message.title, ...(message.body ? { body: message.body } : {}) },\n // FCM data values are strings; MobilePushData's are.\n data: { ...message.data },\n android: {\n priority: 'high',\n notification: sound ? { sound: sound.android, channelId: sound.android } : { sound: 'default' },\n },\n }\n}\n\nexport function createFcmTransport(messaging: FcmMessaging): PushTransport {\n return {\n async send(targets: readonly PushTarget[], message: PushMessage): Promise<PushOutcome[]> {\n const outcomes: PushOutcome[] = []\n for (let start = 0; start < targets.length; start += FCM_BATCH) {\n const batch = targets.slice(start, start + FCM_BATCH)\n try {\n const { responses } = await messaging.sendEach(batch.map((target) => fcmMessage(target.token, message, target.sound)))\n for (const [index] of batch.entries()) {\n const response = responses[index]\n if (response?.success) outcomes.push('sent')\n else outcomes.push(GONE.has(response?.error?.code ?? '') ? 'prune' : 'failed')\n }\n } catch {\n outcomes.push(...batch.map((): PushOutcome => 'failed'))\n }\n }\n return outcomes\n },\n }\n}\n\nlet configured: PushTransport | null = null\n\n/** The deployment's FCM transport, on the firebase-admin default app. */\nexport function fcmTransport(): PushTransport {\n configured ??= createFcmTransport(getMessaging(getApp()))\n return configured\n}\n"],"names":["getApp","getMessaging","FCM_BATCH","GONE","Set","fcmMessage","token","message","sound","notification","title","body","data","android","priority","channelId","createFcmTransport","messaging","send","targets","outcomes","start","length","batch","slice","responses","sendEach","map","target","index","entries","response","success","push","has","error","code","configured","fcmTransport"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;CAUC,GAED,SAASA,MAAM,QAAQ,qBAAoB;AAC3C,SAASC,YAAY,QAA+C,2BAA0B;AAC9F,OAAO,sBAAkB;AAIzB,2CAA2C,GAC3C,OAAO,MAAMC,YAAY,IAAG;AAE5B,MAAMC,OAAO,IAAIC,IAAI;IACnB;IACA;IACA;CACD;AAOD;;;;;CAKC,GACD,OAAO,SAASC,WAAWC,KAAa,EAAEC,OAAoB,EAAEC,KAAyB;IACvF,OAAO;QACLF;QACAG,cAAc;YAAEC,OAAOH,QAAQG,KAAK;WAAMH,QAAQI,IAAI,GAAG;YAAEA,MAAMJ,QAAQI,IAAI;QAAC,IAAI,CAAC;QACnF,qDAAqD;QACrDC,MAAM,aAAKL,QAAQK,IAAI;QACvBC,SAAS;YACPC,UAAU;YACVL,cAAcD,QAAQ;gBAAEA,OAAOA,MAAMK,OAAO;gBAAEE,WAAWP,MAAMK,OAAO;YAAC,IAAI;gBAAEL,OAAO;YAAU;QAChG;IACF;AACF;AAEA,OAAO,SAASQ,mBAAmBC,SAAuB;IACxD,OAAO;QACL,MAAMC,MAAKC,OAA8B,EAAEZ,OAAoB;YAC7D,MAAMa,WAA0B,EAAE;YAClC,IAAK,IAAIC,QAAQ,GAAGA,QAAQF,QAAQG,MAAM,EAAED,SAASnB,UAAW;gBAC9D,MAAMqB,QAAQJ,QAAQK,KAAK,CAACH,OAAOA,QAAQnB;gBAC3C,IAAI;oBACF,MAAM,EAAEuB,SAAS,EAAE,GAAG,MAAMR,UAAUS,QAAQ,CAACH,MAAMI,GAAG,CAAC,CAACC,SAAWvB,WAAWuB,OAAOtB,KAAK,EAAEC,SAASqB,OAAOpB,KAAK;oBACnH,KAAK,MAAM,CAACqB,MAAM,IAAIN,MAAMO,OAAO,GAAI;;4BAGTC;wBAF5B,MAAMA,WAAWN,SAAS,CAACI,MAAM;wBACjC,IAAIE,4BAAAA,SAAUC,OAAO,EAAEZ,SAASa,IAAI,CAAC;6BAChCb,SAASa,IAAI,CAAC9B,KAAK+B,GAAG,SAACH,6BAAAA,kBAAAA,SAAUI,KAAK,qBAAfJ,gBAAiBK,IAAI,mBAAI,MAAM,UAAU;oBACvE;gBACF,EAAE,eAAM;oBACNhB,SAASa,IAAI,IAAIV,MAAMI,GAAG,CAAC,IAAmB;gBAChD;YACF;YACA,OAAOP;QACT;IACF;AACF;AAEA,IAAIiB,aAAmC;AAEvC,uEAAuE,GACvE,OAAO,SAASC;IACdD,qBAAAA,aAAAA,aAAerB,mBAAmBf,aAAaD;IAC/C,OAAOqC;AACT"}
@@ -257,6 +257,10 @@ export declare function resetServerErrorsForTests(): void;
257
257
  * a door that cannot go red.
258
258
  */
259
259
  export declare const BEACON_HEARTBEAT_DOC_PREFIX = "beaconHeartbeat_";
260
+ /** How often one instance rewrites a service's marker (AGL-3932). */
261
+ export declare const BEACON_HEARTBEAT_RECORD_MIN_INTERVAL_MS: number;
262
+ /** Test seam. */
263
+ export declare function resetBeaconHeartbeatRecordForTests(): void;
260
264
  /**
261
265
  * Record that a heartbeat reached Cloud Logging (AGL-2713).
262
266
  *
@@ -265,10 +269,14 @@ export declare const BEACON_HEARTBEAT_DOC_PREFIX = "beaconHeartbeat_";
265
269
  * probe it is attached to fails. A write that does not land simply means the
266
270
  * next miss is graded without it, which is the safe direction.
267
271
  *
268
- * The caller is memoized per instance on a five-minute TTL, so the write rate
269
- * is one per instance per five minutes however hard the public endpoint is
270
- * hit — orders of magnitude under the per-document ceiling that produced
271
- * AGL-2404's contention storm.
272
+ * The write is spaced per instance to one per {@link BEACON_HEARTBEAT_RECORD_MIN_INTERVAL_MS}
273
+ * per service, however hard the public endpoint is hit — orders of magnitude
274
+ * under the per-document ceiling that produced AGL-2404's contention storm.
275
+ * The callers' own memo (two minutes since AGL-2947) was never enough on its
276
+ * own: three uptime regions and a probe service each land on their own
277
+ * instance, and the sample of 2026-10-18 showed a marker write for nearly
278
+ * every probe, ~1,000 a day (AGL-3932). A marker is only ever read to
279
+ * forgive a miss inside the fifteen-minute grace, so five minutes is fresh.
272
280
  */
273
281
  export declare function recordBeaconHeartbeat(service: string, options?: {
274
282
  now?: number;
@@ -478,6 +478,11 @@ import { checkRateLimit, DEFAULT_RATE_LIMIT, DEFAULT_RATE_WINDOW_MS } from "./ap
478
478
  * and the marker's disappearance changes nothing.
479
479
  */ const BEACON_HEARTBEAT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
480
480
  /** How long the failure path waits for the marker before giving up on it. */ const BEACON_HEARTBEAT_READ_BUDGET_MS = 2000;
481
+ /** How often one instance rewrites a service's marker (AGL-3932). */ export const BEACON_HEARTBEAT_RECORD_MIN_INTERVAL_MS = 5 * 60000;
482
+ /** When this instance last recorded each service's marker. */ const lastBeaconHeartbeatRecord = new Map();
483
+ /** Test seam. */ export function resetBeaconHeartbeatRecordForTests() {
484
+ lastBeaconHeartbeatRecord.clear();
485
+ }
481
486
  /**
482
487
  * Record that a heartbeat reached Cloud Logging (AGL-2713).
483
488
  *
@@ -486,13 +491,22 @@ import { checkRateLimit, DEFAULT_RATE_LIMIT, DEFAULT_RATE_WINDOW_MS } from "./ap
486
491
  * probe it is attached to fails. A write that does not land simply means the
487
492
  * next miss is graded without it, which is the safe direction.
488
493
  *
489
- * The caller is memoized per instance on a five-minute TTL, so the write rate
490
- * is one per instance per five minutes however hard the public endpoint is
491
- * hit — orders of magnitude under the per-document ceiling that produced
492
- * AGL-2404's contention storm.
494
+ * The write is spaced per instance to one per {@link BEACON_HEARTBEAT_RECORD_MIN_INTERVAL_MS}
495
+ * per service, however hard the public endpoint is hit — orders of magnitude
496
+ * under the per-document ceiling that produced AGL-2404's contention storm.
497
+ * The callers' own memo (two minutes since AGL-2947) was never enough on its
498
+ * own: three uptime regions and a probe service each land on their own
499
+ * instance, and the sample of 2026-10-18 showed a marker write for nearly
500
+ * every probe, ~1,000 a day (AGL-3932). A marker is only ever read to
501
+ * forgive a miss inside the fifteen-minute grace, so five minutes is fresh.
493
502
  */ export function recordBeaconHeartbeat(service, options) {
494
503
  var _ref;
495
504
  const nowMs = (_ref = options == null ? void 0 : options.now) != null ? _ref : Date.now();
505
+ const last = lastBeaconHeartbeatRecord.get(service);
506
+ // `>= 0` so a clock that steps backwards records rather than going quiet.
507
+ if (last !== undefined && nowMs - last >= 0 && nowMs - last < BEACON_HEARTBEAT_RECORD_MIN_INTERVAL_MS) {
508
+ return;
509
+ }
496
510
  let firestore;
497
511
  try {
498
512
  var _ref1;
@@ -503,6 +517,7 @@ import { checkRateLimit, DEFAULT_RATE_LIMIT, DEFAULT_RATE_WINDOW_MS } from "./ap
503
517
  // miss is lost, and a miss with no evidence reds.
504
518
  return;
505
519
  }
520
+ lastBeaconHeartbeatRecord.set(service, nowMs);
506
521
  void Promise.resolve(firestore.collection(RATE_LIMIT_COLLECTION).doc(`${BEACON_HEARTBEAT_DOC_PREFIX}${service}`).set({
507
522
  // NOT `lastAtMs`, NOT `refusedAtMs`, NOT `erroredAtMs`, NOT
508
523
  // `servedAtMs` — see the prefix doc above.