@aglyn/tenant-data-admin 1.0.0-beta.218 → 1.0.0-beta.220

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 (156) hide show
  1. package/package.json +8 -8
  2. package/src/lib/server/api-http.js +5 -1
  3. package/src/lib/server/api-http.js.map +1 -1
  4. package/src/lib/server/api-v1-description.d.ts +112 -0
  5. package/src/lib/server/api-v1-description.js +126 -0
  6. package/src/lib/server/api-v1-description.js.map +1 -0
  7. package/src/lib/server/api-v1-kit.d.ts +163 -0
  8. package/src/lib/server/api-v1-kit.js +191 -0
  9. package/src/lib/server/api-v1-kit.js.map +1 -0
  10. package/src/lib/server/api-v1-resources.d.ts +143 -0
  11. package/src/lib/server/api-v1-resources.js +125 -0
  12. package/src/lib/server/api-v1-resources.js.map +1 -0
  13. package/src/lib/server/campaign-conversion-attribution.d.ts +1 -1
  14. package/src/lib/server/campaign-conversion-attribution.js +3 -3
  15. package/src/lib/server/campaign-conversion-attribution.js.map +1 -1
  16. package/src/lib/server/card-payment-velocity.d.ts +9 -0
  17. package/src/lib/server/card-payment-velocity.js +28 -2
  18. package/src/lib/server/card-payment-velocity.js.map +1 -1
  19. package/src/lib/server/consent-group-carry.js +1 -1
  20. package/src/lib/server/consent-group-carry.js.map +1 -1
  21. package/src/lib/server/consent-group-change.d.ts +2 -1
  22. package/src/lib/server/consent-group-change.js +43 -18
  23. package/src/lib/server/consent-group-change.js.map +1 -1
  24. package/src/lib/server/contact-email-index.d.ts +22 -0
  25. package/src/lib/server/contact-email-index.js +108 -0
  26. package/src/lib/server/contact-email-index.js.map +1 -1
  27. package/src/lib/server/crm-email-activity.d.ts +1 -1
  28. package/src/lib/server/crm-email-activity.js +1 -1
  29. package/src/lib/server/crm-email-activity.js.map +1 -1
  30. package/src/lib/server/crm-records.d.ts +9 -1
  31. package/src/lib/server/crm-records.js +19 -2
  32. package/src/lib/server/crm-records.js.map +1 -1
  33. package/src/lib/server/cron-auth.d.ts +44 -0
  34. package/src/lib/server/cron-auth.js +76 -0
  35. package/src/lib/server/cron-auth.js.map +1 -0
  36. package/src/lib/server/dataset-live-pages.js +6 -6
  37. package/src/lib/server/dataset-live-pages.js.map +1 -1
  38. package/src/lib/server/duplicate-resource.d.ts +26 -0
  39. package/src/lib/server/duplicate-resource.js +47 -25
  40. package/src/lib/server/duplicate-resource.js.map +1 -1
  41. package/src/lib/server/dynamic-list-materialize.js +6 -3
  42. package/src/lib/server/dynamic-list-materialize.js.map +1 -1
  43. package/src/lib/server/email-flow-gate.js +2 -2
  44. package/src/lib/server/email-flow-gate.js.map +1 -1
  45. package/src/lib/server/email-suppression.d.ts +11 -0
  46. package/src/lib/server/email-suppression.js +37 -2
  47. package/src/lib/server/email-suppression.js.map +1 -1
  48. package/src/lib/server/email-unsubscribe-link.d.ts +8 -5
  49. package/src/lib/server/email-unsubscribe-link.js +7 -7
  50. package/src/lib/server/email-unsubscribe-link.js.map +1 -1
  51. package/src/lib/server/erase.d.ts +19 -33
  52. package/src/lib/server/erase.js +37 -162
  53. package/src/lib/server/erase.js.map +1 -1
  54. package/src/lib/server/host-email-tokens.js +1 -1
  55. package/src/lib/server/host-email-tokens.js.map +1 -1
  56. package/src/lib/server/host-memberships.js +3 -3
  57. package/src/lib/server/host-memberships.js.map +1 -1
  58. package/src/lib/server/host-visitor-records.d.ts +32 -4
  59. package/src/lib/server/host-visitor-records.js +73 -14
  60. package/src/lib/server/host-visitor-records.js.map +1 -1
  61. package/src/lib/server/hosted-page-review.d.ts +27 -0
  62. package/src/lib/server/hosted-page-review.js +149 -12
  63. package/src/lib/server/hosted-page-review.js.map +1 -1
  64. package/src/lib/server/media-cdn-rate-limit.d.ts +6 -3
  65. package/src/lib/server/media-cdn-rate-limit.js +6 -3
  66. package/src/lib/server/media-cdn-rate-limit.js.map +1 -1
  67. package/src/lib/server/member-email-aliases.d.ts +10 -2
  68. package/src/lib/server/member-email-aliases.js +26 -2
  69. package/src/lib/server/member-email-aliases.js.map +1 -1
  70. package/src/lib/server/new-account-announcement.d.ts +62 -0
  71. package/src/lib/server/new-account-announcement.js +77 -0
  72. package/src/lib/server/new-account-announcement.js.map +1 -0
  73. package/src/lib/server/notifications.d.ts +22 -2
  74. package/src/lib/server/notifications.js +40 -3
  75. package/src/lib/server/notifications.js.map +1 -1
  76. package/src/lib/server/operator-alerts.d.ts +7 -1
  77. package/src/lib/server/operator-alerts.js +5 -3
  78. package/src/lib/server/operator-alerts.js.map +1 -1
  79. package/src/lib/server/org-containers.d.ts +66 -0
  80. package/src/lib/server/org-containers.js +95 -0
  81. package/src/lib/server/org-containers.js.map +1 -0
  82. package/src/lib/server/org-member-notice.js +3 -2
  83. package/src/lib/server/org-member-notice.js.map +1 -1
  84. package/src/lib/server/payment-fraud-signal.js +5 -1
  85. package/src/lib/server/payment-fraud-signal.js.map +1 -1
  86. package/src/lib/server/{connect-payout-failure.d.ts → payment-provider-stripe-connect-payouts.d.ts} +3 -0
  87. package/src/lib/server/{connect-payout-failure.js → payment-provider-stripe-connect-payouts.js} +36 -2
  88. package/src/lib/server/payment-provider-stripe-connect-payouts.js.map +1 -0
  89. package/src/lib/server/{connect-account-status.d.ts → payment-provider-stripe-connect-status.d.ts} +3 -0
  90. package/src/lib/server/{connect-account-status.js → payment-provider-stripe-connect-status.js} +1 -1
  91. package/src/lib/server/payment-provider-stripe-connect-status.js.map +1 -0
  92. package/src/lib/server/{stripe-account-mode.d.ts → payment-provider-stripe-connect.d.ts} +45 -70
  93. package/src/lib/server/{stripe-account-mode.js → payment-provider-stripe-connect.js} +78 -52
  94. package/src/lib/server/payment-provider-stripe-connect.js.map +1 -0
  95. package/src/lib/server/payment-provider.d.ts +173 -0
  96. package/src/lib/server/payment-provider.js +70 -0
  97. package/src/lib/server/payment-provider.js.map +1 -0
  98. package/src/lib/server/payment-risk-record.d.ts +1 -1
  99. package/src/lib/server/payment-risk-record.js +3 -1
  100. package/src/lib/server/payment-risk-record.js.map +1 -1
  101. package/src/lib/server/personal-data-export.js +1 -1
  102. package/src/lib/server/personal-data-export.js.map +1 -1
  103. package/src/lib/server/platform-marketing-consent.d.ts +1 -1
  104. package/src/lib/server/platform-marketing-consent.js +1 -1
  105. package/src/lib/server/platform-marketing-consent.js.map +1 -1
  106. package/src/lib/server/rate-limit-store.js +13 -3
  107. package/src/lib/server/rate-limit-store.js.map +1 -1
  108. package/src/lib/server/realm-plugins.js +8 -3
  109. package/src/lib/server/realm-plugins.js.map +1 -1
  110. package/src/lib/server/retained-refusals.d.ts +142 -0
  111. package/src/lib/server/retained-refusals.js +325 -0
  112. package/src/lib/server/retained-refusals.js.map +1 -0
  113. package/src/lib/server/risk-notice.d.ts +32 -1
  114. package/src/lib/server/risk-notice.js +90 -28
  115. package/src/lib/server/risk-notice.js.map +1 -1
  116. package/src/lib/server/sending-domains.d.ts +17 -0
  117. package/src/lib/server/sending-domains.js +28 -4
  118. package/src/lib/server/sending-domains.js.map +1 -1
  119. package/src/lib/server/sso-enforcement.js +7 -2
  120. package/src/lib/server/sso-enforcement.js.map +1 -1
  121. package/src/lib/server/staff-alert-email.js +4 -2
  122. package/src/lib/server/staff-alert-email.js.map +1 -1
  123. package/src/lib/server/test-firestore-queries.d.ts +7 -0
  124. package/src/lib/server/test-firestore-queries.js +70 -27
  125. package/src/lib/server/test-firestore-queries.js.map +1 -1
  126. package/src/lib/server/{email-topic-confirmation.js → topic-subscriptions.js} +15 -11
  127. package/src/lib/server/topic-subscriptions.js.map +1 -0
  128. package/src/lib/server/upsert-contact.d.ts +46 -1
  129. package/src/lib/server/upsert-contact.js +87 -20
  130. package/src/lib/server/upsert-contact.js.map +1 -1
  131. package/src/tenancy.d.ts +5 -8
  132. package/src/tenancy.js +12 -13
  133. package/src/tenancy.js.map +1 -1
  134. package/src/lib/server/connect-account-status.js.map +0 -1
  135. package/src/lib/server/connect-payout-failure.js.map +0 -1
  136. package/src/lib/server/contact-email-engagement.d.ts +0 -32
  137. package/src/lib/server/contact-email-engagement.js +0 -145
  138. package/src/lib/server/contact-email-engagement.js.map +0 -1
  139. package/src/lib/server/contact-lifecycle-floor.d.ts +0 -89
  140. package/src/lib/server/contact-lifecycle-floor.js +0 -91
  141. package/src/lib/server/contact-lifecycle-floor.js.map +0 -1
  142. package/src/lib/server/contact-merge.d.ts +0 -55
  143. package/src/lib/server/contact-merge.js +0 -288
  144. package/src/lib/server/contact-merge.js.map +0 -1
  145. package/src/lib/server/crm-booking-activity.d.ts +0 -86
  146. package/src/lib/server/crm-booking-activity.js +0 -257
  147. package/src/lib/server/crm-booking-activity.js.map +0 -1
  148. package/src/lib/server/crm-inbound-email.d.ts +0 -145
  149. package/src/lib/server/crm-inbound-email.js +0 -297
  150. package/src/lib/server/crm-inbound-email.js.map +0 -1
  151. package/src/lib/server/email-topic-confirmation.js.map +0 -1
  152. package/src/lib/server/form-dataset-binding-token.d.ts +0 -35
  153. package/src/lib/server/form-dataset-binding-token.js +0 -107
  154. package/src/lib/server/form-dataset-binding-token.js.map +0 -1
  155. package/src/lib/server/stripe-account-mode.js.map +0 -1
  156. /package/src/lib/server/{email-topic-confirmation.d.ts → topic-subscriptions.d.ts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/operator-alerts.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\nimport { createHash, createHmac } from 'node:crypto'\nimport {\n effectiveOperatorAlertSetting,\n OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE,\n OPERATOR_ALERT_TIER_LABELS,\n renderOperatorAlertTemplate,\n type AglynNotificationType,\n type OperatorAlertContext,\n type OperatorAlertDefinition,\n type OperatorAlertSettings,\n type OperatorAlertTypeSetting,\n} from '@aglyn/aglyn/server'\nimport {\n getOperatorAlert,\n registerOperatorAlerts,\n} from '@aglyn/aglyn/plugin-manager/operator-alerts'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { isEmailConfigured, type SendEmailResult } from '@aglyn/shared-util-email'\nimport firebaseAdmin from './firebase-admin'\n\n/**\n * RAISING AN OPERATOR ALERT (AGL-3377): the one server entry point every\n * alert in the registry goes through.\n *\n * In order, for one call:\n *\n * 1. The type is looked up in the registry (core's catalog plus what plugins\n * registered). A plugin may pass its definition itself, which registers\n * it in this process if its declarations have not loaded yet.\n * 2. A `dedupeKey` is claimed against `operatorAlertState`, so a condition\n * that flaps inside the type's window is told once, and a type with\n * `minOccurrences` fires only once it has recurred that often.\n * 3. The staff console notification is written for every staff member, as\n * `notifyStaff` always has.\n * 4. Staff's switches (`platformSettings/operatorAlerts`, coded defaults\n * until changed) decide the rest: off is console only, `digest` queues it\n * for the once-a-day digest, `immediate` emails the operator now.\n * 5. The email is the `operator-alert` system email, to\n * `resolveStaffAlertRecipients()`; the optional out-of-band webhook\n * (`OPERATOR_ALERT_WEBHOOK_URL`) gets the same alert beside it, so a mail\n * provider that is itself the outage still reaches somebody.\n *\n * Never throws: an alert is raised from inside the failure it reports, and a\n * second failure there must not replace the first.\n */\n\n/** Where staff's per-type switches live. */\nexport const OPERATOR_ALERT_SETTINGS_COLLECTION = 'platformSettings'\nexport const OPERATOR_ALERT_SETTINGS_DOC = 'operatorAlerts'\n/** One document per (type, dedupeKey): when it last fired, how often since. */\nexport const OPERATOR_ALERT_STATE_COLLECTION = 'operatorAlertState'\n/** Alerts waiting for the daily digest. */\nexport const OPERATOR_ALERT_DIGEST_COLLECTION = 'operatorAlertDigest'\n\n/** The hour, UTC, the digest goes out when staff have not chosen one. */\nexport const OPERATOR_ALERT_DIGEST_DEFAULT_HOUR_UTC = 14\n\nexport interface OperatorAlertSettingsDoc extends OperatorAlertSettings {\n /** The hour of the day, UTC, the digest is sent. */\n digestHourUtc?: number\n updatedAtMs?: number\n updatedByEmail?: string | null\n}\n\nexport interface RaiseOperatorAlertOptions {\n /**\n * What makes two raises the SAME alert — a dispute id, an org and month, a\n * check id. Absent never dedupes: every raise is told.\n */\n dedupeKey?: string\n /** Values for the definition's `{{tokens}}`. Never personal data. */\n context?: OperatorAlertContext\n /** A console path or absolute URL; overrides the definition's link. */\n url?: string\n /** The title as written by the caller; overrides the rendered one. */\n subject?: string\n /** The body as written by the caller; overrides the rendered one. */\n body?: string\n orgId?: string\n hostId?: string\n}\n\nexport type OperatorAlertOutcome =\n | 'deduped'\n | 'below-threshold'\n | 'console-only'\n | 'queued'\n | 'delivered'\n | 'undelivered'\n\nexport interface OperatorAlertResult {\n outcome: OperatorAlertOutcome\n type: string\n email?: SendEmailResult\n webhook?: OperatorAlertWebhookResult\n}\n\nexport type OperatorAlertWebhookResult =\n | { posted: true; status: number }\n | { posted: false; reason: 'unconfigured' | 'refused' | 'network'; status?: number }\n\n/** One alert, rendered, as it is delivered and queued. */\nexport interface RenderedOperatorAlert {\n type: string\n label: string\n tier: OperatorAlertDefinition['tier']\n category: OperatorAlertDefinition['category']\n title: string\n body: string\n /** Console path or absolute URL; `''` when there is none. */\n link: string\n notificationType: AglynNotificationType\n orgId?: string\n hostId?: string\n}\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n// ── Settings ────────────────────────────────────────────────────────────────\n\nconst SETTINGS_TTL_MS = 15_000\nlet settingsCache: { at: number; doc: OperatorAlertSettingsDoc } | undefined\n\n/** Drop the in-process settings cache; the console calls it after a write. */\nexport function invalidateOperatorAlertSettingsCache(): void {\n settingsCache = undefined\n}\n\n/** Clamps a stored settings document to what the pipeline understands. */\nexport function normalizeOperatorAlertSettings(\n raw: unknown,\n): OperatorAlertSettingsDoc {\n const source = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const types: Record<string, OperatorAlertTypeSetting> = {}\n const rawTypes = source['types']\n if (rawTypes && typeof rawTypes === 'object') {\n for (const [type, value] of Object.entries(rawTypes as Record<string, unknown>)) {\n if (!type || !value || typeof value !== 'object') continue\n const entry = value as Record<string, unknown>\n const setting: OperatorAlertTypeSetting = {}\n if (typeof entry['enabled'] === 'boolean') setting.enabled = entry['enabled']\n if (entry['delivery'] === 'immediate' || entry['delivery'] === 'digest') {\n setting.delivery = entry['delivery']\n }\n if (Object.keys(setting).length) types[type] = setting\n }\n }\n const hour = Number(source['digestHourUtc'])\n return {\n types,\n digestHourUtc:\n Number.isInteger(hour) && hour >= 0 && hour <= 23\n ? hour\n : OPERATOR_ALERT_DIGEST_DEFAULT_HOUR_UTC,\n ...(typeof source['updatedAtMs'] === 'number'\n ? { updatedAtMs: source['updatedAtMs'] as number }\n : {}),\n ...(typeof source['updatedByEmail'] === 'string'\n ? { updatedByEmail: source['updatedByEmail'] as string }\n : {}),\n }\n}\n\n/**\n * Staff's switches. An unreadable document is the coded defaults, uncached:\n * an alert must still go out when the settings cannot be read.\n */\nexport async function readOperatorAlertSettings(): Promise<OperatorAlertSettingsDoc> {\n const now = Date.now()\n if (settingsCache && now - settingsCache.at < SETTINGS_TTL_MS) return settingsCache.doc\n try {\n const snapshot = await firestore()\n .collection(OPERATOR_ALERT_SETTINGS_COLLECTION)\n .doc(OPERATOR_ALERT_SETTINGS_DOC)\n .get()\n const doc = normalizeOperatorAlertSettings(snapshot.exists ? snapshot.data() : null)\n settingsCache = { at: now, doc }\n return doc\n } catch (error) {\n console.error('[operator-alerts] settings unreadable; using the defaults', error)\n return normalizeOperatorAlertSettings(null)\n }\n}\n\n// ── Dedupe ──────────────────────────────────────────────────────────────────\n\n/** Keys this instance fired, and until when they stay quiet. */\nconst firedLocally = new Map<string, number>()\nconst FIRED_LOCALLY_MAX = 500\n\nfunction stateDocId(type: string, dedupeKey: string): string {\n return createHash('sha256').update(`${type}\\u0000${dedupeKey}`).digest('hex').slice(0, 40)\n}\n\nexport type OperatorAlertClaim =\n | { fire: true; repeats: number }\n | { fire: false; reason: 'deduped' | 'below-threshold' }\n\n/**\n * Whether a raise with this key fires now. One transaction on the key's\n * state document: inside the window after a fire it is counted and\n * suppressed; before it reaches `minOccurrences` it is counted and held.\n * A store that cannot be read FIRES — a duplicate beats a silence.\n */\nexport async function claimOperatorAlert(\n definition: Pick<OperatorAlertDefinition, 'type' | 'dedupeWindowMinutes' | 'minOccurrences'>,\n dedupeKey: string,\n now = Date.now(),\n): Promise<OperatorAlertClaim> {\n const windowMs = Math.max(0, definition.dedupeWindowMinutes) * 60_000\n const minOccurrences = Math.max(1, Math.floor(definition.minOccurrences ?? 1))\n if (!windowMs) return { fire: true, repeats: 0 }\n const localKey = `${definition.type}\\u0000${dedupeKey}`\n const quietUntil = firedLocally.get(localKey)\n if (quietUntil && quietUntil > now) return { fire: false, reason: 'deduped' }\n try {\n const ref = firestore()\n .collection(OPERATOR_ALERT_STATE_COLLECTION)\n .doc(stateDocId(definition.type, dedupeKey))\n const claim = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const state = (snapshot.exists ? snapshot.data() : {}) as Record<string, unknown>\n const lastFiredAtMs = Number(state['lastFiredAtMs'] ?? 0)\n const base = { type: definition.type, dedupeKey: dedupeKey.slice(0, 300), updatedAtMs: now }\n if (lastFiredAtMs && now - lastFiredAtMs < windowMs) {\n transaction.set(ref, { ...base, suppressed: Number(state['suppressed'] ?? 0) + 1 }, { merge: true })\n return { fire: false, reason: 'deduped' } as const\n }\n const windowStartMs = Number(state['windowStartMs'] ?? 0)\n const inWindow = windowStartMs && now - windowStartMs < windowMs\n const occurrences = (inWindow ? Number(state['occurrences'] ?? 0) : 0) + 1\n if (occurrences < minOccurrences) {\n transaction.set(\n ref,\n { ...base, occurrences, windowStartMs: inWindow ? windowStartMs : now },\n { merge: true },\n )\n return { fire: false, reason: 'below-threshold' } as const\n }\n transaction.set(\n ref,\n {\n ...base,\n lastFiredAtMs: now,\n occurrences: 0,\n windowStartMs: 0,\n suppressed: 0,\n fired: Number(state['fired'] ?? 0) + 1,\n },\n { merge: true },\n )\n return { fire: true, repeats: Number(state['suppressed'] ?? 0) } as const\n })\n if (claim.fire) {\n if (firedLocally.size >= FIRED_LOCALLY_MAX) firedLocally.clear()\n firedLocally.set(localKey, now + windowMs)\n }\n return claim\n } catch (error) {\n console.error(`[operator-alerts] dedupe unavailable for ${definition.type}; firing`, error)\n return { fire: true, repeats: 0 }\n }\n}\n\n// ── Out-of-band webhook ─────────────────────────────────────────────────────\n\nconst WEBHOOK_TIMEOUT_MS = 5_000\n\n/** The webhook URL, when one is configured and is http(s). */\nexport function operatorAlertWebhookUrl(): string {\n const value = String(process.env['OPERATOR_ALERT_WEBHOOK_URL'] ?? '').trim()\n return /^https?:\\/\\/\\S+$/i.test(value) ? value : ''\n}\n\n/**\n * The JSON the webhook receives. `text` is what a Slack-compatible incoming\n * webhook renders on its own; `alert` carries the fields for anything that\n * wants to route on them.\n */\nexport function operatorAlertWebhookPayload(\n alerts: readonly RenderedOperatorAlert[],\n options: { digest?: boolean; now?: number } = {},\n): Record<string, unknown> {\n const origin = consoleOrigin()\n const lines = alerts.map((alert) => {\n const link = operatorAlertAbsoluteLink(alert.link)\n return [\n `[${OPERATOR_ALERT_TIER_LABELS[alert.tier]}] ${alert.title}`,\n alert.body,\n link,\n ]\n .filter(Boolean)\n .join('\\n')\n })\n const text = options.digest\n ? [`Operator digest: ${alerts.length} alert${alerts.length === 1 ? '' : 's'}`, ...lines].join('\\n\\n')\n : lines.join('\\n\\n')\n const occurredAt = new Date(options.now ?? Date.now()).toISOString()\n const shaped = alerts.map((alert) => ({\n type: alert.type,\n tier: alert.tier,\n category: alert.category,\n title: alert.title,\n body: alert.body,\n url: operatorAlertAbsoluteLink(alert.link) || null,\n }))\n return {\n text,\n ...(options.digest ? { digest: shaped } : { alert: shaped[0] ?? null }),\n occurredAt,\n ...(origin ? { install: origin } : {}),\n }\n}\n\n/**\n * Posts alerts to `OPERATOR_ALERT_WEBHOOK_URL`, signed when\n * `OPERATOR_ALERT_WEBHOOK_SECRET` is set: `x-operator-alert-timestamp` is the\n * Unix time and `x-operator-alert-signature` is `sha256=` plus the hex HMAC\n * of `{timestamp}.{body}`. Unset means email only. Never throws.\n */\nexport async function postOperatorAlertWebhook(\n alerts: readonly RenderedOperatorAlert[],\n options: { digest?: boolean; now?: number } = {},\n): Promise<OperatorAlertWebhookResult> {\n const url = operatorAlertWebhookUrl()\n if (!url || !alerts.length) return { posted: false, reason: 'unconfigured' }\n const body = JSON.stringify(operatorAlertWebhookPayload(alerts, options))\n const headers: Record<string, string> = { 'content-type': 'application/json' }\n const secret = String(process.env['OPERATOR_ALERT_WEBHOOK_SECRET'] ?? '').trim()\n if (secret) {\n const timestamp = String(Math.floor((options.now ?? Date.now()) / 1000))\n headers['x-operator-alert-timestamp'] = timestamp\n headers['x-operator-alert-signature'] =\n 'sha256=' + createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex')\n }\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body,\n redirect: 'manual',\n signal: AbortSignal.timeout(WEBHOOK_TIMEOUT_MS),\n })\n if (response.ok) return { posted: true, status: response.status }\n console.error(`[operator-alerts] webhook answered ${response.status}`)\n return { posted: false, reason: 'refused', status: response.status }\n } catch (error) {\n console.error('[operator-alerts] webhook unreachable', error)\n return { posted: false, reason: 'network' }\n }\n}\n\n// ── Links ───────────────────────────────────────────────────────────────────\n\nfunction consoleOrigin(): string {\n return String(process.env['NEXT_PUBLIC_CONSOLE_URL'] ?? '').trim().replace(/\\/+$/, '')\n}\n\n/** A console path as an inbox or webhook can follow it, or `''`. */\nexport function operatorAlertAbsoluteLink(link: string | undefined | null): string {\n const value = String(link ?? '').trim()\n if (!value) return ''\n if (/^https?:\\/\\//i.test(value)) return value\n const origin = consoleOrigin()\n return origin && value.startsWith('/') ? `${origin}${value}` : ''\n}\n\n/**\n * The definition's link with its tokens filled, or `''` when a token it\n * needs is missing — `/admin/orgs/` would open the wrong page.\n */\nfunction renderLink(template: string | undefined, context: OperatorAlertContext | undefined): string {\n if (!template) return ''\n const missing = [...template.matchAll(/\\{\\{\\s*([\\w.]+)\\s*\\}\\}/g)].some(([, name]) => {\n const value = context?.[name as string]\n return value === null || value === undefined || value === ''\n })\n return missing ? '' : renderOperatorAlertTemplate(template, context)\n}\n\n// ── Rendering ───────────────────────────────────────────────────────────────\n\n/** Stands in for a type nobody registered, so it is still told. */\nfunction unregisteredDefinition(type: string): OperatorAlertDefinition {\n return {\n type,\n label: type,\n description: 'An alert type this install has no registry entry for.',\n tier: 'should',\n category: 'ops',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 60,\n defaultEnabled: true,\n }\n}\n\n/** Resolves the definition a call names, registering a plugin's own. */\nexport function resolveOperatorAlertDefinition(\n type: string | OperatorAlertDefinition,\n): OperatorAlertDefinition {\n if (typeof type !== 'string') {\n const known = getOperatorAlert(type.type)\n if (known) return known\n if (type.pluginId) {\n try {\n registerOperatorAlerts([type], { pluginId: type.pluginId })\n } catch (error) {\n console.error(`[operator-alerts] ${type.type} could not be registered`, error)\n }\n }\n return type\n }\n const known = getOperatorAlert(type)\n if (known) return known\n console.error(`[operator-alerts] \"${type}\" is not a registered alert type; telling it anyway`)\n return unregisteredDefinition(type)\n}\n\nexport function renderOperatorAlert(\n definition: OperatorAlertDefinition,\n options: RaiseOperatorAlertOptions = {},\n): RenderedOperatorAlert {\n const context: OperatorAlertContext = {\n ...(options.subject ? { title: options.subject } : {}),\n ...(options.body ? { body: options.body } : {}),\n ...(options.context ?? {}),\n }\n const title =\n String(options.subject ?? '').trim() ||\n renderOperatorAlertTemplate(definition.title, context) ||\n definition.label\n const body =\n String(options.body ?? '').trim() || renderOperatorAlertTemplate(definition.body, context)\n return {\n type: definition.type,\n label: definition.label,\n tier: definition.tier,\n category: definition.category,\n title,\n body,\n link: String(options.url ?? '').trim() || renderLink(definition.link, context),\n notificationType: definition.notificationType ?? OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE,\n ...(options.orgId ? { orgId: options.orgId } : {}),\n ...(options.hostId ? { hostId: options.hostId } : {}),\n }\n}\n\n// ── The entry point ─────────────────────────────────────────────────────────\n\n/** Whether an email to the operator can go at all on this install. */\nasync function operatorEmailReachable(): Promise<boolean> {\n if (!isEmailConfigured()) return false\n const { resolveStaffAlertRecipients } = await import('./staff-alert-email')\n return (await resolveStaffAlertRecipients()).length > 0\n}\n\n/** See the module comment. Never throws. */\nexport async function raiseOperatorAlert(\n type: string | OperatorAlertDefinition,\n options: RaiseOperatorAlertOptions = {},\n): Promise<OperatorAlertResult> {\n const typeId = typeof type === 'string' ? type : type.type\n try {\n const definition = resolveOperatorAlertDefinition(type)\n const dedupeKey = String(options.dedupeKey ?? '').trim()\n let repeats = 0\n if (dedupeKey) {\n const claim = await claimOperatorAlert(definition, dedupeKey)\n if (claim.fire === false) return { outcome: claim.reason, type: typeId }\n repeats = claim.repeats\n }\n const alert = renderOperatorAlert(definition, options)\n if (repeats > 0) {\n alert.body = [alert.body, `Raised ${repeats} more time${repeats === 1 ? '' : 's'} since it was last told.`]\n .filter(Boolean)\n .join(' ')\n }\n const settings = await readOperatorAlertSettings()\n const { enabled, delivery } = effectiveOperatorAlertSetting(definition, settings)\n const emailNow = enabled && delivery === 'immediate' && (await operatorEmailReachable())\n\n const { notifyStaffConsole } = await import('./notifications')\n await notifyStaffConsole(\n {\n type: alert.notificationType,\n title: alert.title,\n ...(alert.body ? { body: alert.body } : {}),\n ...(alert.link && alert.link.startsWith('/') ? { link: alert.link } : {}),\n ...(alert.orgId ? { orgId: alert.orgId } : {}),\n ...(alert.hostId ? { hostId: alert.hostId } : {}),\n },\n // The operator is emailed; a staff member who also switched email on\n // for this category is not mailed the same alert a second time.\n emailNow ? { skipEmail: true } : {},\n )\n if (!enabled) return { outcome: 'console-only', type: typeId }\n if (delivery === 'digest') {\n await queueOperatorAlertForDigest(alert)\n return { outcome: 'queued', type: typeId }\n }\n return await deliverOperatorAlert(alert, { emailNow })\n } catch (error) {\n console.error(`[operator-alerts] ${typeId} could not be raised`, error)\n return { outcome: 'undelivered', type: typeId }\n }\n}\n\n/** Emails and posts one alert now. */\nasync function deliverOperatorAlert(\n alert: RenderedOperatorAlert,\n options: { emailNow: boolean },\n): Promise<OperatorAlertResult> {\n const { sendOperatorAlertEmail } = await import('./staff-alert-email')\n const [email, webhook] = await Promise.all([\n options.emailNow\n ? sendOperatorAlertEmail({\n title: alert.title,\n body: alert.body,\n url: operatorAlertAbsoluteLink(alert.link),\n context: `operator-alert ${alert.type}`,\n })\n : Promise.resolve<SendEmailResult>({ sent: false, reason: 'unconfigured' }),\n postOperatorAlertWebhook([alert]),\n ])\n return {\n outcome: email.sent || webhook.posted ? 'delivered' : 'undelivered',\n type: alert.type,\n email,\n webhook,\n }\n}\n\n// ── The digest ──────────────────────────────────────────────────────────────\n\nasync function queueOperatorAlertForDigest(alert: RenderedOperatorAlert): Promise<void> {\n try {\n await firestore()\n .collection(OPERATOR_ALERT_DIGEST_COLLECTION)\n .doc(createResourceUid())\n .set({ ...alert, atMs: Date.now() })\n } catch (error) {\n // The queue is the only record the digest will have; with it gone, the\n // alert goes now rather than never.\n console.error(`[operator-alerts] digest queue unavailable; sending ${alert.type} now`, error)\n await deliverOperatorAlert(alert, { emailNow: await operatorEmailReachable() })\n }\n}\n\n/** At most this many alerts are listed in one digest; the rest are counted. */\nexport const OPERATOR_DIGEST_MAX_LISTED = 50\nconst DIGEST_READ_LIMIT = 500\n\nexport interface OperatorDigestResult {\n /** Whether a digest went out (or, on a dry run, would). */\n sent: boolean\n reason?: 'not-due' | 'already-sent' | 'empty' | 'dry-run' | 'unavailable'\n count: number\n email?: SendEmailResult\n webhook?: OperatorAlertWebhookResult\n}\n\nfunction dayKey(now: number): string {\n return new Date(now).toISOString().slice(0, 10)\n}\n\n/** The state document that claims one UTC day's digest. */\nexport function operatorDigestMarkerId(now: number): string {\n return `digest-${dayKey(now)}`\n}\n\n/** The digest's body: one paragraph per alert, newest last. */\nexport function composeOperatorDigestBody(\n alerts: readonly RenderedOperatorAlert[],\n total = alerts.length,\n): string {\n const listed = alerts.slice(0, OPERATOR_DIGEST_MAX_LISTED).map((alert) => {\n const link = operatorAlertAbsoluteLink(alert.link)\n return [`• ${alert.title}`, alert.body, link].filter(Boolean).join('\\n')\n })\n const rest = total - listed.length\n if (rest > 0) listed.push(`…and ${rest} more in the staff console.`)\n return listed.join('\\n\\n')\n}\n\n/**\n * Sends the day's digest once the configured hour has passed: every queued\n * alert in one `operator-alert-digest` email and one webhook post, then\n * clears what it sent. Once per UTC day, claimed by creating\n * `operatorAlertState/digest-{day}`, so two ticks never both send it.\n */\nexport async function sendOperatorAlertDigest(\n options: { now?: number; dryRun?: boolean; force?: boolean } = {},\n): Promise<OperatorDigestResult> {\n const now = options.now ?? Date.now()\n try {\n const settings = await readOperatorAlertSettings()\n const hour = settings.digestHourUtc ?? OPERATOR_ALERT_DIGEST_DEFAULT_HOUR_UTC\n if (!options.force && new Date(now).getUTCHours() < hour) {\n return { sent: false, reason: 'not-due', count: 0 }\n }\n const collection = firestore().collection(OPERATOR_ALERT_DIGEST_COLLECTION)\n const marker = firestore()\n .collection(OPERATOR_ALERT_STATE_COLLECTION)\n .doc(operatorDigestMarkerId(now))\n if (!options.force && (await marker.get()).exists) {\n return { sent: false, reason: 'already-sent', count: 0 }\n }\n const snapshot = await collection.orderBy('atMs', 'asc').limit(DIGEST_READ_LIMIT).get()\n const queued = snapshot.docs\n if (!queued.length) return { sent: false, reason: 'empty', count: 0 }\n if (options.dryRun) return { sent: false, reason: 'dry-run', count: queued.length }\n if (!options.force) {\n try {\n await marker.create({ atMs: now, count: queued.length })\n } catch {\n return { sent: false, reason: 'already-sent', count: 0 }\n }\n }\n const alerts = queued.map((doc: any) => doc.data() as RenderedOperatorAlert)\n const { sendOperatorAlertDigestEmail } = await import('./staff-alert-email')\n const [email, webhook] = await Promise.all([\n sendOperatorAlertDigestEmail({\n date: dayKey(now),\n count: alerts.length,\n body: composeOperatorDigestBody(alerts),\n url: operatorAlertAbsoluteLink('/admin/operator-alerts'),\n }),\n postOperatorAlertWebhook(alerts, { digest: true, now }),\n ])\n if (email.sent || webhook.posted) {\n const batch = firestore().batch()\n for (const doc of queued) batch.delete(doc.ref)\n await batch.commit()\n } else if (!options.force) {\n // Nothing reached anybody: release the day so the next tick retries.\n await marker.delete().catch(() => undefined)\n }\n return { sent: email.sent || webhook.posted, count: alerts.length, email, webhook }\n } catch (error) {\n console.error('[operator-alerts] digest failed', error)\n return { sent: false, reason: 'unavailable', count: 0 }\n }\n}\n\n\n// ── The staff page ──────────────────────────────────────────────────────────\n\n/** One registry entry as Staff → Operator alerts lists it. */\nexport interface OperatorAlertCatalogRow {\n type: string\n label: string\n description: string\n tier: OperatorAlertDefinition['tier']\n category: OperatorAlertDefinition['category']\n pluginId: string | null\n defaults: { enabled: boolean; delivery: OperatorAlertDefinition['delivery'] }\n effective: { enabled: boolean; delivery: OperatorAlertDefinition['delivery'] }\n /** Whether staff have answered for this type, rather than the default. */\n overridden: boolean\n}\n\n/** Every registered type with its default and its effective setting. */\nexport function operatorAlertCatalogRows(\n definitions: readonly OperatorAlertDefinition[],\n settings: OperatorAlertSettingsDoc,\n): OperatorAlertCatalogRow[] {\n return definitions.map((definition) => ({\n type: definition.type,\n label: definition.label,\n description: definition.description,\n tier: definition.tier,\n category: definition.category,\n pluginId: definition.pluginId ?? null,\n defaults: { enabled: definition.defaultEnabled, delivery: definition.delivery },\n effective: effectiveOperatorAlertSetting(definition, settings),\n overridden: Boolean(settings.types?.[definition.type]),\n }))\n}\n\n/**\n * Sends one `[Test]` alert of a type straight to the operator's inbox and\n * webhook, past dedupe and staff's switches, so an operator can prove the\n * channels reach them. Writes no console notification.\n */\nexport async function sendOperatorAlertTest(\n definition: OperatorAlertDefinition,\n): Promise<{ email: SendEmailResult; webhook: OperatorAlertWebhookResult }> {\n const sample: Record<string, string> = {}\n for (const [, name] of `${definition.title} ${definition.body} ${definition.link ?? ''}`.matchAll(\n /\\{\\{\\s*([\\w.]+)\\s*\\}\\}/g,\n )) {\n sample[name as string] = `sample ${name}`\n }\n const alert = renderOperatorAlert(definition, { context: sample })\n alert.title = `[Test] ${alert.title}`\n alert.body = [\n alert.body,\n 'This is a test of the operator alert channels; nothing happened.',\n ].join(' ')\n const { sendOperatorAlertEmail } = await import('./staff-alert-email')\n const [email, webhook] = await Promise.all([\n isEmailConfigured()\n ? sendOperatorAlertEmail({\n title: alert.title,\n body: alert.body,\n url: operatorAlertAbsoluteLink(alert.link) || operatorAlertAbsoluteLink('/admin/operator-alerts'),\n context: `operator-alert-test ${definition.type}`,\n })\n : Promise.resolve<SendEmailResult>({ sent: false, reason: 'unconfigured' }),\n postOperatorAlertWebhook([alert]),\n ])\n return { email, webhook }\n}\n\n/** Where operator mail goes, named but never listed, for the staff page. */\nexport async function describeOperatorAlertRecipients(): Promise<{\n source: 'STAFF_ALERT_EMAIL' | 'NEXT_PUBLIC_OPERATOR_SUPPORT_EMAIL' | 'staff-accounts' | 'none'\n count: number\n}> {\n const { resolveStaffAlertRecipients } = await import('./staff-alert-email')\n const recipients = await resolveStaffAlertRecipients()\n if (!recipients.length) return { source: 'none', count: 0 }\n const configured = String(process.env['STAFF_ALERT_EMAIL'] ?? '').trim().toLowerCase()\n if (configured.includes('@') && recipients[0] === configured) {\n return { source: 'STAFF_ALERT_EMAIL', count: 1 }\n }\n const support = String(process.env['NEXT_PUBLIC_OPERATOR_SUPPORT_EMAIL'] ?? '').trim().toLowerCase()\n if (support.includes('@') && recipients[0] === support) {\n return { source: 'NEXT_PUBLIC_OPERATOR_SUPPORT_EMAIL', count: 1 }\n }\n return { source: 'staff-accounts', count: recipients.length }\n}\n"],"names":["createHash","createHmac","effectiveOperatorAlertSetting","OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE","OPERATOR_ALERT_TIER_LABELS","renderOperatorAlertTemplate","getOperatorAlert","registerOperatorAlerts","createResourceUid","isEmailConfigured","firebaseAdmin","OPERATOR_ALERT_SETTINGS_COLLECTION","OPERATOR_ALERT_SETTINGS_DOC","OPERATOR_ALERT_STATE_COLLECTION","OPERATOR_ALERT_DIGEST_COLLECTION","OPERATOR_ALERT_DIGEST_DEFAULT_HOUR_UTC","firestore","app","SETTINGS_TTL_MS","settingsCache","invalidateOperatorAlertSettingsCache","undefined","normalizeOperatorAlertSettings","raw","source","types","rawTypes","type","value","Object","entries","entry","setting","enabled","delivery","keys","length","hour","Number","digestHourUtc","isInteger","updatedAtMs","updatedByEmail","readOperatorAlertSettings","now","Date","at","doc","snapshot","collection","get","exists","data","error","console","firedLocally","Map","FIRED_LOCALLY_MAX","stateDocId","dedupeKey","update","digest","slice","claimOperatorAlert","definition","windowMs","Math","max","dedupeWindowMinutes","minOccurrences","floor","fire","repeats","localKey","quietUntil","reason","ref","claim","runTransaction","transaction","state","lastFiredAtMs","base","set","suppressed","merge","windowStartMs","inWindow","occurrences","fired","size","clear","WEBHOOK_TIMEOUT_MS","operatorAlertWebhookUrl","process","String","env","trim","test","operatorAlertWebhookPayload","alerts","options","shaped","origin","consoleOrigin","lines","map","alert","link","operatorAlertAbsoluteLink","tier","title","body","filter","Boolean","join","text","occurredAt","toISOString","category","url","install","postOperatorAlertWebhook","posted","JSON","stringify","headers","secret","timestamp","response","fetch","method","redirect","signal","AbortSignal","timeout","ok","status","replace","startsWith","renderLink","template","context","missing","matchAll","some","name","unregisteredDefinition","label","description","defaultEnabled","resolveOperatorAlertDefinition","known","pluginId","renderOperatorAlert","subject","notificationType","orgId","hostId","operatorEmailReachable","resolveStaffAlertRecipients","raiseOperatorAlert","typeId","outcome","settings","emailNow","notifyStaffConsole","skipEmail","queueOperatorAlertForDigest","deliverOperatorAlert","sendOperatorAlertEmail","email","webhook","Promise","all","resolve","sent","atMs","OPERATOR_DIGEST_MAX_LISTED","DIGEST_READ_LIMIT","dayKey","operatorDigestMarkerId","composeOperatorDigestBody","total","listed","rest","push","sendOperatorAlertDigest","force","getUTCHours","count","marker","orderBy","limit","queued","docs","dryRun","create","sendOperatorAlertDigestEmail","date","batch","delete","commit","catch","operatorAlertCatalogRows","definitions","defaults","effective","overridden","sendOperatorAlertTest","sample","describeOperatorAlertRecipients","recipients","configured","toLowerCase","includes","support"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,UAAU,QAAQ,cAAa;AACpD,SACEC,6BAA6B,EAC7BC,wCAAwC,EACxCC,0BAA0B,EAC1BC,2BAA2B,QAMtB,sBAAqB;AAC5B,SACEC,gBAAgB,EAChBC,sBAAsB,QACjB,8CAA6C;AACpD,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,iBAAiB,QAA8B,2BAA0B;AAClF,OAAOC,mBAAmB,sBAAkB;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GAED,0CAA0C,GAC1C,OAAO,MAAMC,qCAAqC,mBAAkB;AACpE,OAAO,MAAMC,8BAA8B,iBAAgB;AAC3D,6EAA6E,GAC7E,OAAO,MAAMC,kCAAkC,qBAAoB;AACnE,yCAAyC,GACzC,OAAO,MAAMC,mCAAmC,sBAAqB;AAErE,uEAAuE,GACvE,OAAO,MAAMC,yCAAyC,GAAE;AA6DxD,MAAMC,YAAY,IAAMN,cAAcO,GAAG,GAAGD,SAAS;AAErD,+EAA+E;AAE/E,MAAME,kBAAkB;AACxB,IAAIC;AAEJ,4EAA4E,GAC5E,OAAO,SAASC;IACdD,gBAAgBE;AAClB;AAEA,wEAAwE,GACxE,OAAO,SAASC,+BACdC,GAAY;IAEZ,MAAMC,SAAUD,OAAO,OAAOA,QAAQ,WAAWA,MAAM,CAAC;IACxD,MAAME,QAAkD,CAAC;IACzD,MAAMC,WAAWF,MAAM,CAAC,QAAQ;IAChC,IAAIE,YAAY,OAAOA,aAAa,UAAU;QAC5C,KAAK,MAAM,CAACC,MA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AAC,EAAE,KAAKC,YAAY;QAC5D,OAAO;YAAE7L,QAAQ;YAAqBsK,OAAO;QAAE;IACjD;IACA,MAAM0B,UAAUzH,QAAOD,kDAAAA,QAAQE,GAAG,CAAC,qCAAqC,YAAjDF,kDAAqD,IAAIG,IAAI,GAAGqH,WAAW;IAClG,IAAIE,QAAQD,QAAQ,CAAC,QAAQH,UAAU,CAAC,EAAE,KAAKI,SAAS;QACtD,OAAO;YAAEhM,QAAQ;YAAsCsK,OAAO;QAAE;IAClE;IACA,OAAO;QAAEtK,QAAQ;QAAkBsK,OAAOsB,WAAWhL,MAAM;IAAC;AAC9D"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/operator-alerts.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\nimport { createHash, createHmac } from 'node:crypto'\nimport {\n effectiveOperatorAlertSetting,\n OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE,\n OPERATOR_ALERT_TIER_LABELS,\n operatorAlertLevel,\n renderOperatorAlertTemplate,\n type AglynNotificationType,\n type NotificationLevel,\n type OperatorAlertContext,\n type OperatorAlertDefinition,\n type OperatorAlertSettings,\n type OperatorAlertTypeSetting,\n} from '@aglyn/aglyn/server'\nimport {\n getOperatorAlert,\n registerOperatorAlerts,\n} from '@aglyn/aglyn/plugin-manager/operator-alerts'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { isEmailConfigured, type SendEmailResult } from '@aglyn/shared-util-email'\nimport firebaseAdmin from './firebase-admin'\n\n/**\n * RAISING AN OPERATOR ALERT (AGL-3377): the one server entry point every\n * alert in the registry goes through.\n *\n * In order, for one call:\n *\n * 1. The type is looked up in the registry (core's catalog plus what plugins\n * registered). A plugin may pass its definition itself, which registers\n * it in this process if its declarations have not loaded yet.\n * 2. A `dedupeKey` is claimed against `operatorAlertState`, so a condition\n * that flaps inside the type's window is told once, and a type with\n * `minOccurrences` fires only once it has recurred that often.\n * 3. The staff console notification is written for every staff member, as\n * `notifyStaff` always has.\n * 4. Staff's switches (`platformSettings/operatorAlerts`, coded defaults\n * until changed) decide the rest: off is console only, `digest` queues it\n * for the once-a-day digest, `immediate` emails the operator now.\n * 5. The email is the `operator-alert` system email, to\n * `resolveStaffAlertRecipients()`; the optional out-of-band webhook\n * (`OPERATOR_ALERT_WEBHOOK_URL`) gets the same alert beside it, so a mail\n * provider that is itself the outage still reaches somebody.\n *\n * Never throws: an alert is raised from inside the failure it reports, and a\n * second failure there must not replace the first.\n */\n\n/** Where staff's per-type switches live. */\nexport const OPERATOR_ALERT_SETTINGS_COLLECTION = 'platformSettings'\nexport const OPERATOR_ALERT_SETTINGS_DOC = 'operatorAlerts'\n/** One document per (type, dedupeKey): when it last fired, how often since. */\nexport const OPERATOR_ALERT_STATE_COLLECTION = 'operatorAlertState'\n/** Alerts waiting for the daily digest. */\nexport const OPERATOR_ALERT_DIGEST_COLLECTION = 'operatorAlertDigest'\n\n/** The hour, UTC, the digest goes out when staff have not chosen one. */\nexport const OPERATOR_ALERT_DIGEST_DEFAULT_HOUR_UTC = 14\n\nexport interface OperatorAlertSettingsDoc extends OperatorAlertSettings {\n /** The hour of the day, UTC, the digest is sent. */\n digestHourUtc?: number\n updatedAtMs?: number\n updatedByEmail?: string | null\n}\n\nexport interface RaiseOperatorAlertOptions {\n /**\n * What makes two raises the SAME alert — a dispute id, an org and month, a\n * check id. Absent never dedupes: every raise is told.\n */\n dedupeKey?: string\n /** Values for the definition's `{{tokens}}`. Never personal data. */\n context?: OperatorAlertContext\n /** A console path or absolute URL; overrides the definition's link. */\n url?: string\n /** The title as written by the caller; overrides the rendered one. */\n subject?: string\n /** The body as written by the caller; overrides the rendered one. */\n body?: string\n /**\n * The console notification's level as the caller judged it (AGL-3437);\n * overrides the definition's. For a caller whose one alert type covers\n * news of more than one tone.\n */\n level?: NotificationLevel\n orgId?: string\n hostId?: string\n}\n\nexport type OperatorAlertOutcome =\n | 'deduped'\n | 'below-threshold'\n | 'console-only'\n | 'queued'\n | 'delivered'\n | 'undelivered'\n\nexport interface OperatorAlertResult {\n outcome: OperatorAlertOutcome\n type: string\n email?: SendEmailResult\n webhook?: OperatorAlertWebhookResult\n}\n\nexport type OperatorAlertWebhookResult =\n | { posted: true; status: number }\n | { posted: false; reason: 'unconfigured' | 'refused' | 'network'; status?: number }\n\n/** One alert, rendered, as it is delivered and queued. */\nexport interface RenderedOperatorAlert {\n type: string\n label: string\n tier: OperatorAlertDefinition['tier']\n category: OperatorAlertDefinition['category']\n title: string\n body: string\n /** Console path or absolute URL; `''` when there is none. */\n link: string\n notificationType: AglynNotificationType\n orgId?: string\n hostId?: string\n}\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n// ── Settings ────────────────────────────────────────────────────────────────\n\nconst SETTINGS_TTL_MS = 15_000\nlet settingsCache: { at: number; doc: OperatorAlertSettingsDoc } | undefined\n\n/** Drop the in-process settings cache; the console calls it after a write. */\nexport function invalidateOperatorAlertSettingsCache(): void {\n settingsCache = undefined\n}\n\n/** Clamps a stored settings document to what the pipeline understands. */\nexport function normalizeOperatorAlertSettings(\n raw: unknown,\n): OperatorAlertSettingsDoc {\n const source = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const types: Record<string, OperatorAlertTypeSetting> = {}\n const rawTypes = source['types']\n if (rawTypes && typeof rawTypes === 'object') {\n for (const [type, value] of Object.entries(rawTypes as Record<string, unknown>)) {\n if (!type || !value || typeof value !== 'object') continue\n const entry = value as Record<string, unknown>\n const setting: OperatorAlertTypeSetting = {}\n if (typeof entry['enabled'] === 'boolean') setting.enabled = entry['enabled']\n if (entry['delivery'] === 'immediate' || entry['delivery'] === 'digest') {\n setting.delivery = entry['delivery']\n }\n if (Object.keys(setting).length) types[type] = setting\n }\n }\n const hour = Number(source['digestHourUtc'])\n return {\n types,\n digestHourUtc:\n Number.isInteger(hour) && hour >= 0 && hour <= 23\n ? hour\n : OPERATOR_ALERT_DIGEST_DEFAULT_HOUR_UTC,\n ...(typeof source['updatedAtMs'] === 'number'\n ? { updatedAtMs: source['updatedAtMs'] as number }\n : {}),\n ...(typeof source['updatedByEmail'] === 'string'\n ? { updatedByEmail: source['updatedByEmail'] as string }\n : {}),\n }\n}\n\n/**\n * Staff's switches. An unreadable document is the coded defaults, uncached:\n * an alert must still go out when the settings cannot be read.\n */\nexport async function readOperatorAlertSettings(): Promise<OperatorAlertSettingsDoc> {\n const now = Date.now()\n if (settingsCache && now - settingsCache.at < SETTINGS_TTL_MS) return settingsCache.doc\n try {\n const snapshot = await firestore()\n .collection(OPERATOR_ALERT_SETTINGS_COLLECTION)\n .doc(OPERATOR_ALERT_SETTINGS_DOC)\n .get()\n const doc = normalizeOperatorAlertSettings(snapshot.exists ? snapshot.data() : null)\n settingsCache = { at: now, doc }\n return doc\n } catch (error) {\n console.error('[operator-alerts] settings unreadable; using the defaults', error)\n return normalizeOperatorAlertSettings(null)\n }\n}\n\n// ── Dedupe ──────────────────────────────────────────────────────────────────\n\n/** Keys this instance fired, and until when they stay quiet. */\nconst firedLocally = new Map<string, number>()\nconst FIRED_LOCALLY_MAX = 500\n\nfunction stateDocId(type: string, dedupeKey: string): string {\n return createHash('sha256').update(`${type}\\u0000${dedupeKey}`).digest('hex').slice(0, 40)\n}\n\nexport type OperatorAlertClaim =\n | { fire: true; repeats: number }\n | { fire: false; reason: 'deduped' | 'below-threshold' }\n\n/**\n * Whether a raise with this key fires now. One transaction on the key's\n * state document: inside the window after a fire it is counted and\n * suppressed; before it reaches `minOccurrences` it is counted and held.\n * A store that cannot be read FIRES — a duplicate beats a silence.\n */\nexport async function claimOperatorAlert(\n definition: Pick<OperatorAlertDefinition, 'type' | 'dedupeWindowMinutes' | 'minOccurrences'>,\n dedupeKey: string,\n now = Date.now(),\n): Promise<OperatorAlertClaim> {\n const windowMs = Math.max(0, definition.dedupeWindowMinutes) * 60_000\n const minOccurrences = Math.max(1, Math.floor(definition.minOccurrences ?? 1))\n if (!windowMs) return { fire: true, repeats: 0 }\n const localKey = `${definition.type}\\u0000${dedupeKey}`\n const quietUntil = firedLocally.get(localKey)\n if (quietUntil && quietUntil > now) return { fire: false, reason: 'deduped' }\n try {\n const ref = firestore()\n .collection(OPERATOR_ALERT_STATE_COLLECTION)\n .doc(stateDocId(definition.type, dedupeKey))\n const claim = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const state = (snapshot.exists ? snapshot.data() : {}) as Record<string, unknown>\n const lastFiredAtMs = Number(state['lastFiredAtMs'] ?? 0)\n const base = { type: definition.type, dedupeKey: dedupeKey.slice(0, 300), updatedAtMs: now }\n if (lastFiredAtMs && now - lastFiredAtMs < windowMs) {\n transaction.set(ref, { ...base, suppressed: Number(state['suppressed'] ?? 0) + 1 }, { merge: true })\n return { fire: false, reason: 'deduped' } as const\n }\n const windowStartMs = Number(state['windowStartMs'] ?? 0)\n const inWindow = windowStartMs && now - windowStartMs < windowMs\n const occurrences = (inWindow ? Number(state['occurrences'] ?? 0) : 0) + 1\n if (occurrences < minOccurrences) {\n transaction.set(\n ref,\n { ...base, occurrences, windowStartMs: inWindow ? windowStartMs : now },\n { merge: true },\n )\n return { fire: false, reason: 'below-threshold' } as const\n }\n transaction.set(\n ref,\n {\n ...base,\n lastFiredAtMs: now,\n occurrences: 0,\n windowStartMs: 0,\n suppressed: 0,\n fired: Number(state['fired'] ?? 0) + 1,\n },\n { merge: true },\n )\n return { fire: true, repeats: Number(state['suppressed'] ?? 0) } as const\n })\n if (claim.fire) {\n if (firedLocally.size >= FIRED_LOCALLY_MAX) firedLocally.clear()\n firedLocally.set(localKey, now + windowMs)\n }\n return claim\n } catch (error) {\n console.error(`[operator-alerts] dedupe unavailable for ${definition.type}; firing`, error)\n return { fire: true, repeats: 0 }\n }\n}\n\n// ── Out-of-band webhook ─────────────────────────────────────────────────────\n\nconst WEBHOOK_TIMEOUT_MS = 5_000\n\n/** The webhook URL, when one is configured and is http(s). */\nexport function operatorAlertWebhookUrl(): string {\n const value = String(process.env['OPERATOR_ALERT_WEBHOOK_URL'] ?? '').trim()\n return /^https?:\\/\\/\\S+$/i.test(value) ? value : ''\n}\n\n/**\n * The JSON the webhook receives. `text` is what a Slack-compatible incoming\n * webhook renders on its own; `alert` carries the fields for anything that\n * wants to route on them.\n */\nexport function operatorAlertWebhookPayload(\n alerts: readonly RenderedOperatorAlert[],\n options: { digest?: boolean; now?: number } = {},\n): Record<string, unknown> {\n const origin = consoleOrigin()\n const lines = alerts.map((alert) => {\n const link = operatorAlertAbsoluteLink(alert.link)\n return [\n `[${OPERATOR_ALERT_TIER_LABELS[alert.tier]}] ${alert.title}`,\n alert.body,\n link,\n ]\n .filter(Boolean)\n .join('\\n')\n })\n const text = options.digest\n ? [`Operator digest: ${alerts.length} alert${alerts.length === 1 ? '' : 's'}`, ...lines].join('\\n\\n')\n : lines.join('\\n\\n')\n const occurredAt = new Date(options.now ?? Date.now()).toISOString()\n const shaped = alerts.map((alert) => ({\n type: alert.type,\n tier: alert.tier,\n category: alert.category,\n title: alert.title,\n body: alert.body,\n url: operatorAlertAbsoluteLink(alert.link) || null,\n }))\n return {\n text,\n ...(options.digest ? { digest: shaped } : { alert: shaped[0] ?? null }),\n occurredAt,\n ...(origin ? { install: origin } : {}),\n }\n}\n\n/**\n * Posts alerts to `OPERATOR_ALERT_WEBHOOK_URL`, signed when\n * `OPERATOR_ALERT_WEBHOOK_SECRET` is set: `x-operator-alert-timestamp` is the\n * Unix time and `x-operator-alert-signature` is `sha256=` plus the hex HMAC\n * of `{timestamp}.{body}`. Unset means email only. Never throws.\n */\nexport async function postOperatorAlertWebhook(\n alerts: readonly RenderedOperatorAlert[],\n options: { digest?: boolean; now?: number } = {},\n): Promise<OperatorAlertWebhookResult> {\n const url = operatorAlertWebhookUrl()\n if (!url || !alerts.length) return { posted: false, reason: 'unconfigured' }\n const body = JSON.stringify(operatorAlertWebhookPayload(alerts, options))\n const headers: Record<string, string> = { 'content-type': 'application/json' }\n const secret = String(process.env['OPERATOR_ALERT_WEBHOOK_SECRET'] ?? '').trim()\n if (secret) {\n const timestamp = String(Math.floor((options.now ?? Date.now()) / 1000))\n headers['x-operator-alert-timestamp'] = timestamp\n headers['x-operator-alert-signature'] =\n 'sha256=' + createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex')\n }\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body,\n redirect: 'manual',\n signal: AbortSignal.timeout(WEBHOOK_TIMEOUT_MS),\n })\n if (response.ok) return { posted: true, status: response.status }\n console.error(`[operator-alerts] webhook answered ${response.status}`)\n return { posted: false, reason: 'refused', status: response.status }\n } catch (error) {\n console.error('[operator-alerts] webhook unreachable', error)\n return { posted: false, reason: 'network' }\n }\n}\n\n// ── Links ───────────────────────────────────────────────────────────────────\n\nfunction consoleOrigin(): string {\n return String(process.env['NEXT_PUBLIC_CONSOLE_URL'] ?? '').trim().replace(/\\/+$/, '')\n}\n\n/** A console path as an inbox or webhook can follow it, or `''`. */\nexport function operatorAlertAbsoluteLink(link: string | undefined | null): string {\n const value = String(link ?? '').trim()\n if (!value) return ''\n if (/^https?:\\/\\//i.test(value)) return value\n const origin = consoleOrigin()\n return origin && value.startsWith('/') ? `${origin}${value}` : ''\n}\n\n/**\n * The definition's link with its tokens filled, or `''` when a token it\n * needs is missing — `/admin/orgs/` would open the wrong page.\n */\nfunction renderLink(template: string | undefined, context: OperatorAlertContext | undefined): string {\n if (!template) return ''\n const missing = [...template.matchAll(/\\{\\{\\s*([\\w.]+)\\s*\\}\\}/g)].some(([, name]) => {\n const value = context?.[name as string]\n return value === null || value === undefined || value === ''\n })\n return missing ? '' : renderOperatorAlertTemplate(template, context)\n}\n\n// ── Rendering ───────────────────────────────────────────────────────────────\n\n/** Stands in for a type nobody registered, so it is still told. */\nfunction unregisteredDefinition(type: string): OperatorAlertDefinition {\n return {\n type,\n label: type,\n description: 'An alert type this install has no registry entry for.',\n tier: 'should',\n category: 'ops',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 60,\n defaultEnabled: true,\n }\n}\n\n/** Resolves the definition a call names, registering a plugin's own. */\nexport function resolveOperatorAlertDefinition(\n type: string | OperatorAlertDefinition,\n): OperatorAlertDefinition {\n if (typeof type !== 'string') {\n const known = getOperatorAlert(type.type)\n if (known) return known\n if (type.pluginId) {\n try {\n registerOperatorAlerts([type], { pluginId: type.pluginId })\n } catch (error) {\n console.error(`[operator-alerts] ${type.type} could not be registered`, error)\n }\n }\n return type\n }\n const known = getOperatorAlert(type)\n if (known) return known\n console.error(`[operator-alerts] \"${type}\" is not a registered alert type; telling it anyway`)\n return unregisteredDefinition(type)\n}\n\nexport function renderOperatorAlert(\n definition: OperatorAlertDefinition,\n options: RaiseOperatorAlertOptions = {},\n): RenderedOperatorAlert {\n const context: OperatorAlertContext = {\n ...(options.subject ? { title: options.subject } : {}),\n ...(options.body ? { body: options.body } : {}),\n ...(options.context ?? {}),\n }\n const title =\n String(options.subject ?? '').trim() ||\n renderOperatorAlertTemplate(definition.title, context) ||\n definition.label\n const body =\n String(options.body ?? '').trim() || renderOperatorAlertTemplate(definition.body, context)\n return {\n type: definition.type,\n label: definition.label,\n tier: definition.tier,\n category: definition.category,\n title,\n body,\n link: String(options.url ?? '').trim() || renderLink(definition.link, context),\n notificationType: definition.notificationType ?? OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE,\n ...(options.orgId ? { orgId: options.orgId } : {}),\n ...(options.hostId ? { hostId: options.hostId } : {}),\n }\n}\n\n// ── The entry point ─────────────────────────────────────────────────────────\n\n/** Whether an email to the operator can go at all on this install. */\nasync function operatorEmailReachable(): Promise<boolean> {\n if (!isEmailConfigured()) return false\n const { resolveStaffAlertRecipients } = await import('./staff-alert-email')\n return (await resolveStaffAlertRecipients()).length > 0\n}\n\n/** See the module comment. Never throws. */\nexport async function raiseOperatorAlert(\n type: string | OperatorAlertDefinition,\n options: RaiseOperatorAlertOptions = {},\n): Promise<OperatorAlertResult> {\n const typeId = typeof type === 'string' ? type : type.type\n try {\n const definition = resolveOperatorAlertDefinition(type)\n const dedupeKey = String(options.dedupeKey ?? '').trim()\n let repeats = 0\n if (dedupeKey) {\n const claim = await claimOperatorAlert(definition, dedupeKey)\n if (claim.fire === false) return { outcome: claim.reason, type: typeId }\n repeats = claim.repeats\n }\n const alert = renderOperatorAlert(definition, options)\n if (repeats > 0) {\n alert.body = [alert.body, `Raised ${repeats} more time${repeats === 1 ? '' : 's'} since it was last told.`]\n .filter(Boolean)\n .join(' ')\n }\n const settings = await readOperatorAlertSettings()\n const { enabled, delivery } = effectiveOperatorAlertSetting(definition, settings)\n const emailNow = enabled && delivery === 'immediate' && (await operatorEmailReachable())\n\n const { notifyStaffConsole } = await import('./notifications')\n await notifyStaffConsole(\n {\n type: alert.notificationType,\n title: alert.title,\n ...(alert.body ? { body: alert.body } : {}),\n level: options.level ?? operatorAlertLevel(definition),\n ...(alert.link && alert.link.startsWith('/') ? { link: alert.link } : {}),\n ...(alert.orgId ? { orgId: alert.orgId } : {}),\n ...(alert.hostId ? { hostId: alert.hostId } : {}),\n },\n // The operator is emailed; a staff member who also switched email on\n // for this category is not mailed the same alert a second time.\n emailNow ? { skipEmail: true } : {},\n )\n if (!enabled) return { outcome: 'console-only', type: typeId }\n if (delivery === 'digest') {\n await queueOperatorAlertForDigest(alert)\n return { outcome: 'queued', type: typeId }\n }\n return await deliverOperatorAlert(alert, { emailNow })\n } catch (error) {\n console.error(`[operator-alerts] ${typeId} could not be raised`, error)\n return { outcome: 'undelivered', type: typeId }\n }\n}\n\n/** Emails and posts one alert now. */\nasync function deliverOperatorAlert(\n alert: RenderedOperatorAlert,\n options: { emailNow: boolean },\n): Promise<OperatorAlertResult> {\n const { sendOperatorAlertEmail } = await import('./staff-alert-email')\n const [email, webhook] = await Promise.all([\n options.emailNow\n ? sendOperatorAlertEmail({\n title: alert.title,\n body: alert.body,\n url: operatorAlertAbsoluteLink(alert.link),\n context: `operator-alert ${alert.type}`,\n })\n : Promise.resolve<SendEmailResult>({ sent: false, reason: 'unconfigured' }),\n postOperatorAlertWebhook([alert]),\n ])\n return {\n outcome: email.sent || webhook.posted ? 'delivered' : 'undelivered',\n type: alert.type,\n email,\n webhook,\n }\n}\n\n// ── The digest ──────────────────────────────────────────────────────────────\n\nasync function queueOperatorAlertForDigest(alert: RenderedOperatorAlert): Promise<void> {\n try {\n await firestore()\n .collection(OPERATOR_ALERT_DIGEST_COLLECTION)\n .doc(createResourceUid())\n .set({ ...alert, atMs: Date.now() })\n } catch (error) {\n // The queue is the only record the digest will have; with it gone, the\n // alert goes now rather than never.\n console.error(`[operator-alerts] digest queue unavailable; sending ${alert.type} now`, error)\n await deliverOperatorAlert(alert, { emailNow: await operatorEmailReachable() })\n }\n}\n\n/** At most this many alerts are listed in one digest; the rest are counted. */\nexport const OPERATOR_DIGEST_MAX_LISTED = 50\nconst DIGEST_READ_LIMIT = 500\n\nexport interface OperatorDigestResult {\n /** Whether a digest went out (or, on a dry run, would). */\n sent: boolean\n reason?: 'not-due' | 'already-sent' | 'empty' | 'dry-run' | 'unavailable'\n count: number\n email?: SendEmailResult\n webhook?: OperatorAlertWebhookResult\n}\n\nfunction dayKey(now: number): string {\n return new Date(now).toISOString().slice(0, 10)\n}\n\n/** The state document that claims one UTC day's digest. */\nexport function operatorDigestMarkerId(now: number): string {\n return `digest-${dayKey(now)}`\n}\n\n/** The digest's body: one paragraph per alert, newest last. */\nexport function composeOperatorDigestBody(\n alerts: readonly RenderedOperatorAlert[],\n total = alerts.length,\n): string {\n const listed = alerts.slice(0, OPERATOR_DIGEST_MAX_LISTED).map((alert) => {\n const link = operatorAlertAbsoluteLink(alert.link)\n return [`• ${alert.title}`, alert.body, link].filter(Boolean).join('\\n')\n })\n const rest = total - listed.length\n if (rest > 0) listed.push(`…and ${rest} more in the staff console.`)\n return listed.join('\\n\\n')\n}\n\n/**\n * Sends the day's digest once the configured hour has passed: every queued\n * alert in one `operator-alert-digest` email and one webhook post, then\n * clears what it sent. Once per UTC day, claimed by creating\n * `operatorAlertState/digest-{day}`, so two ticks never both send it.\n */\nexport async function sendOperatorAlertDigest(\n options: { now?: number; dryRun?: boolean; force?: boolean } = {},\n): Promise<OperatorDigestResult> {\n const now = options.now ?? Date.now()\n try {\n const settings = await readOperatorAlertSettings()\n const hour = settings.digestHourUtc ?? OPERATOR_ALERT_DIGEST_DEFAULT_HOUR_UTC\n if (!options.force && new Date(now).getUTCHours() < hour) {\n return { sent: false, reason: 'not-due', count: 0 }\n }\n const collection = firestore().collection(OPERATOR_ALERT_DIGEST_COLLECTION)\n const marker = firestore()\n .collection(OPERATOR_ALERT_STATE_COLLECTION)\n .doc(operatorDigestMarkerId(now))\n if (!options.force && (await marker.get()).exists) {\n return { sent: false, reason: 'already-sent', count: 0 }\n }\n const snapshot = await collection.orderBy('atMs', 'asc').limit(DIGEST_READ_LIMIT).get()\n const queued = snapshot.docs\n if (!queued.length) return { sent: false, reason: 'empty', count: 0 }\n if (options.dryRun) return { sent: false, reason: 'dry-run', count: queued.length }\n if (!options.force) {\n try {\n await marker.create({ atMs: now, count: queued.length })\n } catch {\n return { sent: false, reason: 'already-sent', count: 0 }\n }\n }\n const alerts = queued.map((doc: any) => doc.data() as RenderedOperatorAlert)\n const { sendOperatorAlertDigestEmail } = await import('./staff-alert-email')\n const [email, webhook] = await Promise.all([\n sendOperatorAlertDigestEmail({\n date: dayKey(now),\n count: alerts.length,\n body: composeOperatorDigestBody(alerts),\n url: operatorAlertAbsoluteLink('/admin/operator-alerts'),\n }),\n postOperatorAlertWebhook(alerts, { digest: true, now }),\n ])\n if (email.sent || webhook.posted) {\n const batch = firestore().batch()\n for (const doc of queued) batch.delete(doc.ref)\n await batch.commit()\n } else if (!options.force) {\n // Nothing reached anybody: release the day so the next tick retries.\n await marker.delete().catch(() => undefined)\n }\n return { sent: email.sent || webhook.posted, count: alerts.length, email, webhook }\n } catch (error) {\n console.error('[operator-alerts] digest failed', error)\n return { sent: false, reason: 'unavailable', count: 0 }\n }\n}\n\n\n// ── The staff page ──────────────────────────────────────────────────────────\n\n/** One registry entry as Staff → Operator alerts lists it. */\nexport interface OperatorAlertCatalogRow {\n type: string\n label: string\n description: string\n tier: OperatorAlertDefinition['tier']\n category: OperatorAlertDefinition['category']\n pluginId: string | null\n defaults: { enabled: boolean; delivery: OperatorAlertDefinition['delivery'] }\n effective: { enabled: boolean; delivery: OperatorAlertDefinition['delivery'] }\n /** Whether staff have answered for this type, rather than the default. */\n overridden: boolean\n}\n\n/** Every registered type with its default and its effective setting. */\nexport function operatorAlertCatalogRows(\n definitions: readonly OperatorAlertDefinition[],\n settings: OperatorAlertSettingsDoc,\n): OperatorAlertCatalogRow[] {\n return definitions.map((definition) => ({\n type: definition.type,\n label: definition.label,\n description: definition.description,\n tier: definition.tier,\n category: definition.category,\n pluginId: definition.pluginId ?? null,\n defaults: { enabled: definition.defaultEnabled, delivery: definition.delivery },\n effective: effectiveOperatorAlertSetting(definition, settings),\n overridden: Boolean(settings.types?.[definition.type]),\n }))\n}\n\n/**\n * Sends one `[Test]` alert of a type straight to the operator's inbox and\n * webhook, past dedupe and staff's switches, so an operator can prove the\n * channels reach them. Writes no console notification.\n */\nexport async function sendOperatorAlertTest(\n definition: OperatorAlertDefinition,\n): Promise<{ email: SendEmailResult; webhook: OperatorAlertWebhookResult }> {\n const sample: Record<string, string> = {}\n for (const [, name] of `${definition.title} ${definition.body} ${definition.link ?? ''}`.matchAll(\n /\\{\\{\\s*([\\w.]+)\\s*\\}\\}/g,\n )) {\n sample[name as string] = `sample ${name}`\n }\n const alert = renderOperatorAlert(definition, { context: sample })\n alert.title = `[Test] ${alert.title}`\n alert.body = [\n alert.body,\n 'This is a test of the operator alert channels; nothing happened.',\n ].join(' ')\n const { sendOperatorAlertEmail } = await import('./staff-alert-email')\n const [email, webhook] = await Promise.all([\n isEmailConfigured()\n ? sendOperatorAlertEmail({\n title: alert.title,\n body: alert.body,\n url: operatorAlertAbsoluteLink(alert.link) || operatorAlertAbsoluteLink('/admin/operator-alerts'),\n context: `operator-alert-test ${definition.type}`,\n })\n : Promise.resolve<SendEmailResult>({ sent: false, reason: 'unconfigured' }),\n postOperatorAlertWebhook([alert]),\n ])\n return { email, webhook }\n}\n\n/** Where operator mail goes, named but never listed, for the staff page. */\nexport async function describeOperatorAlertRecipients(): Promise<{\n source: 'STAFF_ALERT_EMAIL' | 'NEXT_PUBLIC_OPERATOR_SUPPORT_EMAIL' | 'staff-accounts' | 'none'\n count: number\n}> {\n const { resolveStaffAlertRecipients } = await import('./staff-alert-email')\n const recipients = await resolveStaffAlertRecipients()\n if (!recipients.length) return { source: 'none', count: 0 }\n const configured = String(process.env['STAFF_ALERT_EMAIL'] ?? '').trim().toLowerCase()\n if (configured.includes('@') && recipients[0] === configured) {\n return { source: 'STAFF_ALERT_EMAIL', count: 1 }\n }\n const support = String(process.env['NEXT_PUBLIC_OPERATOR_SUPPORT_EMAIL'] ?? '').trim().toLowerCase()\n if (support.includes('@') && recipients[0] === support) {\n return { source: 'NEXT_PUBLIC_OPERATOR_SUPPORT_EMAIL', count: 1 }\n }\n return { source: 'staff-accounts', count: recipients.length }\n}\n"],"names":["createHash","createHmac","effectiveOperatorAlertSetting","OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE","OPERATOR_ALERT_TIER_LABELS","operatorAlertLevel","renderOperatorAlertTemplate","getOperatorAlert","registerOperatorAlerts","createResourceUid","isEmailConfigured","firebaseAdmin","OPERATOR_ALERT_SETTINGS_COLLECTION","OPERATOR_ALERT_SETTINGS_DOC","OPERATOR_ALERT_STATE_COLLECTION","OPERATOR_ALERT_DIGEST_COLLECTION","OPERATOR_ALERT_DIGEST_DEFAULT_HOUR_UTC","firestore","app","SETTINGS_TTL_MS","settingsCache","invalidateOperatorAlertSettingsCache","undefined","normalizeOperatorAlertSettings","raw","source","types","rawTypes","type","value","Object","entries","entry","setting","enabled","delivery","keys","length","hour","Number","digestHourUtc","isInteger","updatedAtMs","updatedByEmail","readOperatorAlertSettings","now","Date","at","doc","snapshot","collection","get","exists","data","error","console","firedLocally","Map","FIRED_LOCALLY_MAX","stateDocId","dedupeKey","update","digest","slice","claimOperatorAlert","definition","windowMs","Math","max","dedupeWindowMinutes","minOccurrences","floor","fire","repeats","localKey","quietUntil","reason","ref","claim","runTransaction","transaction","state","lastFiredAtMs","base","set","suppressed","merge","windowStartMs","inWindow","occurrences","fired","size","clear","WEBHOOK_TIMEOUT_MS","operatorAlertWebhookUrl","process","String","env","trim","test","operatorAlertWebhookPayload","alerts","options","shaped","origin","consoleOrigin","lines","map","alert","link","operatorAlertAbsoluteLink","tier","title","body","filter","Boolean","join","text","occurredAt","toISOString","category","url","install","postOperatorAlertWebhook","posted","JSON","stringify","headers","secret","timestamp","response","fetch","method","redirect","signal","AbortSignal","timeout","ok","status","replace","startsWith","renderLink","template","context","missing","matchAll","some","name","unregisteredDefinition","label","description","defaultEnabled","resolveOperatorAlertDefinition","known","pluginId","renderOperatorAlert","subject","notificationType","orgId","hostId","operatorEmailReachable","resolveStaffAlertRecipients","raiseOperatorAlert","typeId","outcome","settings","emailNow","notifyStaffConsole","level","skipEmail","queueOperatorAlertForDigest","deliverOperatorAlert","sendOperatorAlertEmail","email","webhook","Promise","all","resolve","sent","atMs","OPERATOR_DIGEST_MAX_LISTED","DIGEST_READ_LIMIT","dayKey","operatorDigestMarkerId","composeOperatorDigestBody","total","listed","rest","push","sendOperatorAlertDigest","force","getUTCHours","count","marker","orderBy","limit","queued","docs","dryRun","create","sendOperatorAlertDigestEmail","date","batch","delete","commit","catch","operatorAlertCatalogRows","definitions","defaults","effective","overridden","sendOperatorAlertTest","sample","describeOperatorAlertRecipients","recipients","configured","toLowerCase","includes","support"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,UAAU,QAAQ,cAAa;AACpD,SACEC,6BAA6B,EAC7BC,wCAAwC,EACxCC,0BAA0B,EAC1BC,kBAAkB,EAClBC,2BAA2B,QAOtB,sBAAqB;AAC5B,SACEC,gBAAgB,EAChBC,sBAAsB,QACjB,8CAA6C;AACpD,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,iBAAiB,QAA8B,2BAA0B;AAClF,OAAOC,mBAAmB,sBAAkB;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GAED,0CAA0C,GAC1C,OAAO,MAAMC,qCAAqC,mBAAkB;AACpE,OAAO,MAAMC,8BAA8B,iBAAgB;AAC3D,6EAA6E,GAC7E,OAAO,MAAMC,kCAAkC,qBAAoB;AACnE,yCAAyC,GACzC,OAAO,MAAMC,mCAAmC,sBAAqB;AAErE,uEAAuE,GACvE,OAAO,MAAMC,yCAAyC,GAAE;AAmExD,MAAMC,YAAY,IAAMN,cAAcO,GAAG,GAAGD,SAAS;AAErD,+EAA+E;AAE/E,MAAME,kBAAkB;AACxB,IAAIC;AAEJ,4EAA4E,GAC5E,OAAO,SAASC;IACdD,gBAAgBE;AAClB;AAEA,wEAAwE,GACxE,OAAO,SAASC,+BACdC,GAAY;IAEZ,MAAMC,SAAUD,OAAO,OAAOA,QAAQ,WAAWA,MAAM,CAAC;IACxD,MAAME,QAAkD,CAAC;IACzD,MAAMC,WAAWF,MAAM,CAAC,QAAQ;IAChC,IAAIE,YAAY,OAAOA,aAAa,UAAU;QAC5C,KAAK,MAAM,CAACC,MAAMC,MAAM,IAAIC,OAAOC,OAAO,CAACJ,UAAsC;YAC/E,IAAI,CAACC,QAAQ,CAACC,SAAS,OAAOA,UAAU,UAAU;YAClD,MAAMG,QAAQH;YACd,MAAMI,UAAoC,CAAC;YAC3C,I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QAAE;IACjD;IACA,MAAM0B,UAAU1H,QAAOD,kDAAAA,QAAQE,GAAG,CAAC,qCAAqC,YAAjDF,kDAAqD,IAAIG,IAAI,GAAGsH,WAAW;IAClG,IAAIE,QAAQD,QAAQ,CAAC,QAAQH,UAAU,CAAC,EAAE,KAAKI,SAAS;QACtD,OAAO;YAAEjM,QAAQ;YAAsCuK,OAAO;QAAE;IAClE;IACA,OAAO;QAAEvK,QAAQ;QAAkBuK,OAAOsB,WAAWjL,MAAM;IAAC;AAC9D"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * AN ORGANIZATION'S CONTAINERS OF ONE KIND, read on the server by a plugin
19
+ * that files its records under them and does not keep them.
20
+ *
21
+ * A container kind is declared by the plugin that keeps it
22
+ * (`plugin-manager/plugin-containers.ts`): which org collection holds the
23
+ * containers and which field names one. That declaration is the whole of what
24
+ * another plugin may rely on — a container's id, its name, the sites its
25
+ * `visibleTo` places it on, and whether its owner retired it (`deletedAt`) —
26
+ * and this module reads exactly that, where the declaration says. A sequence
27
+ * that validates the campaigns it is filed under, an import that matches
28
+ * campaign names, a timeline entry that names the campaign a lead was filed
29
+ * under: none of them names the owner's collection, so the owner may move it.
30
+ *
31
+ * A kind no plugin keeps reads nothing: every id answers as gone, and a list
32
+ * is empty. That is the honest answer for a workspace without the owner.
33
+ */
34
+ /** One container, as much of it as a plugin that files under it may read. */
35
+ export interface OrgContainerRecord {
36
+ id: string;
37
+ /** The org holds a container under this id, retired or not. */
38
+ exists: boolean;
39
+ /** It exists and its owner has not retired it. */
40
+ live: boolean;
41
+ /** Its name, from the field its kind declares; `''` when it has none or is gone. */
42
+ name: string;
43
+ /** Its `visibleTo` scope tokens; `[]` when it has none or is gone. */
44
+ visibleTo: string[];
45
+ }
46
+ /**
47
+ * The containers named by `ids`, one record per id in the order asked: one
48
+ * keyed read each, in a single `getAll`. An id that cannot be a document id
49
+ * is answered as gone without a read.
50
+ *
51
+ * Throws what the read throws; a caller that must not fail on it catches.
52
+ */
53
+ export declare function readOrgContainers(firestore: FirebaseFirestore.Firestore, kind: string, orgId: string, ids: readonly string[]): Promise<OrgContainerRecord[]>;
54
+ /**
55
+ * Up to `ceiling` of the organization's containers of a kind, in document
56
+ * order, retired ones included and marked: a caller that matches by name
57
+ * decides what a retired one means to it. Read as a projection of the
58
+ * fields a record carries.
59
+ */
60
+ export declare function listOrgContainers(firestore: FirebaseFirestore.Firestore, kind: string, orgId: string, ceiling: number): Promise<OrgContainerRecord[]>;
61
+ /**
62
+ * Up to `limit` of the organization's containers of a kind whose declared
63
+ * name field is exactly `name`, retired ones included and marked, so a caller
64
+ * resolving a name can tell a live match from a retired one sharing it.
65
+ */
66
+ export declare function findOrgContainersByName(firestore: FirebaseFirestore.Firestore, kind: string, orgId: string, name: string, limit: number): Promise<OrgContainerRecord[]>;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { pluginContainerKind } from "@aglyn/aglyn/plugin-manager/plugin-containers";
17
+ import { isDocumentId } from "./document-id.js";
18
+ function recordOf(id, snapshot, nameField) {
19
+ var _snapshot_get;
20
+ if (!(snapshot == null ? void 0 : snapshot.exists)) return {
21
+ id,
22
+ exists: false,
23
+ live: false,
24
+ name: '',
25
+ visibleTo: []
26
+ };
27
+ const visibleTo = snapshot.get('visibleTo');
28
+ return {
29
+ id,
30
+ exists: true,
31
+ live: !snapshot.get('deletedAt'),
32
+ name: String((_snapshot_get = snapshot.get(nameField)) != null ? _snapshot_get : '').trim(),
33
+ visibleTo: Array.isArray(visibleTo) ? visibleTo.map(String) : []
34
+ };
35
+ }
36
+ /**
37
+ * The fields a reader may rely on, and the only ones a listing reads: a
38
+ * container can be a large document, and nothing here needs the rest.
39
+ */ const fieldsOf = (nameField)=>[
40
+ nameField,
41
+ 'deletedAt',
42
+ 'visibleTo'
43
+ ];
44
+ /** The kind's collection under the org, or `null` when no plugin keeps the kind. */ function containersOf(firestore, kind, orgId) {
45
+ const declared = pluginContainerKind(kind);
46
+ if (!declared || !isDocumentId(orgId)) return null;
47
+ return {
48
+ ref: firestore.collection('orgs').doc(orgId).collection(declared.orgCollection),
49
+ nameField: declared.nameField
50
+ };
51
+ }
52
+ /**
53
+ * The containers named by `ids`, one record per id in the order asked: one
54
+ * keyed read each, in a single `getAll`. An id that cannot be a document id
55
+ * is answered as gone without a read.
56
+ *
57
+ * Throws what the read throws; a caller that must not fail on it catches.
58
+ */ export async function readOrgContainers(firestore, kind, orgId, ids) {
59
+ if (!ids.length) return [];
60
+ const containers = containersOf(firestore, kind, orgId);
61
+ const readable = ids.filter((id)=>isDocumentId(id));
62
+ if (!containers || !readable.length) return ids.map((id)=>recordOf(id, undefined, ''));
63
+ // `getAll` answers in the order asked, so each snapshot is matched to its
64
+ // id by position rather than by a field of the snapshot.
65
+ const found = await firestore.getAll(...readable.map((id)=>containers.ref.doc(id)));
66
+ const byId = new Map(readable.map((id, index)=>[
67
+ id,
68
+ found[index]
69
+ ]));
70
+ return ids.map((id)=>recordOf(id, byId.get(id), containers.nameField));
71
+ }
72
+ /**
73
+ * Up to `ceiling` of the organization's containers of a kind, in document
74
+ * order, retired ones included and marked: a caller that matches by name
75
+ * decides what a retired one means to it. Read as a projection of the
76
+ * fields a record carries.
77
+ */ export async function listOrgContainers(firestore, kind, orgId, ceiling) {
78
+ const containers = containersOf(firestore, kind, orgId);
79
+ if (!containers || ceiling <= 0) return [];
80
+ const snapshot = await containers.ref.select(...fieldsOf(containers.nameField)).limit(ceiling).get();
81
+ return snapshot.docs.map((doc)=>recordOf(doc.id, doc, containers.nameField));
82
+ }
83
+ /**
84
+ * Up to `limit` of the organization's containers of a kind whose declared
85
+ * name field is exactly `name`, retired ones included and marked, so a caller
86
+ * resolving a name can tell a live match from a retired one sharing it.
87
+ */ export async function findOrgContainersByName(firestore, kind, orgId, name, limit) {
88
+ const containers = containersOf(firestore, kind, orgId);
89
+ const wanted = name.trim();
90
+ if (!containers || !wanted || limit <= 0) return [];
91
+ const snapshot = await containers.ref.where(containers.nameField, '==', wanted).select(...fieldsOf(containers.nameField)).limit(limit).get();
92
+ return snapshot.docs.map((doc)=>recordOf(doc.id, doc, containers.nameField));
93
+ }
94
+
95
+ //# sourceMappingURL=org-containers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/org-containers.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\nimport { pluginContainerKind } from '@aglyn/aglyn/plugin-manager/plugin-containers'\nimport { isDocumentId } from './document-id'\n\n/**\n * AN ORGANIZATION'S CONTAINERS OF ONE KIND, read on the server by a plugin\n * that files its records under them and does not keep them.\n *\n * A container kind is declared by the plugin that keeps it\n * (`plugin-manager/plugin-containers.ts`): which org collection holds the\n * containers and which field names one. That declaration is the whole of what\n * another plugin may rely on — a container's id, its name, the sites its\n * `visibleTo` places it on, and whether its owner retired it (`deletedAt`) —\n * and this module reads exactly that, where the declaration says. A sequence\n * that validates the campaigns it is filed under, an import that matches\n * campaign names, a timeline entry that names the campaign a lead was filed\n * under: none of them names the owner's collection, so the owner may move it.\n *\n * A kind no plugin keeps reads nothing: every id answers as gone, and a list\n * is empty. That is the honest answer for a workspace without the owner.\n */\n\n/** One container, as much of it as a plugin that files under it may read. */\nexport interface OrgContainerRecord {\n id: string\n /** The org holds a container under this id, retired or not. */\n exists: boolean\n /** It exists and its owner has not retired it. */\n live: boolean\n /** Its name, from the field its kind declares; `''` when it has none or is gone. */\n name: string\n /** Its `visibleTo` scope tokens; `[]` when it has none or is gone. */\n visibleTo: string[]\n}\n\ntype Snapshot = Pick<FirebaseFirestore.DocumentSnapshot, 'exists' | 'get'>\n\nfunction recordOf(id: string, snapshot: Snapshot | undefined, nameField: string): OrgContainerRecord {\n if (!snapshot?.exists) return { id, exists: false, live: false, name: '', visibleTo: [] }\n const visibleTo = snapshot.get('visibleTo')\n return {\n id,\n exists: true,\n live: !snapshot.get('deletedAt'),\n name: String(snapshot.get(nameField) ?? '').trim(),\n visibleTo: Array.isArray(visibleTo) ? visibleTo.map(String) : [],\n }\n}\n\n/**\n * The fields a reader may rely on, and the only ones a listing reads: a\n * container can be a large document, and nothing here needs the rest.\n */\nconst fieldsOf = (nameField: string) => [nameField, 'deletedAt', 'visibleTo']\n\n/** The kind's collection under the org, or `null` when no plugin keeps the kind. */\nfunction containersOf(\n firestore: FirebaseFirestore.Firestore,\n kind: string,\n orgId: string,\n): { ref: FirebaseFirestore.CollectionReference; nameField: string } | null {\n const declared = pluginContainerKind(kind)\n if (!declared || !isDocumentId(orgId)) return null\n return {\n ref: firestore.collection('orgs').doc(orgId).collection(declared.orgCollection),\n nameField: declared.nameField,\n }\n}\n\n/**\n * The containers named by `ids`, one record per id in the order asked: one\n * keyed read each, in a single `getAll`. An id that cannot be a document id\n * is answered as gone without a read.\n *\n * Throws what the read throws; a caller that must not fail on it catches.\n */\nexport async function readOrgContainers(\n firestore: FirebaseFirestore.Firestore,\n kind: string,\n orgId: string,\n ids: readonly string[],\n): Promise<OrgContainerRecord[]> {\n if (!ids.length) return []\n const containers = containersOf(firestore, kind, orgId)\n const readable = ids.filter((id) => isDocumentId(id))\n if (!containers || !readable.length) return ids.map((id) => recordOf(id, undefined, ''))\n // `getAll` answers in the order asked, so each snapshot is matched to its\n // id by position rather than by a field of the snapshot.\n const found = await firestore.getAll(...readable.map((id) => containers.ref.doc(id)))\n const byId = new Map(readable.map((id, index) => [id, found[index]]))\n return ids.map((id) => recordOf(id, byId.get(id), containers.nameField))\n}\n\n/**\n * Up to `ceiling` of the organization's containers of a kind, in document\n * order, retired ones included and marked: a caller that matches by name\n * decides what a retired one means to it. Read as a projection of the\n * fields a record carries.\n */\nexport async function listOrgContainers(\n firestore: FirebaseFirestore.Firestore,\n kind: string,\n orgId: string,\n ceiling: number,\n): Promise<OrgContainerRecord[]> {\n const containers = containersOf(firestore, kind, orgId)\n if (!containers || ceiling <= 0) return []\n const snapshot = await containers.ref\n .select(...fieldsOf(containers.nameField))\n .limit(ceiling)\n .get()\n return snapshot.docs.map((doc) => recordOf(doc.id, doc, containers.nameField))\n}\n\n/**\n * Up to `limit` of the organization's containers of a kind whose declared\n * name field is exactly `name`, retired ones included and marked, so a caller\n * resolving a name can tell a live match from a retired one sharing it.\n */\nexport async function findOrgContainersByName(\n firestore: FirebaseFirestore.Firestore,\n kind: string,\n orgId: string,\n name: string,\n limit: number,\n): Promise<OrgContainerRecord[]> {\n const containers = containersOf(firestore, kind, orgId)\n const wanted = name.trim()\n if (!containers || !wanted || limit <= 0) return []\n const snapshot = await containers.ref\n .where(containers.nameField, '==', wanted)\n .select(...fieldsOf(containers.nameField))\n .limit(limit)\n .get()\n return snapshot.docs.map((doc) => recordOf(doc.id, doc, containers.nameField))\n}\n"],"names":["pluginContainerKind","isDocumentId","recordOf","id","snapshot","nameField","exists","live","name","visibleTo","get","String","trim","Array","isArray","map","fieldsOf","containersOf","firestore","kind","orgId","declared","ref","collection","doc","orgCollection","readOrgContainers","ids","length","containers","readable","filter","undefined","found","getAll","byId","Map","index","listOrgContainers","ceiling","select","limit","docs","findOrgContainersByName","wanted","where"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,YAAY,QAAQ,mBAAe;AAmC5C,SAASC,SAASC,EAAU,EAAEC,QAA8B,EAAEC,SAAiB;QAO9DD;IANf,IAAI,EAACA,4BAAAA,SAAUE,MAAM,GAAE,OAAO;QAAEH;QAAIG,QAAQ;QAAOC,MAAM;QAAOC,MAAM;QAAIC,WAAW,EAAE;IAAC;IACxF,MAAMA,YAAYL,SAASM,GAAG,CAAC;IAC/B,OAAO;QACLP;QACAG,QAAQ;QACRC,MAAM,CAACH,SAASM,GAAG,CAAC;QACpBF,MAAMG,QAAOP,gBAAAA,SAASM,GAAG,CAACL,sBAAbD,gBAA2B,IAAIQ,IAAI;QAChDH,WAAWI,MAAMC,OAAO,CAACL,aAAaA,UAAUM,GAAG,CAACJ,UAAU,EAAE;IAClE;AACF;AAEA;;;CAGC,GACD,MAAMK,WAAW,CAACX,YAAsB;QAACA;QAAW;QAAa;KAAY;AAE7E,kFAAkF,GAClF,SAASY,aACPC,SAAsC,EACtCC,IAAY,EACZC,KAAa;IAEb,MAAMC,WAAWrB,oBAAoBmB;IACrC,IAAI,CAACE,YAAY,CAACpB,aAAamB,QAAQ,OAAO;IAC9C,OAAO;QACLE,KAAKJ,UAAUK,UAAU,CAAC,QAAQC,GAAG,CAACJ,OAAOG,UAAU,CAACF,SA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AO,eAAesC,wBACpBzB,SAAsC,EACtCC,IAAY,EACZC,KAAa,EACbZ,IAAY,EACZiC,KAAa;IAEb,MAAMZ,aAAaZ,aAAaC,WAAWC,MAAMC;IACjD,MAAMwB,SAASpC,KAAKI,IAAI;IACxB,IAAI,CAACiB,cAAc,CAACe,UAAUH,SAAS,GAAG,OAAO,EAAE;IACnD,MAAMrC,WAAW,MAAMyB,WAAWP,GAAG,CAClCuB,KAAK,CAAChB,WAAWxB,SAAS,EAAE,MAAMuC,QAClCJ,MAAM,IAAIxB,SAASa,WAAWxB,SAAS,GACvCoC,KAAK,CAACA,OACN/B,GAAG;IACN,OAAON,SAASsC,IAAI,CAAC3B,GAAG,CAAC,CAACS,MAAQtB,SAASsB,IAAIrB,EAAE,EAAEqB,KAAKK,WAAWxB,SAAS;AAC9E"}
@@ -73,9 +73,10 @@ const MAX_SENDS = 25;
73
73
  'notice.subject': input.subject,
74
74
  'notice.body': input.text,
75
75
  'org.name': (_brand_orgName = brand.orgName) != null ? _brand_orgName : ''
76
- }, brand, {
76
+ }, brand, // The last resort reads as the built-in copy does: subject, then body.
77
+ {
77
78
  subject: input.subject,
78
- text: input.text
79
+ text: `${input.subject}\n\n${input.text}`
79
80
  });
