@aglyn/aglyn 1.0.0-beta.151 → 1.0.0-beta.152

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.
@@ -65,6 +65,17 @@ export declare function notificationMuted(prefs: Record<string, boolean> | null
65
65
  * notification and the email it travels with.
66
66
  */
67
67
  export declare const DIGEST_PREFS_FIELD = "digestPrefs";
68
+ /**
69
+ * The key the daily CRM digest keeps inside {@link DIGEST_PREFS_FIELD}.
70
+ *
71
+ * Exported so the console writes the switch through a name rather than a
72
+ * second copy of the string (AGL-3230). The reader below and the page that
73
+ * flips it were spelling the same literal in two files, which is how a
74
+ * preference comes to be written under one key and read under another — and
75
+ * it kept the plugin's vocabulary in a console page, where
76
+ * `check:plugin-domain-in-core` rightly refuses it.
77
+ */
78
+ export declare const CRM_DAILY_DIGEST_KEY = "crmDaily";
68
79
  export declare function crmDailyDigestEnabled(prefs: Record<string, boolean> | null | undefined): boolean;
69
80
  /**
70
81
  * The field on `users/{uid}` naming the workspaces whose weekly insights a
@@ -96,8 +96,18 @@ export function notificationCategory(type) {
96
96
  * drops, not a bucket of types, and one switch governs both the console
97
97
  * notification and the email it travels with.
98
98
  */ export const DIGEST_PREFS_FIELD = 'digestPrefs';
99
+ /**
100
+ * The key the daily CRM digest keeps inside {@link DIGEST_PREFS_FIELD}.
101
+ *
102
+ * Exported so the console writes the switch through a name rather than a
103
+ * second copy of the string (AGL-3230). The reader below and the page that
104
+ * flips it were spelling the same literal in two files, which is how a
105
+ * preference comes to be written under one key and read under another — and
106
+ * it kept the plugin's vocabulary in a console page, where
107
+ * `check:plugin-domain-in-core` rightly refuses it.
108
+ */ export const CRM_DAILY_DIGEST_KEY = 'crmDaily';
99
109
  export function crmDailyDigestEnabled(prefs) {
100
- return (prefs == null ? void 0 : prefs['crmDaily']) !== false;
110
+ return (prefs == null ? void 0 : prefs[CRM_DAILY_DIGEST_KEY]) !== false;
101
111
  }
102
112
  /**
103
113
  * The field on `users/{uid}` naming the workspaces whose weekly insights a
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/notifications.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 type { ITimestamp } from '@aglyn/shared-util-timestamp'\n\n/**\n * In-app notifications (AGL-259): per-user docs at\n * `users/{uid}/notifications/{id}`, written by the Admin SDK (emitters in\n * the API routes + the `notifyAdmins` automation step) and read/marked by\n * their owner. Types follow the common SaaS taxonomy so the console can\n * icon/group them without a registry.\n */\nexport type AglynNotificationType =\n | 'billing.invoice'\n | 'billing.paymentFailed'\n // Stripe gave up on a failed renewal and CANCELLED the subscription\n // (AGL-1877). Distinct from `paymentFailed`, which announces one failed\n // attempt inside a retry window the customer can still recover from; this\n // one is the window having closed. Measured on the test account with a\n // test clock: five attempts over 21.08 days, then\n // `cancellation_details.reason: 'payment_failed'` — and until this existed\n // the org went silently to Free at that moment, with the `past_due` banner\n // disappearing at exactly the instant the consequence arrived.\n | 'billing.subscriptionCanceled'\n | 'billing.usage'\n | 'team.invite'\n | 'team.roleChanged'\n | 'team.hostAccessGranted'\n | 'content.formSubmission'\n | 'content.booking'\n | 'content.order'\n | 'content.lowStock'\n // A CRM task was assigned to the recipient by somebody else (AGL-2599).\n // `content.` because it is the same kind of message as a form submission\n // or a booking: a thing on the site that now needs this person's hands,\n // not a change to their standing (`team.`) and not a platform notice\n // (`system.`). Someone who has muted the operational stream has said they\n // do not want to be told about work as it arrives, and a task is work.\n | 'content.taskAssigned'\n // A CRM task's reminder came due (AGL-2659): the hourly runner telling\n // the assignee, at the task's own time, that the task is due. `content.`\n // beside `taskAssigned` for the same reason it gives — work on the site,\n // not standing — and so the one mute that stops \"work arriving\" stops\n // \"work falling due\" with it. The mute governs the whole reminder, mail\n // included, unlike the digest's: a reminder is one message about one\n // task, and there is no schedule to keep separately from it.\n | 'content.taskReminder'\n // A contact, or a lead, became the recipient's to work (AGL-2618): a\n // capture the assignment rules or the site's default owner routed to\n // them, a lead somebody converted and handed to them, or an automation's\n // \"assign an owner\" step — every server path that writes `ownerUid`\n // except the recipient assigning themselves. Two types rather than one\n // because the record the person opens differs: a lead is the site's own\n // working record and a contact is the org's, and the link goes to the\n // one they will actually work. `content.`, beside `taskAssigned`, for the\n // same reason: work arriving, not standing changing.\n | 'content.contactAssigned'\n | 'content.leadAssigned'\n // The morning's CRM digest (AGL-2619): what the recipient owes today —\n // overdue and due-today tasks, and the leads nobody has worked. `content.`\n // for the reason `taskAssigned` is: it is about work on the site, and the\n // person who muted the operational stream has asked not to be told about\n // work. The digest EMAIL is governed separately, by\n // `crmDailyDigestEnabled`: the mute is a fact about the console feed and\n // the digest switch is a fact about the digest.\n | 'content.crmDailyDigest'\n // The weekly insights (AGL-2915): what a site's figures showed that week,\n // for a person who asked for them. `content.` beside the CRM digest, for the\n // reason that one gives: it is about the site's work, and the operational\n // mute governs the console notification while the person's own switch for\n // the digest governs the digest.\n | 'content.insightsDigest'\n // Marketplace review verdicts (AGL-432/653).\n | 'marketplace.review'\n // Support desk, staff audience (AGL-850): a subscriber opened or replied to\n // a ticket. Fanned out to staff-claim holders, not org members.\n | 'support.ticketOpened'\n | 'support.ticketReply'\n | 'system.announcement'\n // A live plugin version stopped passing the static verifier (AGL-1086).\n // Staff audience: bytes we told workspaces were checked now fail checks\n // that did not exist when they were approved.\n //\n // Deliberately NOT under `marketplace.` (AGL-1088). Category is the prefix,\n // categories are mutable per user, and Marketplace is the category a staff\n // member mutes to stop routine listing-review chatter — which would drop\n // this alert as collateral. `system` is the bucket nobody mutes to reduce\n // noise. The adminAudit record survives a mute either way; the timeliness\n // does not, and timeliness is the whole point of the alert.\n | 'system.pluginVerifierRegression'\n // A sign-in method was removed from the user's own account because their\n // organization turned on SSO enforcement (AGL-1129). `system.`, not\n // `team.`, for the AGL-1088 reason above: `team` is the category someone\n // mutes to stop routine roster chatter, and \"the way you sign in just\n // changed\" is not chatter — the next sign-in fails without it.\n | 'system.signInMethodRemoved'\n // Documents in a scoped collection carrying no `visibleTo` (AGL-1478).\n // Staff audience: the weekly dry run found resources that are invisible\n // to every site-scoped read, which always means a creation path forgot\n // the field. `system.` for the AGL-1088 reason above, and because the\n // collection it names may be `marketplace`-adjacent or not.\n | 'system.scopeDrift'\n // An SSO domain that WAS DNS-proven has stopped answering with our\n // challenge record, for three consecutive weekly sweeps (AGL-1210).\n // Nothing has been turned off — sign-in for that domain still routes\n // exactly as it did — and that is precisely why this has to be said out\n // loud rather than left in a log.\n //\n // `system.`, not `team.`, for the AGL-1088 reason above and one of its\n // own: the audience is the org's own admins, the subject is whether their\n // people can still sign in, and it must reach them BEFORE anybody decides\n // to revoke the routing. A category somebody mutes to quieten roster\n // chatter is the wrong place for the one warning that precedes a lockout.\n | 'system.ssoDomainUnverified'\n // A site hit the per-month form-submission abuse ceiling and further\n // submissions are being refused (AGL-1655). `system.`, not `content.`, for\n // the AGL-1088 reason above and more sharply than any of them: `content` is\n // literally the category a site owner mutes to stop routine form-submission\n // chatter, and this is the one form notification that says the form has\n // STOPPED accepting. Filing it under the muted bucket would guarantee it\n // reaches nobody on exactly the sites busy enough to trip it.\n | 'system.formSubmissionsPaused'\n // A site reached the flat platform ceiling on member accounts or on lead\n // records, so further ones are being refused (AGL-1529). `system.` for the\n // same reason as `formSubmissionsPaused` directly above, and with the same\n // sharpness: `content.` is the bucket an owner mutes to stop routine\n // sign-up and lead chatter, and this is the one notification saying the\n // sign-ups have STOPPED — muted exactly on the sites busy enough to trip it.\n | 'system.visitorRecordsPaused'\n // An outsider reported one of our sites for phishing, malware or CSAM\n // (AGL-1964). `system` for the AGL-1088 reason and, again, more sharply\n // than most: this notification goes to STAFF, not to a customer, and its\n // subject is somebody else's site. There is no bucket a recipient could\n // mute it into that would be honest — nobody has opted into being told a\n // stranger is being phished through our platform, and nobody should be able\n // to opt out of it either.\n //\n // Only the urgent categories raise one, and only on a first report. See the\n // fan-out in apps/tenant/app/api/report-abuse/route.ts for why: a flood of\n // alerts IS the flood, and the alert it would cost us is the phishing one.\n | 'system.abuseReportUrgent'\n // The §512(g) counter-notice (AGL-1983), and the one place the \"only urgent\n // categories raise a notification\" restraint above is deliberately not\n // applied. Every counter-notice carries a statutory deadline that is\n // ALREADY RUNNING when it arrives — the clock counts from the subscriber's\n // submission, not from our attention — so there is no low-value tail of\n // these to drown out the important ones, and the one that goes unread is a\n // customer locked out of their own work plus an unmet obligation under\n // §512(g)(2)(A). Raised on first submission only, like the one above, so a\n // resubmitting customer cannot re-alert.\n | 'system.dmcaCounterNotice'\n // A site crossed the per-month bandwidth abuse ceiling (AGL-2155). Two\n // audiences share one type: staff, because an uncompensated free site\n // serving six figures of page views is an incident; and the site's own\n // managers, because on free the site is now serving a capped notice and\n // nobody should learn that from a visitor.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this meter: on the free plan there is no bill, so `billing` would be the\n // one category where the message is literally never about money — and it is\n // exactly the free-tier trip that changes what visitors see.\n | 'system.bandwidthCeilingTripped'\n // A free site crossed its PLAN's included bandwidth and is now serving the\n // capped notice (AGL-2413). Distinct from the ceiling above on purpose: that\n // one is an incident at 10x the band and goes to staff first; this one is an\n // ordinary quota at 1x, concerns only the site's own managers, and its\n // remedy is an upgrade rather than an investigation. Sending both under one\n // type would tell an owner their traffic was being treated as suspected\n // abuse when it is simply a successful free site.\n | 'system.bandwidthCapEngaged'\n // A Stripe billing webhook threw AFTER its handlers had begun (AGL-2157),\n // so its side effects may be half applied and its idempotency claim is\n // being HELD — Stripe will not retry it. Staff audience: this is the one\n // failure on that route no automatic retry can make safe, because the\n // handlers behind it are not all idempotent, and a human has to reconcile.\n | 'system.billingWebhookHalfApplied'\n // A card dispute arrived that NOTHING in the platform claimed (AGL-2429):\n // no `platformRevenue` row, no storefront order, no marketplace purchase.\n // Staff audience, and the reason it needs a type of its own is that its\n // absence was the bug — the routine case (a storefront or marketplace\n // chargeback, which the plugins own) and the fault case were the same\n // silence from the route's side, so a dispute nobody handled looked\n // exactly like one somebody did.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this alert: `billing` is the category a recipient is most likely to have\n // muted as routine invoice traffic, and this is the one message on that\n // route where muting it means money moves with nobody looking.\n | 'system.disputeUnattributed'\n // Somebody created an account, and somebody created a workspace\n // (AGL-3225). Staff audience, and the only two types in the taxonomy whose\n // subject is the platform's own growth rather than anybody's work.\n //\n // `staff.`, and NOT `system.`, and the AGL-1088 note above is the reason\n // rather than an exception to it: `system` is the bucket nobody mutes to\n // reduce noise, which is exactly what makes it the wrong home for the two\n // routine, high-volume events in the product. A staff member must be able\n // to stop hearing about every sign-up without also dropping the verifier\n // regression and the unattributed dispute that share that bucket — and\n // before this category existed, there was nowhere to put them where that\n // was true.\n //\n // The category also tells the settings page who a row is for: `staff` is\n // rendered only to claim holders, so no customer is shown a switch for\n // notifications they could never receive.\n | 'staff.userSignedUp'\n | 'staff.orgCreated'\n\nexport interface AglynNotification {\n $id?: string\n type: AglynNotificationType\n title: string\n body?: string\n /** Console path the notification opens (e.g. a host inbox). */\n link?: string\n orgId?: string\n hostId?: string\n createdAt?: ITimestamp\n /** Set by the owner when read; unread while absent. */\n readAt?: ITimestamp | null\n}\n\nexport const NOTIFICATION_TYPE_LABELS: Record<AglynNotificationType, string> =\n {\n 'billing.invoice': 'Invoice available',\n 'billing.paymentFailed': 'Payment failed',\n 'billing.subscriptionCanceled': 'Subscription canceled',\n 'billing.usage': 'Usage threshold',\n 'team.invite': 'Team invite',\n 'team.roleChanged': 'Role changed',\n 'team.hostAccessGranted': 'Site access granted',\n 'content.formSubmission': 'Form submission',\n 'content.booking': 'New booking',\n 'content.order': 'New order',\n 'content.lowStock': 'Low stock',\n 'content.taskAssigned': 'Task assigned to you',\n 'content.taskReminder': 'Task reminder',\n 'content.contactAssigned': 'Contact assigned to you',\n 'content.leadAssigned': 'Lead assigned to you',\n 'content.crmDailyDigest': 'Daily CRM digest',\n 'content.insightsDigest': 'Weekly insights',\n 'marketplace.review': 'Listing review',\n\n 'support.ticketOpened': 'New support ticket',\n 'support.ticketReply': 'Support ticket reply',\n 'system.announcement': 'Announcement',\n 'system.pluginVerifierRegression': 'Plugin verifier regression',\n 'system.signInMethodRemoved': 'Sign-in method removed',\n 'system.scopeDrift': 'Resources missing a sharing scope',\n 'system.ssoDomainUnverified': 'SSO domain no longer proves ownership',\n 'system.formSubmissionsPaused': 'Form submissions paused',\n 'system.visitorRecordsPaused': 'Sign-ups or leads paused',\n 'system.abuseReportUrgent': 'Urgent abuse report',\n 'system.dmcaCounterNotice': 'DMCA counter-notice',\n 'system.bandwidthCeilingTripped': 'Bandwidth ceiling reached',\n 'system.bandwidthCapEngaged': 'Monthly traffic limit reached',\n 'system.billingWebhookHalfApplied': 'Billing webhook half applied',\n 'system.disputeUnattributed': 'Card dispute with no owner',\n 'staff.userSignedUp': 'New account',\n 'staff.orgCreated': 'New workspace',\n }\n\n/** Preference buckets (AGL-267): the prefix before the dot. */\nexport type NotificationCategory =\n | 'billing'\n | 'team'\n | 'content'\n | 'marketplace'\n | 'support'\n | 'system'\n // Staff-only, and shown only to staff (AGL-3225) — see\n // {@link STAFF_NOTIFICATION_CATEGORIES}.\n | 'staff'\n\nexport const NOTIFICATION_CATEGORY_LABELS: Record<\n NotificationCategory,\n string\n> = {\n billing: 'Billing',\n team: 'Team & access',\n content: 'Forms & bookings',\n marketplace: 'Marketplace',\n support: 'Support',\n system: 'Product & system',\n staff: 'Platform growth',\n}\n\n/**\n * The categories only staff can receive (AGL-3225).\n *\n * The settings page hides these rows from everybody else, because a switch\n * for mail that can never arrive is a promise the product does not keep. It\n * is presentation only: `notifyStaff` is what decides the audience, and it\n * enumerates the `staff` claim rather than reading this.\n */\nexport const STAFF_NOTIFICATION_CATEGORIES: ReadonlySet<NotificationCategory> =\n new Set<NotificationCategory>(['staff'])\n\nexport function notificationCategory(\n type: AglynNotificationType | string,\n): NotificationCategory {\n const prefix = String(type).split('.')[0]\n return (\n [\n 'billing',\n 'team',\n 'content',\n 'marketplace',\n 'support',\n 'system',\n 'staff',\n ].includes(prefix)\n ? prefix\n : 'system'\n ) as NotificationCategory\n}\n\n/**\n * Per-user mute map stored at `users/{uid}.notificationPrefs`\n * (`{ [category]: false }` mutes); absent categories stay on.\n */\nexport function notificationMuted(\n prefs: Record<string, boolean> | null | undefined,\n type: AglynNotificationType | string,\n): boolean {\n return prefs?.[notificationCategory(type)] === false\n}\n\n/**\n * The field on `users/{uid}` that holds a person's digest switches\n * (AGL-2619): `{ crmDaily: false }` turns the daily CRM digest off, and an\n * absent key leaves it on. Its own map rather than a key in\n * `notificationPrefs`, because that map is keyed by CATEGORY and read by\n * {@link notificationMuted} — a digest is a schedule a person keeps or\n * drops, not a bucket of types, and one switch governs both the console\n * notification and the email it travels with.\n */\nexport const DIGEST_PREFS_FIELD = 'digestPrefs'\n\nexport function crmDailyDigestEnabled(\n prefs: Record<string, boolean> | null | undefined,\n): boolean {\n return prefs?.['crmDaily'] !== false\n}\n\n/**\n * The field on `users/{uid}` naming the workspaces whose weekly insights a\n * person asked for (AGL-2915): `{ [orgId]: true }`. OPT-IN, unlike the CRM\n * digest — an absent key is off — because a weekly insight is generated, and a\n * generation spends the workspace's credits. The person turns it on beside the\n * answers themselves, where the plan, the release and their permission have\n * already been checked, and off again there or in Notifications; the weekly\n * sweep checks all three again before it spends anything.\n */\nexport const INSIGHT_DIGESTS_FIELD = 'insightDigests'\n\n/** Whether a person asked for a workspace's weekly insights. */\nexport function insightDigestSubscribed(\n value: Record<string, boolean> | null | undefined,\n orgId: string,\n): boolean {\n return Boolean(orgId) && value?.[orgId] === true\n}\n\n/**\n * The channels a notification can travel on (AGL-3223).\n *\n * `console` is the feed at `/manage/notifications` and the app-bar dropdown\n * that reads it — the only channel that existed. `email` is the message the\n * fan-out sends beside that doc when the recipient asked for one.\n */\nexport type NotificationChannel = 'console' | 'email'\n\n/**\n * One scope's answer for one category. **Tri-state on purpose**: `true` and\n * `false` decide, and an ABSENT key inherits from the scope above.\n *\n * Inheritance is the whole reason this is a partial rather than a pair of\n * booleans. A person who wants form submissions from one busy site and not\n * from the other five has to be able to say that about the one site without\n * restating their answer for every other category at every other scope — and\n * a two-valued leaf cannot express \"I have not said\", so every override would\n * have to be written out in full and would then stop tracking the account\n * default it was never meant to detach from.\n */\nexport interface NotificationChannelPrefs {\n console?: boolean\n email?: boolean\n}\n\nexport type NotificationCategoryPrefs = Partial<\n Record<NotificationCategory, NotificationChannelPrefs>\n>\n\n/**\n * Per-scope, per-channel notification preferences (AGL-3223), stored at\n * `users/{uid}.notificationSettings`.\n *\n * Three layers, narrowest first when resolving: the SITE a notification\n * concerns, then the WORKSPACE, then the account. Anything none of them\n * answers falls to {@link NOTIFICATION_CHANNEL_DEFAULTS}.\n *\n * ON THE USER DOCUMENT, not on `orgs/{orgId}/members/{uid}`, and that is a\n * cost decision rather than a modelling preference. `notifyUsers` already\n * does exactly one `getAll` over the recipients' user docs to read their\n * category mutes, so every layer living here means per-site preferences are\n * read for free on the fan-out's hot path. The member row would add a read\n * per recipient per notification to answer a question the document already in\n * hand could have answered.\n */\nexport interface NotificationSettings {\n account?: NotificationCategoryPrefs\n /** Keyed by org id. */\n orgs?: Record<string, NotificationCategoryPrefs>\n /** Keyed by host id — a site's own answer, narrower than its workspace's. */\n hosts?: Record<string, NotificationCategoryPrefs>\n}\n\nexport const NOTIFICATION_SETTINGS_FIELD = 'notificationSettings'\n\n/**\n * What a category does when nobody has said otherwise.\n *\n * Console on, email OFF, everywhere. Email defaults off because the inbox is\n * not ours to fill: the product already sends transactional mail nobody opted\n * into — welcome, verification, invites, dunning, usage alerts — and every one\n * of those leaves on the same domain a customer's password reset depends on.\n * Turning a busy site's form submissions into mail by default would put that\n * domain's reputation behind traffic the recipient never asked for.\n *\n * Exhaustive `Record` deliberately: a new {@link NotificationCategory} is a\n * compile error here until somebody decides what it does by default, which is\n * the one question a new category must not be able to ship without answering.\n */\nexport const NOTIFICATION_CHANNEL_DEFAULTS: Record<\n NotificationCategory,\n Record<NotificationChannel, boolean>\n> = {\n billing: { console: true, email: false },\n team: { console: true, email: false },\n content: { console: true, email: false },\n marketplace: { console: true, email: false },\n support: { console: true, email: false },\n system: { console: true, email: false },\n // Console ON, because the complaint this answers is that staff never heard\n // about a sign-up at all; email off, like everything else, because that is\n // what the channel defaults to and a sign-up is not urgent enough to be the\n // exception that starts filling inboxes by default.\n staff: { console: true, email: false },\n}\n\n/**\n * The types that send their OWN email and must never be mailed again by the\n * generic channel (AGL-3224).\n *\n * Both digests compose a message the fan-out could not reproduce — a day's\n * owed tasks, a week's figures — and send it from their own route under their\n * own switch (`digestPrefs.crmDaily`, `insightDigests.{orgId}`). A recipient\n * who switches the `content` email channel on would otherwise receive the\n * digest twice: once as the digest, once as a one-line \"Daily CRM digest\"\n * notification saying that the digest happened.\n */\nexport const NOTIFICATION_SELF_SENT_EMAIL_TYPES: ReadonlySet<string> = new Set<\n AglynNotificationType\n>(['content.crmDailyDigest', 'content.insightsDigest'])\n\n/**\n * Whether a channel is on for one notification, at its own scope.\n *\n * Resolution order, first answer wins: the notification's SITE, its\n * WORKSPACE, the account, then {@link NOTIFICATION_CHANNEL_DEFAULTS}. A scope\n * that holds no entry for the category, or an entry with the channel key\n * absent, does not answer — see {@link NotificationChannelPrefs}.\n *\n * `legacyPrefs` is the flat `notificationPrefs` mute map this replaces\n * (AGL-267), and it sits BELOW the account layer rather than beside it.\n * Nothing migrates it: a person who never opens the new settings page keeps\n * being governed by the mutes they set years ago, and the first thing they do\n * set on the account layer overrides the old map for that category without\n * disturbing the rest of it. It answers for `console` only, because the map\n * predates there being a second channel and reading a console mute as an\n * email preference would be inventing an answer its author never gave.\n */\nexport function notificationChannelEnabled(\n settings: NotificationSettings | null | undefined,\n channel: NotificationChannel,\n type: AglynNotificationType | string,\n scope?: { orgId?: string | null; hostId?: string | null },\n legacyPrefs?: Record<string, boolean> | null,\n): boolean {\n const category = notificationCategory(type)\n const layers: Array<NotificationCategoryPrefs | undefined> = [\n scope?.hostId ? settings?.hosts?.[scope.hostId] : undefined,\n scope?.orgId ? settings?.orgs?.[scope.orgId] : undefined,\n settings?.account,\n ]\n for (const layer of layers) {\n const answer = layer?.[category]?.[channel]\n if (typeof answer === 'boolean') return answer\n }\n if (channel === 'console' && notificationMuted(legacyPrefs, type)) return false\n return NOTIFICATION_CHANNEL_DEFAULTS[category][channel]\n}\n\n/**\n * What one scope says, with no inheritance applied — what the settings page\n * renders as Inherit / On / Off, and `undefined` is Inherit.\n *\n * `scope` names the layer directly rather than being derived from a\n * notification, because the page edits a layer whether or not anything has\n * ever arrived from it.\n */\nexport function notificationScopePref(\n settings: NotificationSettings | null | undefined,\n scope: { kind: 'account' } | { kind: 'org' | 'host'; id: string },\n category: NotificationCategory,\n channel: NotificationChannel,\n): boolean | undefined {\n const layer =\n scope.kind === 'account'\n ? settings?.account\n : scope.kind === 'org'\n ? settings?.orgs?.[scope.id]\n : settings?.hosts?.[scope.id]\n return layer?.[category]?.[channel]\n}\n\n/**\n * The scopes this person has said something different about — what the\n * settings page lists so an override is never somewhere you have to go\n * looking for.\n *\n * Returns ids, not names: the page holds the org and host rosters and this\n * module holds no lookups. An id with no name is still worth listing, because\n * a preference about a workspace somebody left is exactly the kind of\n * leftover that is invisible until it is listed.\n */\nexport function notificationOverriddenScopes(\n settings: NotificationSettings | null | undefined,\n): { orgIds: string[]; hostIds: string[] } {\n const named = (layers: Record<string, NotificationCategoryPrefs> | undefined) =>\n Object.entries(layers ?? {})\n .filter(([, prefs]) =>\n Object.values(prefs ?? {}).some((channels) =>\n Object.values(channels ?? {}).some(\n (value) => typeof value === 'boolean',\n ),\n ),\n )\n .map(([id]) => id)\n .sort()\n return { orgIds: named(settings?.orgs), hostIds: named(settings?.hosts) }\n}\n"],"names":["NOTIFICATION_TYPE_LABELS","NOTIFICATION_CATEGORY_LABELS","billing","team","content","marketplace","support","system","staff","STAFF_NOTIFICATION_CATEGORIES","Set","notificationCategory","type","prefix","String","split","includes","notificationMuted","prefs","DIGEST_PREFS_FIELD","crmDailyDigestEnabled","INSIGHT_DIGESTS_FIELD","insightDigestSubscribed","value","orgId","Boolean","NOTIFICATION_SETTINGS_FIELD","NOTIFICATION_CHANNEL_DEFAULTS","console","email","NOTIFICATION_SELF_SENT_EMAIL_TYPES","notificationChannelEnabled","settings","channel","scope","legacyPrefs","category","layers","hostId","hosts","undefined","orgs","account","layer","answer","notificationScopePref","kind","id","notificationOverriddenScopes","named","Object","entries","filter","values","some","channels","map","sort","orgIds","hostIds"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GA6ND,OAAO,MAAMA,2BACX;IACE,mBAAmB;IACnB,yBAAyB;IACzB,gCAAgC;IAChC,iBAAiB;IACjB,eAAe;IACf,oBAAoB;IACpB,0BAA0B;IAC1B,0BAA0B;IAC1B,mBAAmB;IACnB,iBAAiB;IACjB,oBAAoB;IACpB,wBAAwB;IACxB,wBAAwB;IACxB,2BAA2B;IAC3B,wBAAwB;IACxB,0BAA0B;IAC1B,0BAA0B;IAC1B,sBAAsB;IAEtB,wBAAwB;IACxB,uBAAuB;IACvB,uBAAuB;IACvB,mCAAmC;IACnC,8BAA8B;IAC9B,qBAAqB;IACrB,8BAA8B;IAC9B,gCAAgC;IAChC,+BAA+B;IAC/B,4BAA4B;IAC5B,4BAA4B;IAC5B,kCAAkC;IAClC,8BAA8B;IAC9B,oCAAoC;IACpC,8BAA8B;IAC9B,sBAAsB;IACtB,oBAAoB;AACtB,EAAC;AAcH,OAAO,MAAMC,+BAGT;IACFC,SAAS;IACTC,MAAM;IACNC,SAAS;IACTC,aAAa;IACbC,SA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AMa,EAAE,CAAC;IACnC,OAAOJ,0BAAAA,kBAAAA,KAAO,CAACP,SAAS,qBAAjBO,eAAmB,CAACV,QAAQ;AACrC;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASe,6BACdhB,QAAiD;IAEjD,MAAMiB,QAAQ,CAACZ,SACba,OAAOC,OAAO,CAACd,iBAAAA,SAAU,CAAC,GACvBe,MAAM,CAAC,CAAC,GAAGlC,MAAM,GAChBgC,OAAOG,MAAM,CAACnC,gBAAAA,QAAS,CAAC,GAAGoC,IAAI,CAAC,CAACC,WAC/BL,OAAOG,MAAM,CAACE,mBAAAA,WAAY,CAAC,GAAGD,IAAI,CAChC,CAAC/B,QAAU,OAAOA,UAAU,aAIjCiC,GAAG,CAAC,CAAC,CAACT,GAAG,GAAKA,IACdU,IAAI;IACT,OAAO;QAAEC,QAAQT,MAAMjB,4BAAAA,SAAUS,IAAI;QAAGkB,SAASV,MAAMjB,4BAAAA,SAAUO,KAAK;IAAE;AAC1E"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/notifications.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 type { ITimestamp } from '@aglyn/shared-util-timestamp'\n\n/**\n * In-app notifications (AGL-259): per-user docs at\n * `users/{uid}/notifications/{id}`, written by the Admin SDK (emitters in\n * the API routes + the `notifyAdmins` automation step) and read/marked by\n * their owner. Types follow the common SaaS taxonomy so the console can\n * icon/group them without a registry.\n */\nexport type AglynNotificationType =\n | 'billing.invoice'\n | 'billing.paymentFailed'\n // Stripe gave up on a failed renewal and CANCELLED the subscription\n // (AGL-1877). Distinct from `paymentFailed`, which announces one failed\n // attempt inside a retry window the customer can still recover from; this\n // one is the window having closed. Measured on the test account with a\n // test clock: five attempts over 21.08 days, then\n // `cancellation_details.reason: 'payment_failed'` — and until this existed\n // the org went silently to Free at that moment, with the `past_due` banner\n // disappearing at exactly the instant the consequence arrived.\n | 'billing.subscriptionCanceled'\n | 'billing.usage'\n | 'team.invite'\n | 'team.roleChanged'\n | 'team.hostAccessGranted'\n | 'content.formSubmission'\n | 'content.booking'\n | 'content.order'\n | 'content.lowStock'\n // A CRM task was assigned to the recipient by somebody else (AGL-2599).\n // `content.` because it is the same kind of message as a form submission\n // or a booking: a thing on the site that now needs this person's hands,\n // not a change to their standing (`team.`) and not a platform notice\n // (`system.`). Someone who has muted the operational stream has said they\n // do not want to be told about work as it arrives, and a task is work.\n | 'content.taskAssigned'\n // A CRM task's reminder came due (AGL-2659): the hourly runner telling\n // the assignee, at the task's own time, that the task is due. `content.`\n // beside `taskAssigned` for the same reason it gives — work on the site,\n // not standing — and so the one mute that stops \"work arriving\" stops\n // \"work falling due\" with it. The mute governs the whole reminder, mail\n // included, unlike the digest's: a reminder is one message about one\n // task, and there is no schedule to keep separately from it.\n | 'content.taskReminder'\n // A contact, or a lead, became the recipient's to work (AGL-2618): a\n // capture the assignment rules or the site's default owner routed to\n // them, a lead somebody converted and handed to them, or an automation's\n // \"assign an owner\" step — every server path that writes `ownerUid`\n // except the recipient assigning themselves. Two types rather than one\n // because the record the person opens differs: a lead is the site's own\n // working record and a contact is the org's, and the link goes to the\n // one they will actually work. `content.`, beside `taskAssigned`, for the\n // same reason: work arriving, not standing changing.\n | 'content.contactAssigned'\n | 'content.leadAssigned'\n // The morning's CRM digest (AGL-2619): what the recipient owes today —\n // overdue and due-today tasks, and the leads nobody has worked. `content.`\n // for the reason `taskAssigned` is: it is about work on the site, and the\n // person who muted the operational stream has asked not to be told about\n // work. The digest EMAIL is governed separately, by\n // `crmDailyDigestEnabled`: the mute is a fact about the console feed and\n // the digest switch is a fact about the digest.\n | 'content.crmDailyDigest'\n // The weekly insights (AGL-2915): what a site's figures showed that week,\n // for a person who asked for them. `content.` beside the CRM digest, for the\n // reason that one gives: it is about the site's work, and the operational\n // mute governs the console notification while the person's own switch for\n // the digest governs the digest.\n | 'content.insightsDigest'\n // Marketplace review verdicts (AGL-432/653).\n | 'marketplace.review'\n // Support desk, staff audience (AGL-850): a subscriber opened or replied to\n // a ticket. Fanned out to staff-claim holders, not org members.\n | 'support.ticketOpened'\n | 'support.ticketReply'\n | 'system.announcement'\n // A live plugin version stopped passing the static verifier (AGL-1086).\n // Staff audience: bytes we told workspaces were checked now fail checks\n // that did not exist when they were approved.\n //\n // Deliberately NOT under `marketplace.` (AGL-1088). Category is the prefix,\n // categories are mutable per user, and Marketplace is the category a staff\n // member mutes to stop routine listing-review chatter — which would drop\n // this alert as collateral. `system` is the bucket nobody mutes to reduce\n // noise. The adminAudit record survives a mute either way; the timeliness\n // does not, and timeliness is the whole point of the alert.\n | 'system.pluginVerifierRegression'\n // A sign-in method was removed from the user's own account because their\n // organization turned on SSO enforcement (AGL-1129). `system.`, not\n // `team.`, for the AGL-1088 reason above: `team` is the category someone\n // mutes to stop routine roster chatter, and \"the way you sign in just\n // changed\" is not chatter — the next sign-in fails without it.\n | 'system.signInMethodRemoved'\n // Documents in a scoped collection carrying no `visibleTo` (AGL-1478).\n // Staff audience: the weekly dry run found resources that are invisible\n // to every site-scoped read, which always means a creation path forgot\n // the field. `system.` for the AGL-1088 reason above, and because the\n // collection it names may be `marketplace`-adjacent or not.\n | 'system.scopeDrift'\n // An SSO domain that WAS DNS-proven has stopped answering with our\n // challenge record, for three consecutive weekly sweeps (AGL-1210).\n // Nothing has been turned off — sign-in for that domain still routes\n // exactly as it did — and that is precisely why this has to be said out\n // loud rather than left in a log.\n //\n // `system.`, not `team.`, for the AGL-1088 reason above and one of its\n // own: the audience is the org's own admins, the subject is whether their\n // people can still sign in, and it must reach them BEFORE anybody decides\n // to revoke the routing. A category somebody mutes to quieten roster\n // chatter is the wrong place for the one warning that precedes a lockout.\n | 'system.ssoDomainUnverified'\n // A site hit the per-month form-submission abuse ceiling and further\n // submissions are being refused (AGL-1655). `system.`, not `content.`, for\n // the AGL-1088 reason above and more sharply than any of them: `content` is\n // literally the category a site owner mutes to stop routine form-submission\n // chatter, and this is the one form notification that says the form has\n // STOPPED accepting. Filing it under the muted bucket would guarantee it\n // reaches nobody on exactly the sites busy enough to trip it.\n | 'system.formSubmissionsPaused'\n // A site reached the flat platform ceiling on member accounts or on lead\n // records, so further ones are being refused (AGL-1529). `system.` for the\n // same reason as `formSubmissionsPaused` directly above, and with the same\n // sharpness: `content.` is the bucket an owner mutes to stop routine\n // sign-up and lead chatter, and this is the one notification saying the\n // sign-ups have STOPPED — muted exactly on the sites busy enough to trip it.\n | 'system.visitorRecordsPaused'\n // An outsider reported one of our sites for phishing, malware or CSAM\n // (AGL-1964). `system` for the AGL-1088 reason and, again, more sharply\n // than most: this notification goes to STAFF, not to a customer, and its\n // subject is somebody else's site. There is no bucket a recipient could\n // mute it into that would be honest — nobody has opted into being told a\n // stranger is being phished through our platform, and nobody should be able\n // to opt out of it either.\n //\n // Only the urgent categories raise one, and only on a first report. See the\n // fan-out in apps/tenant/app/api/report-abuse/route.ts for why: a flood of\n // alerts IS the flood, and the alert it would cost us is the phishing one.\n | 'system.abuseReportUrgent'\n // The §512(g) counter-notice (AGL-1983), and the one place the \"only urgent\n // categories raise a notification\" restraint above is deliberately not\n // applied. Every counter-notice carries a statutory deadline that is\n // ALREADY RUNNING when it arrives — the clock counts from the subscriber's\n // submission, not from our attention — so there is no low-value tail of\n // these to drown out the important ones, and the one that goes unread is a\n // customer locked out of their own work plus an unmet obligation under\n // §512(g)(2)(A). Raised on first submission only, like the one above, so a\n // resubmitting customer cannot re-alert.\n | 'system.dmcaCounterNotice'\n // A site crossed the per-month bandwidth abuse ceiling (AGL-2155). Two\n // audiences share one type: staff, because an uncompensated free site\n // serving six figures of page views is an incident; and the site's own\n // managers, because on free the site is now serving a capped notice and\n // nobody should learn that from a visitor.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this meter: on the free plan there is no bill, so `billing` would be the\n // one category where the message is literally never about money — and it is\n // exactly the free-tier trip that changes what visitors see.\n | 'system.bandwidthCeilingTripped'\n // A free site crossed its PLAN's included bandwidth and is now serving the\n // capped notice (AGL-2413). Distinct from the ceiling above on purpose: that\n // one is an incident at 10x the band and goes to staff first; this one is an\n // ordinary quota at 1x, concerns only the site's own managers, and its\n // remedy is an upgrade rather than an investigation. Sending both under one\n // type would tell an owner their traffic was being treated as suspected\n // abuse when it is simply a successful free site.\n | 'system.bandwidthCapEngaged'\n // A Stripe billing webhook threw AFTER its handlers had begun (AGL-2157),\n // so its side effects may be half applied and its idempotency claim is\n // being HELD — Stripe will not retry it. Staff audience: this is the one\n // failure on that route no automatic retry can make safe, because the\n // handlers behind it are not all idempotent, and a human has to reconcile.\n | 'system.billingWebhookHalfApplied'\n // A card dispute arrived that NOTHING in the platform claimed (AGL-2429):\n // no `platformRevenue` row, no storefront order, no marketplace purchase.\n // Staff audience, and the reason it needs a type of its own is that its\n // absence was the bug — the routine case (a storefront or marketplace\n // chargeback, which the plugins own) and the fault case were the same\n // silence from the route's side, so a dispute nobody handled looked\n // exactly like one somebody did.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this alert: `billing` is the category a recipient is most likely to have\n // muted as routine invoice traffic, and this is the one message on that\n // route where muting it means money moves with nobody looking.\n | 'system.disputeUnattributed'\n // Somebody created an account, and somebody created a workspace\n // (AGL-3225). Staff audience, and the only two types in the taxonomy whose\n // subject is the platform's own growth rather than anybody's work.\n //\n // `staff.`, and NOT `system.`, and the AGL-1088 note above is the reason\n // rather than an exception to it: `system` is the bucket nobody mutes to\n // reduce noise, which is exactly what makes it the wrong home for the two\n // routine, high-volume events in the product. A staff member must be able\n // to stop hearing about every sign-up without also dropping the verifier\n // regression and the unattributed dispute that share that bucket — and\n // before this category existed, there was nowhere to put them where that\n // was true.\n //\n // The category also tells the settings page who a row is for: `staff` is\n // rendered only to claim holders, so no customer is shown a switch for\n // notifications they could never receive.\n | 'staff.userSignedUp'\n | 'staff.orgCreated'\n\nexport interface AglynNotification {\n $id?: string\n type: AglynNotificationType\n title: string\n body?: string\n /** Console path the notification opens (e.g. a host inbox). */\n link?: string\n orgId?: string\n hostId?: string\n createdAt?: ITimestamp\n /** Set by the owner when read; unread while absent. */\n readAt?: ITimestamp | null\n}\n\nexport const NOTIFICATION_TYPE_LABELS: Record<AglynNotificationType, string> = {\n 'billing.invoice': 'Invoice available',\n 'billing.paymentFailed': 'Payment failed',\n 'billing.subscriptionCanceled': 'Subscription canceled',\n 'billing.usage': 'Usage threshold',\n 'team.invite': 'Team invite',\n 'team.roleChanged': 'Role changed',\n 'team.hostAccessGranted': 'Site access granted',\n 'content.formSubmission': 'Form submission',\n 'content.booking': 'New booking',\n 'content.order': 'New order',\n 'content.lowStock': 'Low stock',\n 'content.taskAssigned': 'Task assigned to you',\n 'content.taskReminder': 'Task reminder',\n 'content.contactAssigned': 'Contact assigned to you',\n 'content.leadAssigned': 'Lead assigned to you',\n 'content.crmDailyDigest': 'Daily CRM digest',\n 'content.insightsDigest': 'Weekly insights',\n 'marketplace.review': 'Listing review',\n\n 'support.ticketOpened': 'New support ticket',\n 'support.ticketReply': 'Support ticket reply',\n 'system.announcement': 'Announcement',\n 'system.pluginVerifierRegression': 'Plugin verifier regression',\n 'system.signInMethodRemoved': 'Sign-in method removed',\n 'system.scopeDrift': 'Resources missing a sharing scope',\n 'system.ssoDomainUnverified': 'SSO domain no longer proves ownership',\n 'system.formSubmissionsPaused': 'Form submissions paused',\n 'system.visitorRecordsPaused': 'Sign-ups or leads paused',\n 'system.abuseReportUrgent': 'Urgent abuse report',\n 'system.dmcaCounterNotice': 'DMCA counter-notice',\n 'system.bandwidthCeilingTripped': 'Bandwidth ceiling reached',\n 'system.bandwidthCapEngaged': 'Monthly traffic limit reached',\n 'system.billingWebhookHalfApplied': 'Billing webhook half applied',\n 'system.disputeUnattributed': 'Card dispute with no owner',\n 'staff.userSignedUp': 'New account',\n 'staff.orgCreated': 'New workspace',\n}\n\n/** Preference buckets (AGL-267): the prefix before the dot. */\nexport type NotificationCategory =\n | 'billing'\n | 'team'\n | 'content'\n | 'marketplace'\n | 'support'\n | 'system'\n // Staff-only, and shown only to staff (AGL-3225) — see\n // {@link STAFF_NOTIFICATION_CATEGORIES}.\n | 'staff'\n\nexport const NOTIFICATION_CATEGORY_LABELS: Record<\n NotificationCategory,\n string\n> = {\n billing: 'Billing',\n team: 'Team & access',\n content: 'Forms & bookings',\n marketplace: 'Marketplace',\n support: 'Support',\n system: 'Product & system',\n staff: 'Platform growth',\n}\n\n/**\n * The categories only staff can receive (AGL-3225).\n *\n * The settings page hides these rows from everybody else, because a switch\n * for mail that can never arrive is a promise the product does not keep. It\n * is presentation only: `notifyStaff` is what decides the audience, and it\n * enumerates the `staff` claim rather than reading this.\n */\nexport const STAFF_NOTIFICATION_CATEGORIES: ReadonlySet<NotificationCategory> =\n new Set<NotificationCategory>(['staff'])\n\nexport function notificationCategory(\n type: AglynNotificationType | string,\n): NotificationCategory {\n const prefix = String(type).split('.')[0]\n return (\n [\n 'billing',\n 'team',\n 'content',\n 'marketplace',\n 'support',\n 'system',\n 'staff',\n ].includes(prefix)\n ? prefix\n : 'system'\n ) as NotificationCategory\n}\n\n/**\n * Per-user mute map stored at `users/{uid}.notificationPrefs`\n * (`{ [category]: false }` mutes); absent categories stay on.\n */\nexport function notificationMuted(\n prefs: Record<string, boolean> | null | undefined,\n type: AglynNotificationType | string,\n): boolean {\n return prefs?.[notificationCategory(type)] === false\n}\n\n/**\n * The field on `users/{uid}` that holds a person's digest switches\n * (AGL-2619): `{ crmDaily: false }` turns the daily CRM digest off, and an\n * absent key leaves it on. Its own map rather than a key in\n * `notificationPrefs`, because that map is keyed by CATEGORY and read by\n * {@link notificationMuted} — a digest is a schedule a person keeps or\n * drops, not a bucket of types, and one switch governs both the console\n * notification and the email it travels with.\n */\nexport const DIGEST_PREFS_FIELD = 'digestPrefs'\n\n/**\n * The key the daily CRM digest keeps inside {@link DIGEST_PREFS_FIELD}.\n *\n * Exported so the console writes the switch through a name rather than a\n * second copy of the string (AGL-3230). The reader below and the page that\n * flips it were spelling the same literal in two files, which is how a\n * preference comes to be written under one key and read under another — and\n * it kept the plugin's vocabulary in a console page, where\n * `check:plugin-domain-in-core` rightly refuses it.\n */\nexport const CRM_DAILY_DIGEST_KEY = 'crmDaily'\n\nexport function crmDailyDigestEnabled(\n prefs: Record<string, boolean> | null | undefined,\n): boolean {\n return prefs?.[CRM_DAILY_DIGEST_KEY] !== false\n}\n\n/**\n * The field on `users/{uid}` naming the workspaces whose weekly insights a\n * person asked for (AGL-2915): `{ [orgId]: true }`. OPT-IN, unlike the CRM\n * digest — an absent key is off — because a weekly insight is generated, and a\n * generation spends the workspace's credits. The person turns it on beside the\n * answers themselves, where the plan, the release and their permission have\n * already been checked, and off again there or in Notifications; the weekly\n * sweep checks all three again before it spends anything.\n */\nexport const INSIGHT_DIGESTS_FIELD = 'insightDigests'\n\n/** Whether a person asked for a workspace's weekly insights. */\nexport function insightDigestSubscribed(\n value: Record<string, boolean> | null | undefined,\n orgId: string,\n): boolean {\n return Boolean(orgId) && value?.[orgId] === true\n}\n\n/**\n * The channels a notification can travel on (AGL-3223).\n *\n * `console` is the feed at `/manage/notifications` and the app-bar dropdown\n * that reads it — the only channel that existed. `email` is the message the\n * fan-out sends beside that doc when the recipient asked for one.\n */\nexport type NotificationChannel = 'console' | 'email'\n\n/**\n * One scope's answer for one category. **Tri-state on purpose**: `true` and\n * `false` decide, and an ABSENT key inherits from the scope above.\n *\n * Inheritance is the whole reason this is a partial rather than a pair of\n * booleans. A person who wants form submissions from one busy site and not\n * from the other five has to be able to say that about the one site without\n * restating their answer for every other category at every other scope — and\n * a two-valued leaf cannot express \"I have not said\", so every override would\n * have to be written out in full and would then stop tracking the account\n * default it was never meant to detach from.\n */\nexport interface NotificationChannelPrefs {\n console?: boolean\n email?: boolean\n}\n\nexport type NotificationCategoryPrefs = Partial<\n Record<NotificationCategory, NotificationChannelPrefs>\n>\n\n/**\n * Per-scope, per-channel notification preferences (AGL-3223), stored at\n * `users/{uid}.notificationSettings`.\n *\n * Three layers, narrowest first when resolving: the SITE a notification\n * concerns, then the WORKSPACE, then the account. Anything none of them\n * answers falls to {@link NOTIFICATION_CHANNEL_DEFAULTS}.\n *\n * ON THE USER DOCUMENT, not on `orgs/{orgId}/members/{uid}`, and that is a\n * cost decision rather than a modelling preference. `notifyUsers` already\n * does exactly one `getAll` over the recipients' user docs to read their\n * category mutes, so every layer living here means per-site preferences are\n * read for free on the fan-out's hot path. The member row would add a read\n * per recipient per notification to answer a question the document already in\n * hand could have answered.\n */\nexport interface NotificationSettings {\n account?: NotificationCategoryPrefs\n /** Keyed by org id. */\n orgs?: Record<string, NotificationCategoryPrefs>\n /** Keyed by host id — a site's own answer, narrower than its workspace's. */\n hosts?: Record<string, NotificationCategoryPrefs>\n}\n\nexport const NOTIFICATION_SETTINGS_FIELD = 'notificationSettings'\n\n/**\n * What a category does when nobody has said otherwise.\n *\n * Console on, email OFF, everywhere. Email defaults off because the inbox is\n * not ours to fill: the product already sends transactional mail nobody opted\n * into — welcome, verification, invites, dunning, usage alerts — and every one\n * of those leaves on the same domain a customer's password reset depends on.\n * Turning a busy site's form submissions into mail by default would put that\n * domain's reputation behind traffic the recipient never asked for.\n *\n * Exhaustive `Record` deliberately: a new {@link NotificationCategory} is a\n * compile error here until somebody decides what it does by default, which is\n * the one question a new category must not be able to ship without answering.\n */\nexport const NOTIFICATION_CHANNEL_DEFAULTS: Record<\n NotificationCategory,\n Record<NotificationChannel, boolean>\n> = {\n billing: { console: true, email: false },\n team: { console: true, email: false },\n content: { console: true, email: false },\n marketplace: { console: true, email: false },\n support: { console: true, email: false },\n system: { console: true, email: false },\n // Console ON, because the complaint this answers is that staff never heard\n // about a sign-up at all; email off, like everything else, because that is\n // what the channel defaults to and a sign-up is not urgent enough to be the\n // exception that starts filling inboxes by default.\n staff: { console: true, email: false },\n}\n\n/**\n * The types that send their OWN email and must never be mailed again by the\n * generic channel (AGL-3224).\n *\n * Both digests compose a message the fan-out could not reproduce — a day's\n * owed tasks, a week's figures — and send it from their own route under their\n * own switch (`digestPrefs.crmDaily`, `insightDigests.{orgId}`). A recipient\n * who switches the `content` email channel on would otherwise receive the\n * digest twice: once as the digest, once as a one-line \"Daily CRM digest\"\n * notification saying that the digest happened.\n */\nexport const NOTIFICATION_SELF_SENT_EMAIL_TYPES: ReadonlySet<string> =\n new Set<AglynNotificationType>([\n 'content.crmDailyDigest',\n 'content.insightsDigest',\n ])\n\n/**\n * Whether a channel is on for one notification, at its own scope.\n *\n * Resolution order, first answer wins: the notification's SITE, its\n * WORKSPACE, the account, then {@link NOTIFICATION_CHANNEL_DEFAULTS}. A scope\n * that holds no entry for the category, or an entry with the channel key\n * absent, does not answer — see {@link NotificationChannelPrefs}.\n *\n * `legacyPrefs` is the flat `notificationPrefs` mute map this replaces\n * (AGL-267), and it sits BELOW the account layer rather than beside it.\n * Nothing migrates it: a person who never opens the new settings page keeps\n * being governed by the mutes they set years ago, and the first thing they do\n * set on the account layer overrides the old map for that category without\n * disturbing the rest of it. It answers for `console` only, because the map\n * predates there being a second channel and reading a console mute as an\n * email preference would be inventing an answer its author never gave.\n */\nexport function notificationChannelEnabled(\n settings: NotificationSettings | null | undefined,\n channel: NotificationChannel,\n type: AglynNotificationType | string,\n scope?: { orgId?: string | null; hostId?: string | null },\n legacyPrefs?: Record<string, boolean> | null,\n): boolean {\n const category = notificationCategory(type)\n const layers: Array<NotificationCategoryPrefs | undefined> = [\n scope?.hostId ? settings?.hosts?.[scope.hostId] : undefined,\n scope?.orgId ? settings?.orgs?.[scope.orgId] : undefined,\n settings?.account,\n ]\n for (const layer of layers) {\n const answer = layer?.[category]?.[channel]\n if (typeof answer === 'boolean') return answer\n }\n if (channel === 'console' && notificationMuted(legacyPrefs, type))\n return false\n return NOTIFICATION_CHANNEL_DEFAULTS[category][channel]\n}\n\n/**\n * What one scope says, with no inheritance applied — what the settings page\n * renders as Inherit / On / Off, and `undefined` is Inherit.\n *\n * `scope` names the layer directly rather than being derived from a\n * notification, because the page edits a layer whether or not anything has\n * ever arrived from it.\n */\nexport function notificationScopePref(\n settings: NotificationSettings | null | undefined,\n scope: { kind: 'account' } | { kind: 'org' | 'host'; id: string },\n category: NotificationCategory,\n channel: NotificationChannel,\n): boolean | undefined {\n const layer =\n scope.kind === 'account'\n ? settings?.account\n : scope.kind === 'org'\n ? settings?.orgs?.[scope.id]\n : settings?.hosts?.[scope.id]\n return layer?.[category]?.[channel]\n}\n\n/**\n * The scopes this person has said something different about — what the\n * settings page lists so an override is never somewhere you have to go\n * looking for.\n *\n * Returns ids, not names: the page holds the org and host rosters and this\n * module holds no lookups. An id with no name is still worth listing, because\n * a preference about a workspace somebody left is exactly the kind of\n * leftover that is invisible until it is listed.\n */\nexport function notificationOverriddenScopes(\n settings: NotificationSettings | null | undefined,\n): { orgIds: string[]; hostIds: string[] } {\n const named = (\n layers: Record<string, NotificationCategoryPrefs> | undefined,\n ) =>\n Object.entries(layers ?? {})\n .filter(([, prefs]) =>\n Object.values(prefs ?? {}).some((channels) =>\n Object.values(channels ?? {}).some(\n (value) => typeof value === 'boolean',\n ),\n ),\n )\n .map(([id]) => id)\n .sort()\n return { orgIds: named(settings?.orgs), hostIds: named(settings?.hosts) }\n}\n"],"names":["NOTIFICATION_TYPE_LABELS","NOTIFICATION_CATEGORY_LABELS","billing","team","content","marketplace","support","system","staff","STAFF_NOTIFICATION_CATEGORIES","Set","notificationCategory","type","prefix","String","split","includes","notificationMuted","prefs","DIGEST_PREFS_FIELD","CRM_DAILY_DIGEST_KEY","crmDailyDigestEnabled","INSIGHT_DIGESTS_FIELD","insightDigestSubscribed","value","orgId","Boolean","NOTIFICATION_SETTINGS_FIELD","NOTIFICATION_CHANNEL_DEFAULTS","console","email","NOTIFICATION_SELF_SENT_EMAIL_TYPES","notificationChannelEnabled","settings","channel","scope","legacyPrefs","category","layers","hostId","hosts","undefined","orgs","account","layer","answer","notificationScopePref","kind","id","notificationOverriddenScopes","named","Object","entries","filter","values","some","channels","map","sort","orgIds","hostIds"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GA6ND,OAAO,MAAMA,2BAAkE;IAC7E,mBAAmB;IACnB,yBAAyB;IACzB,gCAAgC;IAChC,iBAAiB;IACjB,eAAe;IACf,oBAAoB;IACpB,0BAA0B;IAC1B,0BAA0B;IAC1B,mBAAmB;IACnB,iBAAiB;IACjB,oBAAoB;IACpB,wBAAwB;IACxB,wBAAwB;IACxB,2BAA2B;IAC3B,wBAAwB;IACxB,0BAA0B;IAC1B,0BAA0B;IAC1B,sBAAsB;IAEtB,wBAAwB;IACxB,uBAAuB;IACvB,uBAAuB;IACvB,mCAAmC;IACnC,8BAA8B;IAC9B,qBAAqB;IACrB,8BAA8B;IAC9B,gCAAgC;IAChC,+BAA+B;IAC/B,4BAA4B;IAC5B,4BAA4B;IAC5B,kCAAkC;IAClC,8BAA8B;IAC9B,oCAAoC;IACpC,8BAA8B;IAC9B,sBAAsB;IACtB,oBAAoB;AACtB,EAAC;AAcD,OAAO,MAAMC,+BAGT;IACFC,SAAS;IACTC,MAAM;IACNC,SAAS;IACTC,aAAa;IACbC,SAAS;IACTC,QAAQ;IACRC,OAAO;AACT,EAAC;AAED;;;;;;;CAOC,GACD,OAAO,MAAMC,gCACX,IAAIC,IAA0B;IAAC;CAAQ,EAAC;AAE1C,OAAO,SAASC,qBACdC,IAAoC;IAEpC,MAAMC,SAASC,OAAOF,MAAMG,KAAK,CAAC,IAAI,CAAC,EAAE;IACzC,OACE;QACE;QACA;QACA;QACA;QACA;QACA;QACA;KACD,CAACC,QAAQ,CAACH,UACPA,SACA;AAER;AAEA;;;CAGC,GACD,OAAO,SAASI,kBACdC,KA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MAAM,CAACpC,gBAAAA,QAAS,CAAC,GAAGqC,IAAI,CAAC,CAACC,WAC/BL,OAAOG,MAAM,CAACE,mBAAAA,WAAY,CAAC,GAAGD,IAAI,CAChC,CAAC/B,QAAU,OAAOA,UAAU,aAIjCiC,GAAG,CAAC,CAAC,CAACT,GAAG,GAAKA,IACdU,IAAI;IACT,OAAO;QAAEC,QAAQT,MAAMjB,4BAAAA,SAAUS,IAAI;QAAGkB,SAASV,MAAMjB,4BAAAA,SAAUO,KAAK;IAAE;AAC1E"}
@@ -36,6 +36,13 @@ export interface PluginPermission {
36
36
  viewer: boolean;
37
37
  };
38
38
  }
39
+ /** Calls `listener` after every registration; answers the unsubscribe. */
40
+ export declare function subscribePluginPermissions(listener: () => void): () => void;
41
+ /**
42
+ * A number that changes whenever the registry does — the snapshot for a
43
+ * `useSyncExternalStore` over `subscribePluginPermissions`.
44
+ */
45
+ export declare function pluginPermissionsVersion(): number;
39
46
  /**
40
47
  * Idempotent per key FOR ITS OWNER — the declaring plugin may re-register
41
48
  * (hot reload, a second surface, a repeated init) and its entry is replaced.
@@ -22,6 +22,35 @@
22
22
  * with zero app changes. Register at module scope from both the client
23
23
  * barrel and the /server entry (the AGL-428 pattern).
24
24
  */ const pluginPermissions = new Map();
25
+ /*
26
+ * Whoever resolved a permission map before a plugin registered holds a map
27
+ * without that plugin's keys, and a key that is absent reads as refused
28
+ * (AGL-3228). The console's permission provider resolved its map when the
29
+ * member document arrived; on a cold load of a plugin's deep link the
30
+ * plugin's chunk can register AFTER that, so the owner was refused a surface
31
+ * they hold by default until the next full render. So registration is
32
+ * observable, the way `subscribePluginEntitlements` makes the org catalog's
33
+ * registrations observable, and the provider re-reads on every change.
34
+ */ let registrationVersion = 0;
35
+ const listeners = new Set();
36
+ /** Calls `listener` after every registration; answers the unsubscribe. */ export function subscribePluginPermissions(listener) {
37
+ listeners.add(listener);
38
+ return ()=>{
39
+ listeners.delete(listener);
40
+ };
41
+ }
42
+ /**
43
+ * A number that changes whenever the registry does — the snapshot for a
44
+ * `useSyncExternalStore` over `subscribePluginPermissions`.
45
+ */ export function pluginPermissionsVersion() {
46
+ return registrationVersion;
47
+ }
48
+ function notifyListeners() {
49
+ registrationVersion += 1;
50
+ for (const listener of [
51
+ ...listeners
52
+ ])listener();
53
+ }
25
54
  /**
26
55
  * Idempotent per key FOR ITS OWNER — the declaring plugin may re-register
27
56
  * (hot reload, a second surface, a repeated init) and its entry is replaced.
@@ -47,6 +76,7 @@
47
76
  }
48
77
  pluginPermissions.set(permission.key, permission);
49
78
  }
79
+ notifyListeners();
50
80
  }
51
81
  export function listPluginPermissions() {
52
82
  return [
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/plugin-manager/plugin-permissions.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Plugin-declared permissions (AGL-435, Strapi RBAC-actions parity): a\n * plugin contributes NAMED permission keys with per-role-tier defaults.\n * `resolveRolePermissions` spreads them into every resolved set (custom\n * roles override key-by-key exactly like built-in keys), so\n * `ConsolePluginPageProps.permissions` and API-side resolution carry them\n * with zero app changes. Register at module scope from both the client\n * barrel and the /server entry (the AGL-428 pattern).\n */\n\nexport interface PluginPermission {\n /** Stable key ('managePos') — persisted in custom role docs. */\n key: string\n pluginId: string\n label: string\n description?: string\n /** Verdict per built-in role tier when a role doesn't name the key. */\n defaults: { admin: boolean; editor: boolean; viewer: boolean }\n}\n\nconst pluginPermissions = new Map<string, PluginPermission>()\n\n/**\n * Idempotent per key FOR ITS OWNER — the declaring plugin may re-register\n * (hot reload, a second surface, a repeated init) and its entry is replaced.\n *\n * A key already declared by a DIFFERENT plugin is refused (AGL-2484). This\n * map keyed on `permission.key` alone, so a later registration could redeclare\n * someone else's key with its own tier defaults — and these defaults are not\n * cosmetic: `managePos` is enforced server-side in\n * `libs/plugins/commerce/src/lib/server/pos-order.ts`, so moving\n * `defaults.viewer` to `true` hands a viewer the register. Reaching this\n * needs `PLUGIN_REMOTE_SERVER=enabled` (off by default), realm trust and a\n * signature; the registry closing its own door is the cheap part of that\n * stack.\n *\n * Per KEY, not per batch: a bundle that collides on one key still gets the\n * keys that are genuinely its own.\n */\nexport function registerPluginPermissions(\n permissions: readonly PluginPermission[],\n): void {\n for (const permission of permissions) {\n const incumbent = pluginPermissions.get(permission.key)\n if (incumbent !== undefined && incumbent.pluginId !== permission.pluginId) {\n console.error(\n `[plugins] refused permission key \"${permission.key}\" to ` +\n `\"${permission.pluginId}\": already declared by ` +\n `\"${incumbent.pluginId}\"`,\n )\n continue\n }\n pluginPermissions.set(permission.key, permission)\n }\n}\n\nexport function listPluginPermissions(): PluginPermission[] {\n return [...pluginPermissions.values()]\n}\n\n/**\n * The registered keys alone (AGL-2474). `resolveRolePermissions` needs the\n * grantable key SPACE, not the tier verdicts: it used to iterate\n * `ORG_ROLE_PERMISSION_KEYS` — the legacy six — when applying overrides and\n * custom roles, so a plugin-declared key materialised into the resolved map\n * and could then only ever hold its tier default. Read live rather than\n * snapshotted: registration happens at plugin module scope, which can run\n * after any module-level constant here has already been evaluated.\n */\nexport function listPluginPermissionKeys(): string[] {\n return [...pluginPermissions.keys()]\n}\n\n/** Tier defaults for every registered plugin permission. */\nexport function pluginPermissionDefaults(\n tier: 'admin' | 'editor' | 'viewer',\n): Record<string, boolean> {\n const defaults: Record<string, boolean> = {}\n for (const permission of pluginPermissions.values()) {\n defaults[permission.key] = permission.defaults[tier]\n }\n return defaults\n}\n"],"names":["pluginPermissions","Map","registerPluginPermissions","permissions","permission","incumbent","get","key","undefined","pluginId","console","error","set","listPluginPermissions","values","listPluginPermissionKeys","keys","pluginPermissionDefaults","tier","defaults"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAYD,MAAMA,oBAAoB,IAAIC;AAE9B;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASC,0BACdC,WAAwC;IAExC,KAAK,MAAMC,cAAcD,YAAa;QACpC,MAAME,YAAYL,kBAAkBM,GAAG,CAACF,WAAWG,GAAG;QACtD,IAAIF,cAAcG,aAAaH,UAAUI,QAAQ,KAAKL,WAAWK,QAAQ,EAAE;YACzEC,QAAQC,KAAK,CACX,CAAC,kCAAkC,EAAEP,WAAWG,GAAG,CAAC,KAAK,CAAC,GACxD,CAAC,CAAC,EAAEH,WAAWK,QAAQ,CAAC,uBAAuB,CAAC,GAChD,CAAC,CAAC,EAAEJ,UAAUI,QAAQ,CAAC,CAAC,CAAC;YAE7B;QACF;QACAT,kBAAkBY,GAAG,CAACR,WAAWG,GAAG,EAAEH;IACxC;AACF;AAEA,OAAO,SAASS;IACd,OAAO;WAAIb,kBAAkBc,MAAM;KAAG;AACxC;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC;IACd,OAAO;WAAIf,kBAAkBgB,IAAI;KAAG;AACtC;AAEA,0DAA0D,GAC1D,OAAO,SAASC,yBACdC,IAAmC;IAEnC,MAAMC,WAAoC,CAAC;IAC3C,KAAK,MAAMf,cAAcJ,kBAAkBc,MAAM,GAAI;QACnDK,QAAQ,CAACf,WAAWG,GAAG,CAAC,GAAGH,WAAWe,QAAQ,CAACD,KAAK;IACtD;IACA,OAAOC;AACT"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/plugin-manager/plugin-permissions.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Plugin-declared permissions (AGL-435, Strapi RBAC-actions parity): a\n * plugin contributes NAMED permission keys with per-role-tier defaults.\n * `resolveRolePermissions` spreads them into every resolved set (custom\n * roles override key-by-key exactly like built-in keys), so\n * `ConsolePluginPageProps.permissions` and API-side resolution carry them\n * with zero app changes. Register at module scope from both the client\n * barrel and the /server entry (the AGL-428 pattern).\n */\n\nexport interface PluginPermission {\n /** Stable key ('managePos') — persisted in custom role docs. */\n key: string\n pluginId: string\n label: string\n description?: string\n /** Verdict per built-in role tier when a role doesn't name the key. */\n defaults: { admin: boolean; editor: boolean; viewer: boolean }\n}\n\nconst pluginPermissions = new Map<string, PluginPermission>()\n\n/*\n * Whoever resolved a permission map before a plugin registered holds a map\n * without that plugin's keys, and a key that is absent reads as refused\n * (AGL-3228). The console's permission provider resolved its map when the\n * member document arrived; on a cold load of a plugin's deep link the\n * plugin's chunk can register AFTER that, so the owner was refused a surface\n * they hold by default until the next full render. So registration is\n * observable, the way `subscribePluginEntitlements` makes the org catalog's\n * registrations observable, and the provider re-reads on every change.\n */\nlet registrationVersion = 0\nconst listeners = new Set<() => void>()\n\n/** Calls `listener` after every registration; answers the unsubscribe. */\nexport function subscribePluginPermissions(listener: () => void): () => void {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n}\n\n/**\n * A number that changes whenever the registry does — the snapshot for a\n * `useSyncExternalStore` over `subscribePluginPermissions`.\n */\nexport function pluginPermissionsVersion(): number {\n return registrationVersion\n}\n\nfunction notifyListeners(): void {\n registrationVersion += 1\n for (const listener of [...listeners]) listener()\n}\n\n/**\n * Idempotent per key FOR ITS OWNER — the declaring plugin may re-register\n * (hot reload, a second surface, a repeated init) and its entry is replaced.\n *\n * A key already declared by a DIFFERENT plugin is refused (AGL-2484). This\n * map keyed on `permission.key` alone, so a later registration could redeclare\n * someone else's key with its own tier defaults — and these defaults are not\n * cosmetic: `managePos` is enforced server-side in\n * `libs/plugins/commerce/src/lib/server/pos-order.ts`, so moving\n * `defaults.viewer` to `true` hands a viewer the register. Reaching this\n * needs `PLUGIN_REMOTE_SERVER=enabled` (off by default), realm trust and a\n * signature; the registry closing its own door is the cheap part of that\n * stack.\n *\n * Per KEY, not per batch: a bundle that collides on one key still gets the\n * keys that are genuinely its own.\n */\nexport function registerPluginPermissions(\n permissions: readonly PluginPermission[],\n): void {\n for (const permission of permissions) {\n const incumbent = pluginPermissions.get(permission.key)\n if (incumbent !== undefined && incumbent.pluginId !== permission.pluginId) {\n console.error(\n `[plugins] refused permission key \"${permission.key}\" to ` +\n `\"${permission.pluginId}\": already declared by ` +\n `\"${incumbent.pluginId}\"`,\n )\n continue\n }\n pluginPermissions.set(permission.key, permission)\n }\n notifyListeners()\n}\n\nexport function listPluginPermissions(): PluginPermission[] {\n return [...pluginPermissions.values()]\n}\n\n/**\n * The registered keys alone (AGL-2474). `resolveRolePermissions` needs the\n * grantable key SPACE, not the tier verdicts: it used to iterate\n * `ORG_ROLE_PERMISSION_KEYS` — the legacy six — when applying overrides and\n * custom roles, so a plugin-declared key materialised into the resolved map\n * and could then only ever hold its tier default. Read live rather than\n * snapshotted: registration happens at plugin module scope, which can run\n * after any module-level constant here has already been evaluated.\n */\nexport function listPluginPermissionKeys(): string[] {\n return [...pluginPermissions.keys()]\n}\n\n/** Tier defaults for every registered plugin permission. */\nexport function pluginPermissionDefaults(\n tier: 'admin' | 'editor' | 'viewer',\n): Record<string, boolean> {\n const defaults: Record<string, boolean> = {}\n for (const permission of pluginPermissions.values()) {\n defaults[permission.key] = permission.defaults[tier]\n }\n return defaults\n}\n"],"names":["pluginPermissions","Map","registrationVersion","listeners","Set","subscribePluginPermissions","listener","add","delete","pluginPermissionsVersion","notifyListeners","registerPluginPermissions","permissions","permission","incumbent","get","key","undefined","pluginId","console","error","set","listPluginPermissions","values","listPluginPermissionKeys","keys","pluginPermissionDefaults","tier","defaults"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAYD,MAAMA,oBAAoB,IAAIC;AAE9B;;;;;;;;;CASC,GACD,IAAIC,sBAAsB;AAC1B,MAAMC,YAAY,IAAIC;AAEtB,wEAAwE,GACxE,OAAO,SAASC,2BAA2BC,QAAoB;IAC7DH,UAAUI,GAAG,CAACD;IACd,OAAO;QACLH,UAAUK,MAAM,CAACF;IACnB;AACF;AAEA;;;CAGC,GACD,OAAO,SAASG;IACd,OAAOP;AACT;AAEA,SAASQ;IACPR,uBAAuB;IACvB,KAAK,MAAMI,YAAY;WAAIH;KAAU,CAAEG;AACzC;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASK,0BACdC,WAAwC;IAExC,KAAK,MAAMC,cAAcD,YAAa;QACpC,MAAME,YAAYd,kBAAkBe,GAAG,CAACF,WAAWG,GAAG;QACtD,IAAIF,cAAcG,aAAaH,UAAUI,QAAQ,KAAKL,WAAWK,QAAQ,EAAE;YACzEC,QAAQC,KAAK,CACX,CAAC,kCAAkC,EAAEP,WAAWG,GAAG,CAAC,KAAK,CAAC,GACxD,CAAC,CAAC,EAAEH,WAAWK,QAAQ,CAAC,uBAAuB,CAAC,GAChD,CAAC,CAAC,EAAEJ,UAAUI,QAAQ,CAAC,CAAC,CAAC;YAE7B;QACF;QACAlB,kBAAkBqB,GAAG,CAACR,WAAWG,GAAG,EAAEH;IACxC;IACAH;AACF;AAEA,OAAO,SAASY;IACd,OAAO;WAAItB,kBAAkBuB,MAAM;KAAG;AACxC;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC;IACd,OAAO;WAAIxB,kBAAkByB,IAAI;KAAG;AACtC;AAEA,0DAA0D,GAC1D,OAAO,SAASC,yBACdC,IAAmC;IAEnC,MAAMC,WAAoC,CAAC;IAC3C,KAAK,MAAMf,cAAcb,kBAAkBuB,MAAM,GAAI;QACnDK,QAAQ,CAACf,WAAWG,GAAG,CAAC,GAAGH,WAAWe,QAAQ,CAACD,KAAK;IACtD;IACA,OAAOC;AACT"}
@@ -0,0 +1,51 @@
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
+ export interface PluginTrustSignature {
18
+ /** Base64 Ed25519 signature over the sha256 hex. Absent unless `signed`. */
19
+ signature?: string;
20
+ /**
21
+ * Whether a signature was produced. FALSE when nothing is registered, the
22
+ * deployment holds no key, or signing failed — and a caller must refuse
23
+ * the grant, never write one without a signature.
24
+ */
25
+ signed: boolean;
26
+ /** Why not, in the operator's terms, when `signed` is false. */
27
+ reason?: string;
28
+ }
29
+ export interface PluginTrustSigner {
30
+ /** Signs a version's sha256 hex with the platform's Ed25519 key. */
31
+ sign(sha256: string): Promise<PluginTrustSignature>;
32
+ }
33
+ /**
34
+ * One implementation: the app that holds the key. A second would be a second
35
+ * signing authority, and the loaders verify against ONE public key.
36
+ */
37
+ export declare const PLUGIN_TRUST_SIGNER: import("./plugin-services").PluginServiceContract<PluginTrustSigner>;
38
+ /** Installs the app's signer. Called once, at server boot. */
39
+ export declare function registerPluginTrustSigner(signer: PluginTrustSigner, options?: {
40
+ pluginId?: string;
41
+ }): void;
42
+ /** Whether this deployment can sign at all — for a surface that says so. */
43
+ export declare function hasPluginTrustSigner(): boolean;
44
+ /**
45
+ * Signs `sha256`, or says why it could not.
46
+ *
47
+ * NEVER THROWS, and never answers a signature it did not make. Read
48
+ * `signed` before reading `signature`; see the module docblock for why a
49
+ * caller must refuse rather than continue.
50
+ */
51
+ export declare function signPluginTrust(sha256: string): Promise<PluginTrustSignature>;
@@ -0,0 +1,119 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ /**
18
+ * WHO HOLDS THE PLATFORM'S TRUST KEY (AGL-3080).
19
+ *
20
+ * Realm trust is the strongest grant in the platform: it drops a marketplace
21
+ * bundle into the app realm, where neither the sandbox iframe nor the
22
+ * manifest CSP stands between it and user data. A grant is an Ed25519
23
+ * signature, made with `PLUGIN_TRUST_PRIVATE_KEY`, over the reviewed
24
+ * version's sha256 — and every loader verifies it before a byte executes.
25
+ *
26
+ * ## Why this is a seam rather than a move
27
+ *
28
+ * The queue around it is the MARKETPLACE's: `marketplaceListings` is its
29
+ * collection, "a version must have passed review" is its rule, and the
30
+ * fields the grant writes are its documents. All of that belongs with the
31
+ * plugin, the way the review queue and the report queue already do.
32
+ *
33
+ * The KEY does not. It is deployed to the console and nowhere else — never
34
+ * to a tenant runtime — and this package is published to npm, where a
35
+ * self-hoster generates their own pair. A plugin that read the key directly
36
+ * would put the platform's signing authority inside a package anyone can
37
+ * install, to no benefit: the plugin has nothing to do with it beyond
38
+ * wanting one string signed.
39
+ *
40
+ * So the shell signs, and the marketplace decides what is worth signing.
41
+ * The sibling of `core.site-cache`, and the same direction: the shell
42
+ * offering a capability down.
43
+ *
44
+ * ## ⛔ AN ABSENT SIGNER REFUSES. IT DOES NOT GRANT.
45
+ *
46
+ * This is the opposite failure direction from every other contract here, and
47
+ * it is the one that matters. `core.site-cache` answers `complete: false`
48
+ * and the caller carries on, because a stale cache is survivable. An
49
+ * unsigned realm grant is not survivable: the loaders fail closed on a
50
+ * missing signature, so a "grant" without one produces a version that is
51
+ * marked trusted and cannot load — or, far worse if a loader is ever
52
+ * lenient, one that loads unverified.
53
+ *
54
+ * {@link signPluginTrust} therefore never returns a bare string. It answers
55
+ * `{ signed: false, reason }` when nothing is registered, when the
56
+ * deployment has no key, or when signing throws, and the caller MUST refuse
57
+ * the grant on it rather than writing a partial one.
58
+ */ import { definePluginServiceContract, registerPluginService, resolvePluginService } from "./plugin-services.js";
59
+ /**
60
+ * One implementation: the app that holds the key. A second would be a second
61
+ * signing authority, and the loaders verify against ONE public key.
62
+ */ export const PLUGIN_TRUST_SIGNER = definePluginServiceContract('core.plugin-trust-signer', {
63
+ multiple: false
64
+ });
65
+ /** Installs the app's signer. Called once, at server boot. */ export function registerPluginTrustSigner(signer, options) {
66
+ if (typeof (signer == null ? void 0 : signer.sign) !== 'function') {
67
+ throw new Error('a plugin trust signer needs a sign function');
68
+ }
69
+ registerPluginService(PLUGIN_TRUST_SIGNER, signer, _extends({}, (options == null ? void 0 : options.pluginId) ? {
70
+ pluginId: options.pluginId
71
+ } : {}));
72
+ }
73
+ /** Whether this deployment can sign at all — for a surface that says so. */ export function hasPluginTrustSigner() {
74
+ return Boolean(resolvePluginService(PLUGIN_TRUST_SIGNER));
75
+ }
76
+ /**
77
+ * Signs `sha256`, or says why it could not.
78
+ *
79
+ * NEVER THROWS, and never answers a signature it did not make. Read
80
+ * `signed` before reading `signature`; see the module docblock for why a
81
+ * caller must refuse rather than continue.
82
+ */ export async function signPluginTrust(sha256) {
83
+ const digest = sha256 == null ? void 0 : sha256.trim();
84
+ if (!digest) {
85
+ return {
86
+ signed: false,
87
+ reason: 'No version hash to sign.'
88
+ };
89
+ }
90
+ const signer = resolvePluginService(PLUGIN_TRUST_SIGNER);
91
+ if (!signer) {
92
+ console.error('[trust-signer] no implementation is installed, so realm trust cannot ' + 'be granted. The app registers this at boot.');
93
+ return {
94
+ signed: false,
95
+ reason: 'Trust signing is not available on this deployment.'
96
+ };
97
+ }
98
+ try {
99
+ const result = await signer.sign(digest);
100
+ // A signer that answered `signed` with nothing to show is a bug in the
101
+ // signer, and granting on it would write the trust flag with no
102
+ // signature — the one state the loaders cannot distinguish from tampering.
103
+ if (result.signed && !result.signature) {
104
+ return {
105
+ signed: false,
106
+ reason: 'Trust signing returned no signature.'
107
+ };
108
+ }
109
+ return result;
110
+ } catch (error) {
111
+ console.error('[trust-signer] signing failed', error);
112
+ return {
113
+ signed: false,
114
+ reason: 'Trust signing failed.'
115
+ };
116
+ }
117
+ }
118
+
119
+ //# sourceMappingURL=plugin-trust-signing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/plugin-manager/plugin-trust-signing.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * WHO HOLDS THE PLATFORM'S TRUST KEY (AGL-3080).\n *\n * Realm trust is the strongest grant in the platform: it drops a marketplace\n * bundle into the app realm, where neither the sandbox iframe nor the\n * manifest CSP stands between it and user data. A grant is an Ed25519\n * signature, made with `PLUGIN_TRUST_PRIVATE_KEY`, over the reviewed\n * version's sha256 — and every loader verifies it before a byte executes.\n *\n * ## Why this is a seam rather than a move\n *\n * The queue around it is the MARKETPLACE's: `marketplaceListings` is its\n * collection, \"a version must have passed review\" is its rule, and the\n * fields the grant writes are its documents. All of that belongs with the\n * plugin, the way the review queue and the report queue already do.\n *\n * The KEY does not. It is deployed to the console and nowhere else — never\n * to a tenant runtime — and this package is published to npm, where a\n * self-hoster generates their own pair. A plugin that read the key directly\n * would put the platform's signing authority inside a package anyone can\n * install, to no benefit: the plugin has nothing to do with it beyond\n * wanting one string signed.\n *\n * So the shell signs, and the marketplace decides what is worth signing.\n * The sibling of `core.site-cache`, and the same direction: the shell\n * offering a capability down.\n *\n * ## ⛔ AN ABSENT SIGNER REFUSES. IT DOES NOT GRANT.\n *\n * This is the opposite failure direction from every other contract here, and\n * it is the one that matters. `core.site-cache` answers `complete: false`\n * and the caller carries on, because a stale cache is survivable. An\n * unsigned realm grant is not survivable: the loaders fail closed on a\n * missing signature, so a \"grant\" without one produces a version that is\n * marked trusted and cannot load — or, far worse if a loader is ever\n * lenient, one that loads unverified.\n *\n * {@link signPluginTrust} therefore never returns a bare string. It answers\n * `{ signed: false, reason }` when nothing is registered, when the\n * deployment has no key, or when signing throws, and the caller MUST refuse\n * the grant on it rather than writing a partial one.\n */\n\nimport {\n definePluginServiceContract,\n registerPluginService,\n resolvePluginService,\n} from './plugin-services'\n\nexport interface PluginTrustSignature {\n /** Base64 Ed25519 signature over the sha256 hex. Absent unless `signed`. */\n signature?: string\n /**\n * Whether a signature was produced. FALSE when nothing is registered, the\n * deployment holds no key, or signing failed — and a caller must refuse\n * the grant, never write one without a signature.\n */\n signed: boolean\n /** Why not, in the operator's terms, when `signed` is false. */\n reason?: string\n}\n\nexport interface PluginTrustSigner {\n /** Signs a version's sha256 hex with the platform's Ed25519 key. */\n sign(sha256: string): Promise<PluginTrustSignature>\n}\n\n/**\n * One implementation: the app that holds the key. A second would be a second\n * signing authority, and the loaders verify against ONE public key.\n */\nexport const PLUGIN_TRUST_SIGNER =\n definePluginServiceContract<PluginTrustSigner>('core.plugin-trust-signer', {\n multiple: false,\n })\n\n/** Installs the app's signer. Called once, at server boot. */\nexport function registerPluginTrustSigner(\n signer: PluginTrustSigner,\n options?: { pluginId?: string },\n): void {\n if (typeof signer?.sign !== 'function') {\n throw new Error('a plugin trust signer needs a sign function')\n }\n registerPluginService(PLUGIN_TRUST_SIGNER, signer, {\n ...(options?.pluginId ? { pluginId: options.pluginId } : {}),\n })\n}\n\n/** Whether this deployment can sign at all — for a surface that says so. */\nexport function hasPluginTrustSigner(): boolean {\n return Boolean(resolvePluginService(PLUGIN_TRUST_SIGNER))\n}\n\n/**\n * Signs `sha256`, or says why it could not.\n *\n * NEVER THROWS, and never answers a signature it did not make. Read\n * `signed` before reading `signature`; see the module docblock for why a\n * caller must refuse rather than continue.\n */\nexport async function signPluginTrust(\n sha256: string,\n): Promise<PluginTrustSignature> {\n const digest = sha256?.trim()\n if (!digest) {\n return { signed: false, reason: 'No version hash to sign.' }\n }\n const signer = resolvePluginService(PLUGIN_TRUST_SIGNER)\n if (!signer) {\n console.error(\n '[trust-signer] no implementation is installed, so realm trust cannot ' +\n 'be granted. The app registers this at boot.',\n )\n return {\n signed: false,\n reason: 'Trust signing is not available on this deployment.',\n }\n }\n try {\n const result = await signer.sign(digest)\n // A signer that answered `signed` with nothing to show is a bug in the\n // signer, and granting on it would write the trust flag with no\n // signature — the one state the loaders cannot distinguish from tampering.\n if (result.signed && !result.signature) {\n return {\n signed: false,\n reason: 'Trust signing returned no signature.',\n }\n }\n return result\n } catch (error) {\n console.error('[trust-signer] signing failed', error)\n return { signed: false, reason: 'Trust signing failed.' }\n }\n}\n"],"names":["definePluginServiceContract","registerPluginService","resolvePluginService","PLUGIN_TRUST_SIGNER","multiple","registerPluginTrustSigner","signer","options","sign","Error","pluginId","hasPluginTrustSigner","Boolean","signPluginTrust","sha256","digest","trim","signed","reason","console","error","result","signature"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,GAED,SACEA,2BAA2B,EAC3BC,qBAAqB,EACrBC,oBA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