80
81
  let sent = 0;
81
82
  for (const to of recipients.slice(0, MAX_SENDS)){
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/org-member-notice.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\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { withoutMailWithheldAccounts } from './account-mail'\nimport { findUserByUidAcrossPools } from './auth-pools'\nimport { filterSuppressedEmails } from './email-suppression'\nimport { listOrgMembers } from './organizations'\nimport { orgSystemEmailBrand, renderSystemEmailContent } from './render-system-email'\n\n/**\n * A NOTICE TO NAMED MEMBERS OF AN ORGANIZATION, BY EMAIL (AGL-3244).\n *\n * The console notification (`notifications.ts`) is the record, and its email\n * channel is a preference that defaults off. Some things cannot wait on a\n * preference: a sequence mailbox that paused itself holds every enrollment\n * on it until its owner acts, and the owner is not watching the page. This\n * sends the email regardless, to the members named and — when asked — to\n * the organization's owners and admins beside them, one send per address\n * so nobody is shown anyone else's.\n *\n * Addresses come from the roster (`orgs/{orgId}/members/{uid}.email`), and\n * for a member whose row carries none, from the directory. Suppressed\n * addresses are skipped, the send is metered to the organization, and\n * nothing here throws: the notice is a courtesy beside a state the caller\n * already wrote.\n */\n\nexport interface OrgMemberNoticeInput {\n orgId: string\n /** The members to write to, by uid. */\n uids: readonly string[]\n /** Also the organization's owners and admins. */\n includeAdmins?: boolean\n subject: string\n text: string\n /** Resend tag / log label. */\n context: string\n}\n\nexport interface OrgMemberNoticeResult {\n /** Addresses the notice went to. */\n sent: number\n /** Why nothing could be sent at all, when nothing could. */\n reason?: 'unconfigured' | 'no-recipients' | 'failed'\n}\n\n/** At most this many directory lookups, and this many sends, per notice. */\nconst MAX_LOOKUPS = 10\nconst MAX_SENDS = 25\n\n/** Sends one notice to each member — see the module note. */\nexport async function sendOrgMemberNotice(input: OrgMemberNoticeInput): Promise<OrgMemberNoticeResult> {\n if (!isEmailConfigured()) return { sent: 0, reason: 'unconfigured' }\n try {\n const members = await listOrgMembers(input.orgId)\n const rosterEmail = new Map<string, string>()\n for (const member of members) {\n const address = String(member.email ?? '')\n .trim()\n .toLowerCase()\n if (address.includes('@')) rosterEmail.set(member.$id, address)\n }\n const uids = new Set(input.uids.filter(Boolean))\n if (input.includeAdmins) {\n for (const member of members) {\n if (member.role === 'owner' || member.role === 'admin') uids.add(member.$id)\n }\n }\n const addresses = new Set<string>()\n let lookups = 0\n // A locked or disabled account is not mailed (AGL-3418).\n for (const uid of await withoutMailWithheldAccounts([...uids])) {\n let address = rosterEmail.get(uid) ?? ''\n if (!address && lookups < MAX_LOOKUPS) {\n lookups += 1\n const pooled = await findUserByUidAcrossPools(uid).catch(() => null)\n address = String(pooled?.record?.email ?? '')\n .trim()\n .toLowerCase()\n }\n if (address.includes('@')) addresses.add(address)\n }\n const recipients = await filterSuppressedEmails([...addresses])\n if (!recipients.length) return { sent: 0, reason: 'no-recipients' }\n // One message for everyone, in the organization's brand, as the\n // `workspace-notice` system email (AGL-3367).\n const brand = await orgSystemEmailBrand(input.orgId)\n const content = await renderSystemEmailContent(\n 'workspace-notice',\n {\n 'notice.subject': input.subject,\n 'notice.body': input.text,\n 'org.name': brand.orgName ?? '',\n },\n brand,\n { subject: input.subject, text: input.text },\n )\n let sent = 0\n for (const to of recipients.slice(0, MAX_SENDS)) {\n const result = await sendEmail({\n to,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: input.context,\n })\n if (!result.sent) continue\n sent += 1\n const { meterOrgEmail } = await import('./email-metering')\n await meterOrgEmail(input.orgId).catch(() => undefined)\n }\n return sent ? { sent } : { sent: 0, reason: 'failed' }\n } catch (error) {\n console.error('[org-member-notice] send failed', error)\n return { sent: 0, reason: 'failed' }\n }\n}\n"],"names":["isEmailConfigured","sendEmail","withoutMailWithheldAccounts","findUserByUidAcrossPools","filterSuppressedEmails","listOrgMembers","orgSystemEmailBrand","renderSystemEmailContent","MAX_LOOKUPS","MAX_SENDS","sendOrgMemberNotice","input","sent","reason","brand","members","orgId","rosterEmail","Map","member","address","String","email","trim","toLowerCase","includes","set","$id","uids","Set","filter","Boolean","includeAdmins","role","add","addresses","lookups","uid","get","pooled","catch","record","recipients","length","content","subject","text","orgName","to","slice","result","fromName","context","meterOrgEmail","undefined","error","console"],"mappings":";AAAA;;;;;;;;;;;;;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;QAAS;IACvD,EAAE,OAAO0C,OAAO;QACdC,QAAQD,KAAK,CAAC,mCAAmCA;QACjD,OAAO;YAAE3C,MAAM;YAAGC,QAAQ;QAAS;IACrC;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/org-member-notice.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\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { withoutMailWithheldAccounts } from './account-mail'\nimport { findUserByUidAcrossPools } from './auth-pools'\nimport { filterSuppressedEmails } from './email-suppression'\nimport { listOrgMembers } from './organizations'\nimport { orgSystemEmailBrand, renderSystemEmailContent } from './render-system-email'\n\n/**\n * A NOTICE TO NAMED MEMBERS OF AN ORGANIZATION, BY EMAIL (AGL-3244).\n *\n * The console notification (`notifications.ts`) is the record, and its email\n * channel is a preference that defaults off. Some things cannot wait on a\n * preference: a sequence mailbox that paused itself holds every enrollment\n * on it until its owner acts, and the owner is not watching the page. This\n * sends the email regardless, to the members named and — when asked — to\n * the organization's owners and admins beside them, one send per address\n * so nobody is shown anyone else's.\n *\n * Addresses come from the roster (`orgs/{orgId}/members/{uid}.email`), and\n * for a member whose row carries none, from the directory. Suppressed\n * addresses are skipped, the send is metered to the organization, and\n * nothing here throws: the notice is a courtesy beside a state the caller\n * already wrote.\n */\n\nexport interface OrgMemberNoticeInput {\n orgId: string\n /** The members to write to, by uid. */\n uids: readonly string[]\n /** Also the organization's owners and admins. */\n includeAdmins?: boolean\n subject: string\n text: string\n /** Resend tag / log label. */\n context: string\n}\n\nexport interface OrgMemberNoticeResult {\n /** Addresses the notice went to. */\n sent: number\n /** Why nothing could be sent at all, when nothing could. */\n reason?: 'unconfigured' | 'no-recipients' | 'failed'\n}\n\n/** At most this many directory lookups, and this many sends, per notice. */\nconst MAX_LOOKUPS = 10\nconst MAX_SENDS = 25\n\n/** Sends one notice to each member — see the module note. */\nexport async function sendOrgMemberNotice(input: OrgMemberNoticeInput): Promise<OrgMemberNoticeResult> {\n if (!isEmailConfigured()) return { sent: 0, reason: 'unconfigured' }\n try {\n const members = await listOrgMembers(input.orgId)\n const rosterEmail = new Map<string, string>()\n for (const member of members) {\n const address = String(member.email ?? '')\n .trim()\n .toLowerCase()\n if (address.includes('@')) rosterEmail.set(member.$id, address)\n }\n const uids = new Set(input.uids.filter(Boolean))\n if (input.includeAdmins) {\n for (const member of members) {\n if (member.role === 'owner' || member.role === 'admin') uids.add(member.$id)\n }\n }\n const addresses = new Set<string>()\n let lookups = 0\n // A locked or disabled account is not mailed (AGL-3418).\n for (const uid of await withoutMailWithheldAccounts([...uids])) {\n let address = rosterEmail.get(uid) ?? ''\n if (!address && lookups < MAX_LOOKUPS) {\n lookups += 1\n const pooled = await findUserByUidAcrossPools(uid).catch(() => null)\n address = String(pooled?.record?.email ?? '')\n .trim()\n .toLowerCase()\n }\n if (address.includes('@')) addresses.add(address)\n }\n const recipients = await filterSuppressedEmails([...addresses])\n if (!recipients.length) return { sent: 0, reason: 'no-recipients' }\n // One message for everyone, in the organization's brand, as the\n // `workspace-notice` system email (AGL-3367).\n const brand = await orgSystemEmailBrand(input.orgId)\n const content = await renderSystemEmailContent(\n 'workspace-notice',\n {\n 'notice.subject': input.subject,\n 'notice.body': input.text,\n 'org.name': brand.orgName ?? '',\n },\n brand,\n // The last resort reads as the built-in copy does: subject, then body.\n { subject: input.subject, text: `${input.subject}\\n\\n${input.text}` },\n )\n let sent = 0\n for (const to of recipients.slice(0, MAX_SENDS)) {\n const result = await sendEmail({\n to,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: input.context,\n })\n if (!result.sent) continue\n sent += 1\n const { meterOrgEmail } = await import('./email-metering')\n await meterOrgEmail(input.orgId).catch(() => undefined)\n }\n return sent ? { sent } : { sent: 0, reason: 'failed' }\n } catch (error) {\n console.error('[org-member-notice] send failed', error)\n return { sent: 0, reason: 'failed' }\n }\n}\n"],"names":["isEmailConfigured","sendEmail","withoutMailWithheldAccounts","findUserByUidAcrossPools","filterSuppressedEmails","listOrgMembers","orgSystemEmailBrand","renderSystemEmailContent","MAX_LOOKUPS","MAX_SENDS","sendOrgMemberNotice","input","sent","reason","brand","members","orgId","rosterEmail","Map","member","address","String","email","trim","toLowerCase","includes","set","$id","uids","Set","filter","Boolean","includeAdmins","role","add","addresses","lookups","uid","get","pooled","catch","record","recipients","length","content","subject","text","orgName","to","slice","result","fromName","context","meterOrgEmail","undefined","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,2BAA2B,QAAQ,oBAAgB;AAC5D,SAASC,wBAAwB,QAAQ,kBAAc;AACvD,SAASC,sBAAsB,QAAQ,yBAAqB;AAC5D,SAASC,cAAc,QAAQ,qBAAiB;AAChD,SAASC,mBAAmB,EAAEC,wBAAwB,QAAQ,2BAAuB;AAuCrF,0EAA0E,GAC1E,MAAMC,cAAc;AACpB,MAAMC,YAAY;AAElB,2DAA2D,GAC3D,OAAO,eAAeC,oBAAoBC,KAA2B;IACnE,IAAI,CAACX,qBAAqB,OAAO;QAAEY,MAAM;QAAGC,QAAQ;IAAe;IACnE,IAAI;YAuCcC;QAtChB,MAAMC,UAAU,MAAMV,eAAeM,MAAMK,KAAK;QAChD,MAAMC,cAAc,IAAIC;QACxB,KAAK,MAAMC,UAAUJ,QAAS;gBACLI;YAAvB,MAAMC,UAAUC,QAAOF,gBAAAA,OAAOG,KAAK,YAAZH,gBAAgB,IACpCI,IAAI,GACJC,W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,iBAAiB;QAC/B,GACAA,OACA,uEAAuE;QACvE;YAAE+B,SAASlC,MAAMkC,OAAO;YAAEC,MAAM,GAAGnC,MAAMkC,OAAO,CAAC,IAAI,EAAElC,MAAMmC,IAAI,EAAE;QAAC;QAEtE,IAAIlC,OAAO;QACX,KAAK,MAAMoC,MAAMN,WAAWO,KAAK,CAAC,GAAGxC,WAAY;YAC/C,MAAMyC,SAAS,MAAMjD,UAAU;gBAC7B+C;eACGJ,SACC9B,MAAMqC,QAAQ,GAAG;gBAAEA,UAAUrC,MAAMqC,QAAQ;YAAC,IAAI,CAAC;gBACrDC,SAASzC,MAAMyC,OAAO;;YAExB,IAAI,CAACF,OAAOtC,IAAI,EAAE;YAClBA,QAAQ;YACR,MAAM,EAAEyC,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC;YACvC,MAAMA,cAAc1C,MAAMK,KAAK,EAAEwB,KAAK,CAAC,IAAMc;QAC/C;QACA,OAAO1C,OAAO;YAAEA;QAAK,IAAI;YAAEA,MAAM;YAAGC,QAAQ;QAAS;IACvD,EAAE,OAAO0C,OAAO;QACdC,QAAQD,KAAK,CAAC,mCAAmCA;QACjD,OAAO;YAAE3C,MAAM;YAAGC,QAAQ;QAAS;IACrC;AACF"}
@@ -37,6 +37,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
37
37
  * substituting the admin barrel substitutes these too.
38
38
  *=========================================*/ import { createHash } from "crypto";
39
39
  import { ABUSE_REPORT_COLLECTION } from "@aglyn/aglyn/app-utils/abuse-report";
40
+ import { RISK_PAYMENT_EVENTS } from "@aglyn/shared-util-email/risk-notice-catalog";
40
41
  import { FieldValue } from "firebase-admin/firestore";
41
42
  const KIND_LABEL = {
42
43
  'early-fraud-warning': 'Early fraud warning',
@@ -176,7 +177,7 @@ const KIND_LABEL = {
176
177
  merge: true
177
178
  });
178
179
  if (first) {
179
- var _ref, _signal_chargeId;
180
+ var _RISK_PAYMENT_EVENTS_signal_kind, _ref, _signal_chargeId;
180
181
  // The workspace's owners are told their subscription payment was
181
182
  // flagged and how to confirm it; staff get the row with the evidence.
182
183
  await deps.notifyRisk({
@@ -189,6 +190,9 @@ const KIND_LABEL = {
189
190
  path: '/org/billing/invoices'
190
191
  },
191
192
  amount: formatSignalAmount(signal.amountCents, signal.currency),
193
+ // A dispute is the bank's, already opened; a warning or a review is
194
+ // a fraud check. The notice says which.
195
+ paymentEvent: (_RISK_PAYMENT_EVENTS_signal_kind = RISK_PAYMENT_EVENTS[signal.kind]) != null ? _RISK_PAYMENT_EVENTS_signal_kind : null,
192
196
  stripeUrl: stripeSignalDashboardUrl(signal),
193
197
  staffEvidence: `${KIND_LABEL[signal.kind]} (${signal.stripeObjectId}) on charge ` + `${(_ref = (_signal_chargeId = signal.chargeId) != null ? _signal_chargeId : signal.paymentIntentId) != null ? _ref : 'not named'}` + (signal.detail ? `; Stripe says: ${signal.detail}` : '') + (signal.livemode ? '' : ' — TEST MODE') + '.'
194
198
  }).catch(()=>undefined);