@aglyn/tenant-data-admin 1.0.0-beta.292 → 1.0.0-beta.293

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.0.0-beta.292",
3
+ "version": "1.0.0-beta.293",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.292",
29
- "@aglyn/shared-util-email": "1.0.0-beta.292",
30
- "@aglyn/shared-util-fbserver": "1.0.0-beta.292",
31
- "@aglyn/shared-util-first-touch": "1.0.0-beta.292",
32
- "@aglyn/shared-util-http": "1.0.0-beta.292",
33
- "@aglyn/shared-util-tools": "1.0.0-beta.292",
28
+ "@aglyn/aglyn": "1.0.0-beta.293",
29
+ "@aglyn/shared-util-email": "1.0.0-beta.293",
30
+ "@aglyn/shared-util-fbserver": "1.0.0-beta.293",
31
+ "@aglyn/shared-util-first-touch": "1.0.0-beta.293",
32
+ "@aglyn/shared-util-http": "1.0.0-beta.293",
33
+ "@aglyn/shared-util-tools": "1.0.0-beta.293",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -19,7 +19,7 @@ import { operatorAlertForNotificationType } from "@aglyn/aglyn/plugin-manager/op
19
19
  import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
20
20
  import { notificationPushEnabled } from "@aglyn/aglyn/app-utils/notification-push";
21
21
  import { NOTIFICATION_SOUND_FIELD, notificationSound } from "@aglyn/aglyn/app-utils/notification-sounds";
22
- import { notificationEmailAction } from "@aglyn/aglyn/app-utils/notifications";
22
+ import { notificationEmailAction, notificationLabel } from "@aglyn/aglyn/app-utils/notifications";
23
23
  import { PLATFORM_BRANDING_PROFILE, platformConsoleOrigin } from "@aglyn/aglyn/app-utils/platform-brand";
24
24
  import { FieldValue } from "firebase-admin/firestore";
25
25
  import { withoutMailWithheldAccounts } from "./account-mail.js";
@@ -80,7 +80,7 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
80
80
  *
81
81
  * Never throws, like everything else on this path.
82
82
  */ async function emailNotification(uids, payload, known, audience, emailDetails, replyTo) {
83
- var _payload_body;
83
+ var _context_line, _payload_body;
84
84
  /*
85
85
  * `platformConsoleOrigin`, never `NEXT_PUBLIC_CONSOLE_URL` read bare: this
86
86
  * runs in the site app as well as the console, and the site app's
@@ -92,6 +92,13 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
92
92
  const context = await notificationEmailContext(payload, audience);
93
93
  const url = notificationEmailUrl(payload, context, origin);
94
94
  const details = formatNotificationEmailDetails(emailDetails);
95
+ // The eyebrow names what this is before where (AGL-4096), "Proof approved ·
96
+ // Copper Kettle · Acme", when the emitter gave the notification a label of
97
+ // its own; every other notification keeps the site and workspace alone.
98
+ const eyebrow = [
99
+ payload.label ? notificationLabel(payload) : '',
100
+ (_context_line = context.line) != null ? _context_line : ''
101
+ ].filter(Boolean).join(' · ');
95
102
  const loaded = await loadSystemEmail('notification').catch(()=>null);
96
103
  const fallbackText = [
97
104
  payload.title,
@@ -103,7 +110,7 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
103
110
  let lookups = 0;
104
111
  let sent = 0;
105
112
  for (const uid of uids){
106
- var _known_uid, _payload_body1, _context_line;
113
+ var _known_uid, _payload_body1;
107
114
  if (sent >= NOTIFY_EMAIL_MAX_SENDS) break;
108
115
  let address = String((_known_uid = known[uid]) != null ? _known_uid : '').trim().toLowerCase();
109
116
  if (!address.includes('@')) {
@@ -124,9 +131,9 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
124
131
  'notification.body': (_payload_body1 = payload.body) != null ? _payload_body1 : '',
125
132
  'notification.details': details,
126
133
  'notification.url': url,
127
- 'notification.context': (_context_line = context.line) != null ? _context_line : '',
134
+ 'notification.context': eyebrow,
128
135
  'notification.replyNote': replyTo ? `Reply to this email to answer ${replyTo}.` : '',
129
- 'notification.action': notificationEmailAction(payload.type, context.brand.merge['brand.productName'] || PLATFORM_BRANDING_PROFILE.productName),
136
+ 'notification.action': notificationEmailAction(payload.type, context.brand.merge['brand.productName'] || PLATFORM_BRANDING_PROFILE.productName, payload.actionLabel),
130
137
  settingsUrl
131
138
  }), context.brand.options) : null;
132
139
  const result = await sendEmail(_extends({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/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 {\n buildRoute,\n NOTIFICATION_SELF_SENT_EMAIL_TYPES,\n NOTIFICATION_SETTINGS_FIELD,\n normalizeNotificationLink,\n notificationChannelEnabled,\n type AglynNotification,\n Route,\n type NotificationSettings,\n} from '@aglyn/aglyn/server'\nimport { operatorAlertForNotificationType } from '@aglyn/aglyn/plugin-manager/operator-alerts'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { notificationPushEnabled } from '@aglyn/aglyn/app-utils/notification-push'\nimport { NOTIFICATION_SOUND_FIELD, notificationSound } from '@aglyn/aglyn/app-utils/notification-sounds'\nimport { notificationEmailAction } from '@aglyn/aglyn/app-utils/notifications'\nimport { PLATFORM_BRANDING_PROFILE, platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { withoutMailWithheldAccounts } from './account-mail'\nimport { findUserByUidAcrossPools, listStaffUidsAcrossPools } from './auth-pools'\nimport { filterSuppressedEmails } from './email-suppression'\nimport { meterOrgEmail, meterPlatformEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { keepAlive } from './keep-alive'\nimport { mobilePushEnabled, mobilePushSenders } from './mobile-push-switch'\nimport { listOrgMembers } from './organizations'\nimport {\n loadSystemEmail,\n renderLoadedSystemEmail,\n systemEmailBrand,\n systemEmailContent,\n type SystemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport type NotificationPayload = Omit<\n AglynNotification,\n '$id' | 'createdAt' | 'readAt'\n>\n\nexport interface NotifyUsersOptions {\n /**\n * Addresses the caller already holds, by uid (AGL-3224).\n *\n * Purely an optimization, and one worth taking where it is free: a caller\n * that read the roster — `notifyOrgAdmins` does — has every address in hand\n * already, and without this the email half would look each one up again in\n * the directory. Absent uids fall back to that lookup, so passing a partial\n * map is fine and passing none is correct.\n */\n emails?: Readonly<Record<string, string | null | undefined>>\n /**\n * Who the fan-out is for (AGL-3367). `staff` is the platform talking to its\n * own people, so the email wears the platform's brand and is the platform's\n * cost even when the notification is ABOUT an org, which a canceled\n * subscription or a new ticket always is. Anything else speaks in the org's\n * brand when the notification names one.\n */\n audience?: 'staff'\n /**\n * Write the console notification only, and mail nobody through the\n * per-person email channel (AGL-3375): the caller has emailed the same\n * alert to the operator's inbox, and a staff member who also switched\n * email on would otherwise get it twice.\n */\n skipEmail?: boolean\n /**\n * People not to mail through the email channel for this one notification,\n * because the caller emails them the same event itself — the seller's\n * designed sale email beside a Buy Now order's notification. Everyone else\n * the fan-out reaches is mailed as their preferences say.\n */\n skipEmailFor?: readonly string[]\n /**\n * Particulars the email carries and the notification does not: a form\n * submission's answers, so the person reading the email has the inquiry\n * without opening the console.\n *\n * Email only, never written to the notification document or pushed. The\n * document is copied once per recipient and outlives the record it points\n * at, and a push lands on a lock screen; the record itself stays the one\n * place the visitor's answers are kept.\n */\n emailDetails?: readonly NotificationEmailDetail[]\n /**\n * Who a reply to the email reaches (AGL-3897): the visitor who filled in a\n * form, so a manager answers an inquiry from the inbox it landed in. Never\n * set on a staff fan-out.\n */\n replyTo?: string\n}\n\n/** One labeled line of a notification email's details. */\nexport interface NotificationEmailDetail {\n label: string\n value: string\n}\n\n/**\n * At most this many characters of details per email. A submission is capped\n * at 2,000 characters a field, so a long form would otherwise be a long email.\n */\nconst NOTIFY_EMAIL_MAX_DETAILS_CHARS = 10_000\n\n/**\n * The details as the email prints them: `Label: value`, one per line, a\n * value's own line breaks kept and blank values left out.\n */\nexport function formatNotificationEmailDetails(\n details: readonly NotificationEmailDetail[] | undefined,\n): string {\n const text = (details ?? [])\n .map(({ label, value }) => ({ label: label.trim(), value: value.trim() }))\n .filter(({ value }) => value)\n .map(({ label, value }) => (label ? `${label}: ${value}` : value))\n .join('\\n')\n return text.length > NOTIFY_EMAIL_MAX_DETAILS_CHARS\n ? `${text.slice(0, NOTIFY_EMAIL_MAX_DETAILS_CHARS).trimEnd()}…`\n : text\n}\n\n/**\n * At most this many directory lookups per fan-out, and at most this many\n * notification emails.\n *\n * Both ceilings bite only on a fan-out where many recipients are emailed —\n * the email channel defaults off outside the types in\n * `NOTIFICATION_TYPE_CHANNEL_DEFAULTS`, and every fan-out goes to one\n * workspace's or one site's people, or to staff. They are here because a\n * fan-out takes up to 400 uids and `notifyUsers` runs inside the mutation\n * that emitted it: a notification must not be able to turn one write into\n * four hundred directory reads and four hundred sends.\n */\nconst NOTIFY_EMAIL_MAX_LOOKUPS = 25\nconst NOTIFY_EMAIL_MAX_SENDS = 50\n\n/**\n * The email beside the console notification (AGL-3224).\n *\n * One send per recipient, never a shared `to:` list — two people who manage\n * the same site have not agreed to be shown each other's addresses, and the\n * settings link in the footer belongs to one person.\n *\n * `List-Unsubscribe` points at the settings page rather than at a one-click\n * endpoint: this is not marketing mail and RFC 8058's POST form would be\n * claiming a capability that does not exist. What it does do is put the way\n * out in the headers as well as the body, so a client that surfaces it shows\n * the person the page where the switch they want actually is.\n *\n * Rendered through the `notification` system email (AGL-3367), which is what\n * gives it the header and footer every other system email wears, and makes\n * it designable on the staff System emails page. It used to hand `sendEmail`\n * bare text, which is the unbranded card the fallback HTML part draws. The\n * template is read once per fan-out and rendered per recipient.\n *\n * Never throws, like everything else on this path.\n */\nasync function emailNotification(\n uids: string[],\n payload: NotificationPayload,\n known: Readonly<Record<string, string | null | undefined>>,\n audience: NotifyUsersOptions['audience'],\n emailDetails: NotifyUsersOptions['emailDetails'],\n replyTo?: string,\n): Promise<void> {\n /*\n * `platformConsoleOrigin`, never `NEXT_PUBLIC_CONSOLE_URL` read bare: this\n * runs in the site app as well as the console, and the site app's\n * deployment does not set that variable. Read bare, a notification a site\n * sends (a form submission, an order) would carry a button that opens\n * nothing and a settings line with no address.\n */\n const origin = platformConsoleOrigin()\n const settingsUrl = `${origin}${buildRoute(Route.MANAGE_NOTIFICATION_SETTINGS)}`\n const context = await notificationEmailContext(payload, audience)\n const url = notificationEmailUrl(payload, context, origin)\n const details = formatNotificationEmailDetails(emailDetails)\n const loaded = await loadSystemEmail('notification').catch(() => null)\n const fallbackText = [\n payload.title,\n payload.body ?? '',\n details,\n url,\n `Change what you are emailed about: ${settingsUrl}`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n let lookups = 0\n let sent = 0\n for (const uid of uids) {\n if (sent >= NOTIFY_EMAIL_MAX_SENDS) break\n let address = String(known[uid] ?? '').trim().toLowerCase()\n if (!address.includes('@')) {\n if (lookups >= NOTIFY_EMAIL_MAX_LOOKUPS) continue\n lookups += 1\n const pooled = await findUserByUidAcrossPools(uid).catch(() => null)\n address = String(pooled?.record?.email ?? '').trim().toLowerCase()\n }\n if (!address.includes('@')) continue\n const recipients = await filterSuppressedEmails([address])\n if (!recipients.length) continue\n const rendered = loaded\n ? renderLoadedSystemEmail(\n loaded,\n {\n ...context.brand.merge,\n 'notification.title': payload.title,\n 'notification.body': payload.body ?? '',\n 'notification.details': details,\n 'notification.url': url,\n 'notification.context': context.line ?? '',\n 'notification.replyNote': replyTo ? `Reply to this email to answer ${replyTo}.` : '',\n 'notification.action': notificationEmailAction(\n payload.type,\n context.brand.merge['brand.productName'] || PLATFORM_BRANDING_PROFILE.productName,\n ),\n settingsUrl,\n },\n context.brand.options,\n )\n : null\n const result = await sendEmail({\n to: recipients,\n ...systemEmailContent(rendered, {\n subject: payload.title,\n text: fallbackText,\n }),\n ...(context.brand.fromName ? { fromName: context.brand.fromName } : {}),\n context: 'notification',\n ...(replyTo ? { replyTo } : {}),\n headers: { 'List-Unsubscribe': `<${settingsUrl}>` },\n })\n if (!result.sent) continue\n sent += 1\n // Whose cost it is: a notification to a workspace's people is that\n // workspace's mail, and a staff alert or an account-level notice is the\n // platform's, whichever org it is about.\n await (payload.orgId && audience !== 'staff'\n ? meterOrgEmail(payload.orgId)\n : meterPlatformEmail()\n ).catch(() => undefined)\n }\n}\n\n/** What a notification email needs from the org and site it is about. */\ninterface NotificationEmailContext {\n brand: SystemEmailBrand\n orgSlug?: string\n hostSubdomain?: string\n /**\n * What the notification is about, for the line above its heading\n * (AGL-3897): the site and the workspace, \"Copper Kettle Catering · Acme\",\n * or the workspace alone. A person in several workspaces otherwise gets\n * \"New order\" with nothing to say whose.\n */\n line?: string\n}\n\n/**\n * The org's brand, and the slug and subdomain its stored link is rewritten\n * with (AGL-3367): at most two reads per fan-out, made only when someone is\n * being emailed.\n *\n * A staff fan-out reads nothing. Its brand is the platform's, and its links\n * are staff routes that need no rewriting.\n */\nasync function notificationEmailContext(\n payload: NotificationPayload,\n audience: NotifyUsersOptions['audience'],\n): Promise<NotificationEmailContext> {\n if (audience === 'staff' || !payload.orgId) {\n return { brand: systemEmailBrand(null) }\n }\n try {\n const db = firestore()\n const [org, host] = await Promise.all([\n db.collection('orgs').doc(payload.orgId).get(),\n payload.hostId\n ? db.collection('hosts').doc(payload.hostId).get()\n : Promise.resolve(null),\n ])\n const slug = org.get('slug')\n const subdomain = host?.get('subdomain')\n const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '')\n const orgName = text(org.get('name'))\n const siteName = text(host?.get('displayName')) || text(host?.get('name')) || text(subdomain)\n const line = [siteName, orgName && orgName !== siteName ? orgName : ''].filter(Boolean).join(' · ')\n return {\n brand: systemEmailBrand(org.exists ? (org.data() ?? null) : null),\n ...(line ? { line } : {}),\n ...(typeof slug === 'string' && slug ? { orgSlug: slug } : {}),\n ...(typeof subdomain === 'string' && subdomain\n ? { hostSubdomain: subdomain }\n : {}),\n }\n } catch (error) {\n console.error('notification email context failed', error)\n return { brand: systemEmailBrand(null) }\n }\n}\n\n/**\n * Where the email's button goes: the notification's own link, rewritten onto\n * today's routes the way the console rewrites it when it is clicked, else\n * the notifications page. A stored host link is `/{hostDocId}/…`, which only\n * that rewrite turns into a page that exists.\n */\nfunction notificationEmailUrl(\n payload: NotificationPayload,\n context: NotificationEmailContext,\n origin: string,\n): string {\n const link = normalizeNotificationLink(payload.link, {\n orgSlug: context.orgSlug,\n hostId: payload.hostId,\n hostSubdomain: context.hostSubdomain,\n })\n if (link && /^https?:\\/\\//i.test(link)) return link\n return `${origin}${link?.startsWith('/') ? link : buildRoute(Route.MANAGE_NOTIFICATIONS)}`\n}\n\n/**\n * Notification fan-out (AGL-259): batch-writes one doc per recipient at\n * `users/{uid}/notifications`, and — for recipients who asked for it\n * (AGL-3224) — sends one email beside it. Never throws: a notification miss,\n * or a send that failed, must not break the mutation that emitted it.\n */\nasync function notifyUsersNow(\n uids: Iterable<string>,\n payload: NotificationPayload,\n options: NotifyUsersOptions = {},\n): Promise<void> {\n try {\n const db = firestore()\n const targets = [...new Set(uids)].filter(Boolean).slice(0, 400)\n if (!targets.length) return\n // Per-user preferences (AGL-267, AGL-3223): one getAll over the user\n // docs, which now answers for both channels and for all three scopes —\n // the settings live on this document precisely so that stays one read.\n const userDocs = await db.getAll(\n ...targets.map((uid) => db.collection('users').doc(uid)),\n )\n const scope = { orgId: payload.orgId, hostId: payload.hostId }\n const batch = db.batch()\n let count = 0\n const mailTo: string[] = []\n const pushTo: string[] = []\n const sounds: Record<string, string> = {}\n for (const userDoc of userDocs) {\n const settings = userDoc.get(NOTIFICATION_SETTINGS_FIELD) as\n | NotificationSettings\n | undefined\n const legacy = userDoc.get('notificationPrefs') as\n | Record<string, boolean>\n | undefined\n if (\n notificationChannelEnabled(\n settings,\n 'console',\n payload.type,\n scope,\n legacy,\n )\n ) {\n batch.set(\n db\n .collection('users')\n .doc(userDoc.id)\n .collection('notifications')\n .doc(),\n // `read: false` on create, so the feed can ask for unread and read\n // alike by equality (AGL-3321; see `AglynNotification.read`).\n { ...payload, read: false, createdAt: FieldValue.serverTimestamp() },\n )\n count += 1\n }\n // The mobile push channel (AGL-3620); unanswered, it follows the feed.\n if (notificationPushEnabled(settings, payload.type, scope, legacy)) {\n pushTo.push(userDoc.id)\n sounds[userDoc.id] = notificationSound(userDoc.get(NOTIFICATION_SOUND_FIELD)).id\n }\n if (\n notificationChannelEnabled(settings, 'email', payload.type, scope, legacy) &&\n !options.skipEmailFor?.includes(userDoc.id)\n ) {\n mailTo.push(userDoc.id)\n }\n }\n if (count > 0) await batch.commit()\n /*\n * The push after the commit for the same reason as the email below:\n * every registered transport is handed the recipients whose preferences\n * say push, unless the deployment has pulled the kill switch. A failing\n * transport is logged and never stops the email or another transport.\n */\n if (pushTo.length && mobilePushEnabled()) {\n for (const send of mobilePushSenders()) {\n try {\n await send(pushTo, payload, { db, sounds })\n } catch (error) {\n console.error('push delivery failed', error)\n }\n }\n }\n /*\n * THE EMAIL AFTER THE COMMIT, and not inside its `try`.\n *\n * The console notification is the durable record and the send is a\n * courtesy on top of it, so the order is the one where a failing network\n * call cannot lose the record. The two channels are independent by\n * design — a person may have muted the feed and asked for mail, or the\n * reverse — so neither is gated on the other having happened.\n *\n * Digests are excluded: they compose and send their own mail, under\n * their own switches, and the generic channel would send a second\n * message announcing that the first one had been sent.\n *\n * A locked or disabled account is not mailed (AGL-3418); its feed entry\n * above still records the event.\n */\n if (\n mailTo.length &&\n !options.skipEmail &&\n isEmailConfigured() &&\n !NOTIFICATION_SELF_SENT_EMAIL_TYPES.has(payload.type)\n ) {\n const reachable = await withoutMailWithheldAccounts(mailTo)\n if (!reachable.length) return\n await emailNotification(\n reachable,\n payload,\n options.emails ?? {},\n options.audience,\n options.emailDetails,\n options.audience === 'staff' ? undefined : options.replyTo,\n )\n }\n } catch (error) {\n console.error('notification fan-out failed', error)\n }\n}\n\n// Staff are identified by a Firebase Auth custom claim (`staff`), which is not\n// a Firestore query — so the roster comes from paginating the auth users. A\n// burst of ticket activity shouldn't rescan every time, so the (small) result\n// is cached briefly. Fails soft to an empty list.\nlet staffUidCache: { uids: string[]; at: number } | null = null\nconst STAFF_CACHE_MS = 60_000\n\nasync function listStaffUids(): Promise<string[]> {\n const now = Date.now()\n if (staffUidCache && now - staffUidCache.at < STAFF_CACHE_MS) {\n return staffUidCache.uids\n }\n // Across ALL auth pools (AGL-1122). This scanned only the project pool, so\n // a staff member who signs in through enterprise SSO — whose account lives\n // in a GCIP tenant pool — was never in the fan-out. Nothing errored; the\n // notification simply never arrived, which is the worst shape a miss can\n // take on an alerting path.\n const uids = await listStaffUidsAcrossPools()\n staffUidCache = { uids, at: now }\n return uids\n}\n\n/**\n * Notifies every staff-claim holder (AGL-850) — the support-desk audience.\n * Staff are not org members, so `notifyOrgAdmins`/`notifyHostManagers` never\n * reach them; this enumerates the `staff` custom claim instead. The docs land\n * at `users/{uid}/notifications`, which the console notifications menu already\n * renders, so no separate staff inbox is needed. Never throws.\n *\n * A type the operator alert registry names (AGL-3377) — a fraud or risk\n * alert, a dispute nobody owns, a support ticket — is raised as that alert\n * instead: the same console notification, plus staff's switches, the\n * operator email or digest, and the webhook. See `raiseOperatorAlert`.\n */\nasync function notifyStaffNow(\n payload: NotificationPayload,\n options: Pick<NotifyUsersOptions, 'emailDetails'> = {},\n): Promise<void> {\n try {\n const alert = operatorAlertForNotificationType(payload.type)\n if (alert) {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n await raiseOperatorAlert(alert, {\n subject: payload.title,\n ...(payload.body ? { body: payload.body } : {}),\n ...(payload.level ? { level: payload.level } : {}),\n ...(payload.link ? { url: payload.link } : {}),\n ...(payload.orgId ? { orgId: payload.orgId } : {}),\n ...(payload.hostId ? { hostId: payload.hostId } : {}),\n })\n return\n }\n await notifyStaffConsole(payload, options)\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * The staff console notification alone, with the per-person email channel\n * it carries: what `notifyStaff` did before the registry, and what\n * `raiseOperatorAlert` writes as its first step. Never throws.\n */\nasync function notifyStaffConsoleNow(\n payload: NotificationPayload,\n options: Pick<NotifyUsersOptions, 'skipEmail' | 'emailDetails'> = {},\n): Promise<void> {\n try {\n await notifyUsers(await listStaffUids(), payload, {\n audience: 'staff',\n ...(options.skipEmail ? { skipEmail: true } : {}),\n // What the email alone carries — a new account's acquisition, a new\n // site's workspace (AGL-3897) — beside the bell's one line.\n ...(options.emailDetails?.length ? { emailDetails: options.emailDetails } : {}),\n })\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * Notifies the org's owner + admins (billing, membership, org events).\n *\n * `skipEmail` is for a caller that emails the same notice to the same people\n * itself — the usage alerts do (AGL-3431) — so an admin who switched the\n * email channel on is not sent it twice.\n */\nasync function notifyOrgAdminsNow(\n orgId: string,\n payload: NotificationPayload,\n options: Pick<NotifyUsersOptions, 'skipEmail'> = {},\n): Promise<void> {\n try {\n const members = await listOrgMembers(orgId)\n const admins = members.filter(\n (member) => member.role === 'owner' || member.role === 'admin',\n )\n // The roster rows carry addresses, so the email channel (AGL-3224) needs\n // no directory lookup for anyone reached this way.\n const emails: Record<string, string | undefined> = {}\n for (const member of admins) {\n if (member.email) emails[member.$id] = member.email\n }\n await notifyUsers(\n admins.map((member) => member.$id),\n { ...payload, orgId },\n { emails, ...(options.skipEmail ? { skipEmail: true } : {}) },\n )\n } catch (error) {\n console.error('org admin notification failed', error)\n }\n}\n\n/**\n * The name a site's managers know it by: the name they gave it, then its\n * address, then — for a doc with neither — its id.\n */\nexport function hostDisplayName(\n host: Record<string, unknown> | undefined,\n hostId: string,\n): string {\n for (const value of [host?.['displayName'], host?.['subdomain']]) {\n if (typeof value === 'string' && value.trim()) return value.trim()\n }\n return hostId\n}\n\n/**\n * Fills `{site}` in a host notification's title or body (AGL-3432).\n *\n * A manager of ten storefronts reads \"New order — $42.00\" and cannot tell\n * which store it came from, and the email shows only the body to someone who\n * skips the subject. `notifyHostManagers` already reads the host doc, so a\n * caller writes \"New order on {site}\" and pays no read of its own.\n */\nexport function withSiteName(text: string, site: string): string {\n return text.includes('{site}') ? text.split('{site}').join(site) : text\n}\n\n/**\n * Notifies everyone who manages a host (admin/editor in the host doc's\n * `memberRoles` projection) — the audience for form submissions and\n * bookings on that site.\n *\n * The OWNING ORG travels with the notification (AGL-1773). Host links are\n * stored in the legacy `/{hostDocId}/rest` shape and rewritten to\n * `/{orgSlug}/hosts/{subdomain}/rest` when they are FOLLOWED\n * (`normalizeNotificationLink`, AGL-644) — a rewrite that needs an org slug.\n * With no `orgId` on the doc the console had nothing to key on and fell back\n * to whichever org the reader happens to have OPEN, so a manager who belongs\n * to more than one workspace was routed to `/{other-org}/hosts/{subdomain}/…`\n * and got a designed 404: `HostGuard` only resolves subdomains belonging to\n * the current org. `notifyOrgAdmins` has always stamped it; the host fan-out\n * — every form submission, booking, order and stock alert — never did.\n *\n * The host doc already carries `orgId` (AGL-233), so this costs no extra\n * read. Spread conditionally: the field is optional on the host model and\n * Firestore rejects `undefined`.\n */\nasync function notifyHostManagersNow(\n hostId: string,\n payload: NotificationPayload,\n options: {\n /**\n * Mail the workspace owner nothing through the email channel, because\n * the caller sends them their own email about the same event.\n */\n skipOwnerEmail?: boolean\n /** What the email alone carries; see {@link NotifyUsersOptions.emailDetails}. */\n emailDetails?: readonly NotificationEmailDetail[]\n /** Who a reply reaches; see {@link NotifyUsersOptions.replyTo}. */\n replyTo?: string\n } = {},\n): Promise<void> {\n try {\n const host = await firestore().collection('hosts').doc(hostId).get()\n const memberRoles =\n (host.get('memberRoles') as Record<string, string> | undefined) ?? {}\n const managers = Object.entries(memberRoles)\n .filter(([, role]) => role === 'admin' || role === 'editor')\n .map(([uid]) => uid)\n const orgId = payload.orgId ?? (host.get('orgId') as string | undefined)\n const site = hostDisplayName(host.data(), hostId)\n const ownerUid =\n options.skipOwnerEmail && orgId\n ? ((await firestore().collection('orgs').doc(orgId).get()).get('ownerUid') as\n | string\n | undefined)\n : undefined\n await notifyUsers(\n managers,\n {\n ...payload,\n title: withSiteName(payload.title, site),\n ...(payload.body !== undefined\n ? { body: withSiteName(payload.body, site) }\n : {}),\n hostId,\n ...(orgId ? { orgId } : {}),\n },\n {\n ...(ownerUid ? { skipEmailFor: [ownerUid] } : {}),\n ...(options.emailDetails ? { emailDetails: options.emailDetails } : {}),\n ...(options.replyTo ? { replyTo: options.replyTo } : {}),\n },\n )\n } catch (error) {\n console.error('host manager notification failed', error)\n }\n}\n\n/*\n * The fan-out's public doors. Most callers start a notification with\n * `void notify…()` beside the mutation it reports, so each door hands its\n * work to the platform's `waitUntil` (`keep-alive.ts`): the push and the email\n * after the feed write are no longer cut off when the response goes out.\n */\n\n/** {@link notifyUsersNow}, kept alive past the response. */\nexport function notifyUsers(...args: Parameters<typeof notifyUsersNow>): Promise<void> {\n return keepAlive(notifyUsersNow(...args))\n}\n\n/** {@link notifyStaffNow}, kept alive past the response. */\nexport function notifyStaff(...args: Parameters<typeof notifyStaffNow>): Promise<void> {\n return keepAlive(notifyStaffNow(...args))\n}\n\n/** {@link notifyStaffConsoleNow}, kept alive past the response. */\nexport function notifyStaffConsole(...args: Parameters<typeof notifyStaffConsoleNow>): Promise<void> {\n return keepAlive(notifyStaffConsoleNow(...args))\n}\n\n/** {@link notifyOrgAdminsNow}, kept alive past the response. */\nexport function notifyOrgAdmins(...args: Parameters<typeof notifyOrgAdminsNow>): Promise<void> {\n return keepAlive(notifyOrgAdminsNow(...args))\n}\n\n/** {@link notifyHostManagersNow}, kept alive past the response. */\nexport function notifyHostManagers(...args: Parameters<typeof notifyHostManagersNow>): Promise<void> {\n return keepAlive(notifyHostManagersNow(...args))\n}\n"],"names":["buildRoute","NOTIFICATION_SELF_SENT_EMAIL_TYPES","NOTIFICATION_SETTINGS_FIELD","normalizeNotificationLink","notificationChannelEnabled","Route","operatorAlertForNotificationType","isEmailConfigured","sendEmail","notificationPushEnabled","NOTIFICATION_SOUND_FIELD","notificationSound","notificationEmailAction","PLATFORM_BRANDING_PROFILE","platformConsoleOrigin","FieldValue","withoutMailWithheldAccounts","findUserByUidAcrossPools","listStaffUidsAcrossPools","filterSuppressedEmails","meterOrgEmail","meterPlatformEmail","firebaseAdmin","keepAlive","mobilePushEnabled","mobilePushSenders","listOrgMembers","loadSystemEmail","renderLoadedSystemEmail","systemEmailBrand","systemEmailContent","firestore","app","NOTIFY_EMAIL_MAX_DETAILS_CHARS","formatNotificationEmailDetails","details","text","map","label","value","trim","filter","join","length","slice","trimEnd","NOTIFY_EMAIL_MAX_LOOKUPS","NOTIFY_EMAIL_MAX_SENDS","emailNotification","uids","payload","known","audience","emailDetails","replyTo","origin","settingsUrl","MANAGE_NOTIFICATION_SETTINGS","context","notificationEmailContext","url","notificationEmailUrl","loaded","catch","fallbackText","title","body","Boolean","lookups","sent","uid","address","String","toLowerCase","includes","pooled","record","email","recipients","rendered","brand","merge","line","type","productName","options","result","to","subject","fromName","headers","orgId","undefined","org","db","host","Promise","all","collection","doc","get","hostId","resolve","slug","subdomain","orgName","siteName","exists","data","orgSlug","hostSubdomain","error","console","link","test","startsWith","MANAGE_NOTIFICATIONS","notifyUsersNow","targets","Set","userDocs","getAll","scope","batch","count","mailTo","pushTo","sounds","userDoc","settings","legacy","set","id","read","createdAt","serverTimestamp","push","skipEmailFor","commit","send","skipEmail","has","reachable","emails","staffUidCache","STAFF_CACHE_MS","listStaffUids","now","Date","at","notifyStaffNow","alert","raiseOperatorAlert","level","notifyStaffConsole","notifyStaffConsoleNow","notifyUsers","notifyOrgAdminsNow","members","admins","member","role","$id","hostDisplayName","withSiteName","site","split","notifyHostManagersNow","memberRoles","managers","Object","entries","ownerUid","skipOwnerEmail","args","notifyStaff","notifyOrgAdmins","notifyHostManagers"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,kCAAkC,EAClCC,2BAA2B,EAC3BC,yBAAyB,EACzBC,0BAA0B,EAE1BC,KAAK,QAEA,sBAAqB;AAC5B,SAASC,gCAAgC,QAAQ,8CAA6C;AAC9F,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,uBAAuB,QAAQ,2CAA0C;AAClF,SAASC,wBAAwB,EAAEC,iBAAiB,QAAQ,6CAA4C;AACxG,SAASC,uBAAuB,QAAQ,uCAAsC;AAC9E,SAASC,yBAAyB,EAAEC,qBAAqB,QAAQ,wCAAuC;AACxG,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,2BAA2B,QAAQ,oBAAgB;AAC5D,SAASC,wBAAwB,EAAEC,wBAAwB,QAAQ,kBAAc;AACjF,SAASC,sBAAsB,QAAQ,yBAAqB;AAC5D,SAASC,aAAa,EAAEC,kBAAkB,QAAQ,sBAAkB;AACpE,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,SAAS,QAAQ,kBAAc;AACxC,SAASC,iBAAiB,EAAEC,iBAAiB,QAAQ,0BAAsB;AAC3E,SAASC,cAAc,QAAQ,qBAAiB;AAChD,SACEC,eAAe,EACfC,uBAAuB,EACvBC,gBAAgB,EAChBC,kBAAkB,QAEb,2BAAuB;AAE9B,MAAMC,YAAY,IAAMT,cAAcU,GAAG,GAAGD,SAAS;AAiErD;;;CAGC,GACD,MAAME,iCAAiC;AAEvC;;;CAGC,GACD,OAAO,SAASC,+BACdC,OAAuD;IAEvD,MAAMC,OAAO,CAACD,kBAAAA,U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pB,mBAAmB,GAAGoB,IAA8C;IAClF,OAAOvJ,UAAUoI,yBAAyBmB;AAC5C;AAEA,8DAA8D,GAC9D,OAAO,SAASE,gBAAgB,GAAGF,IAA2C;IAC5E,OAAOvJ,UAAUsI,sBAAsBiB;AACzC;AAEA,iEAAiE,GACjE,OAAO,SAASG,mBAAmB,GAAGH,IAA8C;IAClF,OAAOvJ,UAAUgJ,yBAAyBO;AAC5C"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/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 {\n buildRoute,\n NOTIFICATION_SELF_SENT_EMAIL_TYPES,\n NOTIFICATION_SETTINGS_FIELD,\n normalizeNotificationLink,\n notificationChannelEnabled,\n type AglynNotification,\n Route,\n type NotificationSettings,\n} from '@aglyn/aglyn/server'\nimport { operatorAlertForNotificationType } from '@aglyn/aglyn/plugin-manager/operator-alerts'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { notificationPushEnabled } from '@aglyn/aglyn/app-utils/notification-push'\nimport { NOTIFICATION_SOUND_FIELD, notificationSound } from '@aglyn/aglyn/app-utils/notification-sounds'\nimport { notificationEmailAction, notificationLabel } from '@aglyn/aglyn/app-utils/notifications'\nimport { PLATFORM_BRANDING_PROFILE, platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { withoutMailWithheldAccounts } from './account-mail'\nimport { findUserByUidAcrossPools, listStaffUidsAcrossPools } from './auth-pools'\nimport { filterSuppressedEmails } from './email-suppression'\nimport { meterOrgEmail, meterPlatformEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { keepAlive } from './keep-alive'\nimport { mobilePushEnabled, mobilePushSenders } from './mobile-push-switch'\nimport { listOrgMembers } from './organizations'\nimport {\n loadSystemEmail,\n renderLoadedSystemEmail,\n systemEmailBrand,\n systemEmailContent,\n type SystemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport type NotificationPayload = Omit<\n AglynNotification,\n '$id' | 'createdAt' | 'readAt'\n>\n\nexport interface NotifyUsersOptions {\n /**\n * Addresses the caller already holds, by uid (AGL-3224).\n *\n * Purely an optimization, and one worth taking where it is free: a caller\n * that read the roster — `notifyOrgAdmins` does — has every address in hand\n * already, and without this the email half would look each one up again in\n * the directory. Absent uids fall back to that lookup, so passing a partial\n * map is fine and passing none is correct.\n */\n emails?: Readonly<Record<string, string | null | undefined>>\n /**\n * Who the fan-out is for (AGL-3367). `staff` is the platform talking to its\n * own people, so the email wears the platform's brand and is the platform's\n * cost even when the notification is ABOUT an org, which a canceled\n * subscription or a new ticket always is. Anything else speaks in the org's\n * brand when the notification names one.\n */\n audience?: 'staff'\n /**\n * Write the console notification only, and mail nobody through the\n * per-person email channel (AGL-3375): the caller has emailed the same\n * alert to the operator's inbox, and a staff member who also switched\n * email on would otherwise get it twice.\n */\n skipEmail?: boolean\n /**\n * People not to mail through the email channel for this one notification,\n * because the caller emails them the same event itself — the seller's\n * designed sale email beside a Buy Now order's notification. Everyone else\n * the fan-out reaches is mailed as their preferences say.\n */\n skipEmailFor?: readonly string[]\n /**\n * Particulars the email carries and the notification does not: a form\n * submission's answers, so the person reading the email has the inquiry\n * without opening the console.\n *\n * Email only, never written to the notification document or pushed. The\n * document is copied once per recipient and outlives the record it points\n * at, and a push lands on a lock screen; the record itself stays the one\n * place the visitor's answers are kept.\n */\n emailDetails?: readonly NotificationEmailDetail[]\n /**\n * Who a reply to the email reaches (AGL-3897): the visitor who filled in a\n * form, so a manager answers an inquiry from the inbox it landed in. Never\n * set on a staff fan-out.\n */\n replyTo?: string\n}\n\n/** One labeled line of a notification email's details. */\nexport interface NotificationEmailDetail {\n label: string\n value: string\n}\n\n/**\n * At most this many characters of details per email. A submission is capped\n * at 2,000 characters a field, so a long form would otherwise be a long email.\n */\nconst NOTIFY_EMAIL_MAX_DETAILS_CHARS = 10_000\n\n/**\n * The details as the email prints them: `Label: value`, one per line, a\n * value's own line breaks kept and blank values left out.\n */\nexport function formatNotificationEmailDetails(\n details: readonly NotificationEmailDetail[] | undefined,\n): string {\n const text = (details ?? [])\n .map(({ label, value }) => ({ label: label.trim(), value: value.trim() }))\n .filter(({ value }) => value)\n .map(({ label, value }) => (label ? `${label}: ${value}` : value))\n .join('\\n')\n return text.length > NOTIFY_EMAIL_MAX_DETAILS_CHARS\n ? `${text.slice(0, NOTIFY_EMAIL_MAX_DETAILS_CHARS).trimEnd()}…`\n : text\n}\n\n/**\n * At most this many directory lookups per fan-out, and at most this many\n * notification emails.\n *\n * Both ceilings bite only on a fan-out where many recipients are emailed —\n * the email channel defaults off outside the types in\n * `NOTIFICATION_TYPE_CHANNEL_DEFAULTS`, and every fan-out goes to one\n * workspace's or one site's people, or to staff. They are here because a\n * fan-out takes up to 400 uids and `notifyUsers` runs inside the mutation\n * that emitted it: a notification must not be able to turn one write into\n * four hundred directory reads and four hundred sends.\n */\nconst NOTIFY_EMAIL_MAX_LOOKUPS = 25\nconst NOTIFY_EMAIL_MAX_SENDS = 50\n\n/**\n * The email beside the console notification (AGL-3224).\n *\n * One send per recipient, never a shared `to:` list — two people who manage\n * the same site have not agreed to be shown each other's addresses, and the\n * settings link in the footer belongs to one person.\n *\n * `List-Unsubscribe` points at the settings page rather than at a one-click\n * endpoint: this is not marketing mail and RFC 8058's POST form would be\n * claiming a capability that does not exist. What it does do is put the way\n * out in the headers as well as the body, so a client that surfaces it shows\n * the person the page where the switch they want actually is.\n *\n * Rendered through the `notification` system email (AGL-3367), which is what\n * gives it the header and footer every other system email wears, and makes\n * it designable on the staff System emails page. It used to hand `sendEmail`\n * bare text, which is the unbranded card the fallback HTML part draws. The\n * template is read once per fan-out and rendered per recipient.\n *\n * Never throws, like everything else on this path.\n */\nasync function emailNotification(\n uids: string[],\n payload: NotificationPayload,\n known: Readonly<Record<string, string | null | undefined>>,\n audience: NotifyUsersOptions['audience'],\n emailDetails: NotifyUsersOptions['emailDetails'],\n replyTo?: string,\n): Promise<void> {\n /*\n * `platformConsoleOrigin`, never `NEXT_PUBLIC_CONSOLE_URL` read bare: this\n * runs in the site app as well as the console, and the site app's\n * deployment does not set that variable. Read bare, a notification a site\n * sends (a form submission, an order) would carry a button that opens\n * nothing and a settings line with no address.\n */\n const origin = platformConsoleOrigin()\n const settingsUrl = `${origin}${buildRoute(Route.MANAGE_NOTIFICATION_SETTINGS)}`\n const context = await notificationEmailContext(payload, audience)\n const url = notificationEmailUrl(payload, context, origin)\n const details = formatNotificationEmailDetails(emailDetails)\n // The eyebrow names what this is before where (AGL-4096), \"Proof approved ·\n // Copper Kettle · Acme\", when the emitter gave the notification a label of\n // its own; every other notification keeps the site and workspace alone.\n const eyebrow = [payload.label ? notificationLabel(payload) : '', context.line ?? '']\n .filter(Boolean)\n .join(' · ')\n const loaded = await loadSystemEmail('notification').catch(() => null)\n const fallbackText = [\n payload.title,\n payload.body ?? '',\n details,\n url,\n `Change what you are emailed about: ${settingsUrl}`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n let lookups = 0\n let sent = 0\n for (const uid of uids) {\n if (sent >= NOTIFY_EMAIL_MAX_SENDS) break\n let address = String(known[uid] ?? '').trim().toLowerCase()\n if (!address.includes('@')) {\n if (lookups >= NOTIFY_EMAIL_MAX_LOOKUPS) continue\n lookups += 1\n const pooled = await findUserByUidAcrossPools(uid).catch(() => null)\n address = String(pooled?.record?.email ?? '').trim().toLowerCase()\n }\n if (!address.includes('@')) continue\n const recipients = await filterSuppressedEmails([address])\n if (!recipients.length) continue\n const rendered = loaded\n ? renderLoadedSystemEmail(\n loaded,\n {\n ...context.brand.merge,\n 'notification.title': payload.title,\n 'notification.body': payload.body ?? '',\n 'notification.details': details,\n 'notification.url': url,\n 'notification.context': eyebrow,\n 'notification.replyNote': replyTo ? `Reply to this email to answer ${replyTo}.` : '',\n 'notification.action': notificationEmailAction(\n payload.type,\n context.brand.merge['brand.productName'] || PLATFORM_BRANDING_PROFILE.productName,\n payload.actionLabel,\n ),\n settingsUrl,\n },\n context.brand.options,\n )\n : null\n const result = await sendEmail({\n to: recipients,\n ...systemEmailContent(rendered, {\n subject: payload.title,\n text: fallbackText,\n }),\n ...(context.brand.fromName ? { fromName: context.brand.fromName } : {}),\n context: 'notification',\n ...(replyTo ? { replyTo } : {}),\n headers: { 'List-Unsubscribe': `<${settingsUrl}>` },\n })\n if (!result.sent) continue\n sent += 1\n // Whose cost it is: a notification to a workspace's people is that\n // workspace's mail, and a staff alert or an account-level notice is the\n // platform's, whichever org it is about.\n await (payload.orgId && audience !== 'staff'\n ? meterOrgEmail(payload.orgId)\n : meterPlatformEmail()\n ).catch(() => undefined)\n }\n}\n\n/** What a notification email needs from the org and site it is about. */\ninterface NotificationEmailContext {\n brand: SystemEmailBrand\n orgSlug?: string\n hostSubdomain?: string\n /**\n * What the notification is about, for the line above its heading\n * (AGL-3897): the site and the workspace, \"Copper Kettle Catering · Acme\",\n * or the workspace alone. A person in several workspaces otherwise gets\n * \"New order\" with nothing to say whose.\n */\n line?: string\n}\n\n/**\n * The org's brand, and the slug and subdomain its stored link is rewritten\n * with (AGL-3367): at most two reads per fan-out, made only when someone is\n * being emailed.\n *\n * A staff fan-out reads nothing. Its brand is the platform's, and its links\n * are staff routes that need no rewriting.\n */\nasync function notificationEmailContext(\n payload: NotificationPayload,\n audience: NotifyUsersOptions['audience'],\n): Promise<NotificationEmailContext> {\n if (audience === 'staff' || !payload.orgId) {\n return { brand: systemEmailBrand(null) }\n }\n try {\n const db = firestore()\n const [org, host] = await Promise.all([\n db.collection('orgs').doc(payload.orgId).get(),\n payload.hostId\n ? db.collection('hosts').doc(payload.hostId).get()\n : Promise.resolve(null),\n ])\n const slug = org.get('slug')\n const subdomain = host?.get('subdomain')\n const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '')\n const orgName = text(org.get('name'))\n const siteName = text(host?.get('displayName')) || text(host?.get('name')) || text(subdomain)\n const line = [siteName, orgName && orgName !== siteName ? orgName : ''].filter(Boolean).join(' · ')\n return {\n brand: systemEmailBrand(org.exists ? (org.data() ?? null) : null),\n ...(line ? { line } : {}),\n ...(typeof slug === 'string' && slug ? { orgSlug: slug } : {}),\n ...(typeof subdomain === 'string' && subdomain\n ? { hostSubdomain: subdomain }\n : {}),\n }\n } catch (error) {\n console.error('notification email context failed', error)\n return { brand: systemEmailBrand(null) }\n }\n}\n\n/**\n * Where the email's button goes: the notification's own link, rewritten onto\n * today's routes the way the console rewrites it when it is clicked, else\n * the notifications page. A stored host link is `/{hostDocId}/…`, which only\n * that rewrite turns into a page that exists.\n */\nfunction notificationEmailUrl(\n payload: NotificationPayload,\n context: NotificationEmailContext,\n origin: string,\n): string {\n const link = normalizeNotificationLink(payload.link, {\n orgSlug: context.orgSlug,\n hostId: payload.hostId,\n hostSubdomain: context.hostSubdomain,\n })\n if (link && /^https?:\\/\\//i.test(link)) return link\n return `${origin}${link?.startsWith('/') ? link : buildRoute(Route.MANAGE_NOTIFICATIONS)}`\n}\n\n/**\n * Notification fan-out (AGL-259): batch-writes one doc per recipient at\n * `users/{uid}/notifications`, and — for recipients who asked for it\n * (AGL-3224) — sends one email beside it. Never throws: a notification miss,\n * or a send that failed, must not break the mutation that emitted it.\n */\nasync function notifyUsersNow(\n uids: Iterable<string>,\n payload: NotificationPayload,\n options: NotifyUsersOptions = {},\n): Promise<void> {\n try {\n const db = firestore()\n const targets = [...new Set(uids)].filter(Boolean).slice(0, 400)\n if (!targets.length) return\n // Per-user preferences (AGL-267, AGL-3223): one getAll over the user\n // docs, which now answers for both channels and for all three scopes —\n // the settings live on this document precisely so that stays one read.\n const userDocs = await db.getAll(\n ...targets.map((uid) => db.collection('users').doc(uid)),\n )\n const scope = { orgId: payload.orgId, hostId: payload.hostId }\n const batch = db.batch()\n let count = 0\n const mailTo: string[] = []\n const pushTo: string[] = []\n const sounds: Record<string, string> = {}\n for (const userDoc of userDocs) {\n const settings = userDoc.get(NOTIFICATION_SETTINGS_FIELD) as\n | NotificationSettings\n | undefined\n const legacy = userDoc.get('notificationPrefs') as\n | Record<string, boolean>\n | undefined\n if (\n notificationChannelEnabled(\n settings,\n 'console',\n payload.type,\n scope,\n legacy,\n )\n ) {\n batch.set(\n db\n .collection('users')\n .doc(userDoc.id)\n .collection('notifications')\n .doc(),\n // `read: false` on create, so the feed can ask for unread and read\n // alike by equality (AGL-3321; see `AglynNotification.read`).\n { ...payload, read: false, createdAt: FieldValue.serverTimestamp() },\n )\n count += 1\n }\n // The mobile push channel (AGL-3620); unanswered, it follows the feed.\n if (notificationPushEnabled(settings, payload.type, scope, legacy)) {\n pushTo.push(userDoc.id)\n sounds[userDoc.id] = notificationSound(userDoc.get(NOTIFICATION_SOUND_FIELD)).id\n }\n if (\n notificationChannelEnabled(settings, 'email', payload.type, scope, legacy) &&\n !options.skipEmailFor?.includes(userDoc.id)\n ) {\n mailTo.push(userDoc.id)\n }\n }\n if (count > 0) await batch.commit()\n /*\n * The push after the commit for the same reason as the email below:\n * every registered transport is handed the recipients whose preferences\n * say push, unless the deployment has pulled the kill switch. A failing\n * transport is logged and never stops the email or another transport.\n */\n if (pushTo.length && mobilePushEnabled()) {\n for (const send of mobilePushSenders()) {\n try {\n await send(pushTo, payload, { db, sounds })\n } catch (error) {\n console.error('push delivery failed', error)\n }\n }\n }\n /*\n * THE EMAIL AFTER THE COMMIT, and not inside its `try`.\n *\n * The console notification is the durable record and the send is a\n * courtesy on top of it, so the order is the one where a failing network\n * call cannot lose the record. The two channels are independent by\n * design — a person may have muted the feed and asked for mail, or the\n * reverse — so neither is gated on the other having happened.\n *\n * Digests are excluded: they compose and send their own mail, under\n * their own switches, and the generic channel would send a second\n * message announcing that the first one had been sent.\n *\n * A locked or disabled account is not mailed (AGL-3418); its feed entry\n * above still records the event.\n */\n if (\n mailTo.length &&\n !options.skipEmail &&\n isEmailConfigured() &&\n !NOTIFICATION_SELF_SENT_EMAIL_TYPES.has(payload.type)\n ) {\n const reachable = await withoutMailWithheldAccounts(mailTo)\n if (!reachable.length) return\n await emailNotification(\n reachable,\n payload,\n options.emails ?? {},\n options.audience,\n options.emailDetails,\n options.audience === 'staff' ? undefined : options.replyTo,\n )\n }\n } catch (error) {\n console.error('notification fan-out failed', error)\n }\n}\n\n// Staff are identified by a Firebase Auth custom claim (`staff`), which is not\n// a Firestore query — so the roster comes from paginating the auth users. A\n// burst of ticket activity shouldn't rescan every time, so the (small) result\n// is cached briefly. Fails soft to an empty list.\nlet staffUidCache: { uids: string[]; at: number } | null = null\nconst STAFF_CACHE_MS = 60_000\n\nasync function listStaffUids(): Promise<string[]> {\n const now = Date.now()\n if (staffUidCache && now - staffUidCache.at < STAFF_CACHE_MS) {\n return staffUidCache.uids\n }\n // Across ALL auth pools (AGL-1122). This scanned only the project pool, so\n // a staff member who signs in through enterprise SSO — whose account lives\n // in a GCIP tenant pool — was never in the fan-out. Nothing errored; the\n // notification simply never arrived, which is the worst shape a miss can\n // take on an alerting path.\n const uids = await listStaffUidsAcrossPools()\n staffUidCache = { uids, at: now }\n return uids\n}\n\n/**\n * Notifies every staff-claim holder (AGL-850) — the support-desk audience.\n * Staff are not org members, so `notifyOrgAdmins`/`notifyHostManagers` never\n * reach them; this enumerates the `staff` custom claim instead. The docs land\n * at `users/{uid}/notifications`, which the console notifications menu already\n * renders, so no separate staff inbox is needed. Never throws.\n *\n * A type the operator alert registry names (AGL-3377) — a fraud or risk\n * alert, a dispute nobody owns, a support ticket — is raised as that alert\n * instead: the same console notification, plus staff's switches, the\n * operator email or digest, and the webhook. See `raiseOperatorAlert`.\n */\nasync function notifyStaffNow(\n payload: NotificationPayload,\n options: Pick<NotifyUsersOptions, 'emailDetails'> = {},\n): Promise<void> {\n try {\n const alert = operatorAlertForNotificationType(payload.type)\n if (alert) {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n await raiseOperatorAlert(alert, {\n subject: payload.title,\n ...(payload.body ? { body: payload.body } : {}),\n ...(payload.level ? { level: payload.level } : {}),\n ...(payload.link ? { url: payload.link } : {}),\n ...(payload.orgId ? { orgId: payload.orgId } : {}),\n ...(payload.hostId ? { hostId: payload.hostId } : {}),\n })\n return\n }\n await notifyStaffConsole(payload, options)\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * The staff console notification alone, with the per-person email channel\n * it carries: what `notifyStaff` did before the registry, and what\n * `raiseOperatorAlert` writes as its first step. Never throws.\n */\nasync function notifyStaffConsoleNow(\n payload: NotificationPayload,\n options: Pick<NotifyUsersOptions, 'skipEmail' | 'emailDetails'> = {},\n): Promise<void> {\n try {\n await notifyUsers(await listStaffUids(), payload, {\n audience: 'staff',\n ...(options.skipEmail ? { skipEmail: true } : {}),\n // What the email alone carries — a new account's acquisition, a new\n // site's workspace (AGL-3897) — beside the bell's one line.\n ...(options.emailDetails?.length ? { emailDetails: options.emailDetails } : {}),\n })\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * Notifies the org's owner + admins (billing, membership, org events).\n *\n * `skipEmail` is for a caller that emails the same notice to the same people\n * itself — the usage alerts do (AGL-3431) — so an admin who switched the\n * email channel on is not sent it twice.\n */\nasync function notifyOrgAdminsNow(\n orgId: string,\n payload: NotificationPayload,\n options: Pick<NotifyUsersOptions, 'skipEmail'> = {},\n): Promise<void> {\n try {\n const members = await listOrgMembers(orgId)\n const admins = members.filter(\n (member) => member.role === 'owner' || member.role === 'admin',\n )\n // The roster rows carry addresses, so the email channel (AGL-3224) needs\n // no directory lookup for anyone reached this way.\n const emails: Record<string, string | undefined> = {}\n for (const member of admins) {\n if (member.email) emails[member.$id] = member.email\n }\n await notifyUsers(\n admins.map((member) => member.$id),\n { ...payload, orgId },\n { emails, ...(options.skipEmail ? { skipEmail: true } : {}) },\n )\n } catch (error) {\n console.error('org admin notification failed', error)\n }\n}\n\n/**\n * The name a site's managers know it by: the name they gave it, then its\n * address, then — for a doc with neither — its id.\n */\nexport function hostDisplayName(\n host: Record<string, unknown> | undefined,\n hostId: string,\n): string {\n for (const value of [host?.['displayName'], host?.['subdomain']]) {\n if (typeof value === 'string' && value.trim()) return value.trim()\n }\n return hostId\n}\n\n/**\n * Fills `{site}` in a host notification's title or body (AGL-3432).\n *\n * A manager of ten storefronts reads \"New order — $42.00\" and cannot tell\n * which store it came from, and the email shows only the body to someone who\n * skips the subject. `notifyHostManagers` already reads the host doc, so a\n * caller writes \"New order on {site}\" and pays no read of its own.\n */\nexport function withSiteName(text: string, site: string): string {\n return text.includes('{site}') ? text.split('{site}').join(site) : text\n}\n\n/**\n * Notifies everyone who manages a host (admin/editor in the host doc's\n * `memberRoles` projection) — the audience for form submissions and\n * bookings on that site.\n *\n * The OWNING ORG travels with the notification (AGL-1773). Host links are\n * stored in the legacy `/{hostDocId}/rest` shape and rewritten to\n * `/{orgSlug}/hosts/{subdomain}/rest` when they are FOLLOWED\n * (`normalizeNotificationLink`, AGL-644) — a rewrite that needs an org slug.\n * With no `orgId` on the doc the console had nothing to key on and fell back\n * to whichever org the reader happens to have OPEN, so a manager who belongs\n * to more than one workspace was routed to `/{other-org}/hosts/{subdomain}/…`\n * and got a designed 404: `HostGuard` only resolves subdomains belonging to\n * the current org. `notifyOrgAdmins` has always stamped it; the host fan-out\n * — every form submission, booking, order and stock alert — never did.\n *\n * The host doc already carries `orgId` (AGL-233), so this costs no extra\n * read. Spread conditionally: the field is optional on the host model and\n * Firestore rejects `undefined`.\n */\nasync function notifyHostManagersNow(\n hostId: string,\n payload: NotificationPayload,\n options: {\n /**\n * Mail the workspace owner nothing through the email channel, because\n * the caller sends them their own email about the same event.\n */\n skipOwnerEmail?: boolean\n /** What the email alone carries; see {@link NotifyUsersOptions.emailDetails}. */\n emailDetails?: readonly NotificationEmailDetail[]\n /** Who a reply reaches; see {@link NotifyUsersOptions.replyTo}. */\n replyTo?: string\n } = {},\n): Promise<void> {\n try {\n const host = await firestore().collection('hosts').doc(hostId).get()\n const memberRoles =\n (host.get('memberRoles') as Record<string, string> | undefined) ?? {}\n const managers = Object.entries(memberRoles)\n .filter(([, role]) => role === 'admin' || role === 'editor')\n .map(([uid]) => uid)\n const orgId = payload.orgId ?? (host.get('orgId') as string | undefined)\n const site = hostDisplayName(host.data(), hostId)\n const ownerUid =\n options.skipOwnerEmail && orgId\n ? ((await firestore().collection('orgs').doc(orgId).get()).get('ownerUid') as\n | string\n | undefined)\n : undefined\n await notifyUsers(\n managers,\n {\n ...payload,\n title: withSiteName(payload.title, site),\n ...(payload.body !== undefined\n ? { body: withSiteName(payload.body, site) }\n : {}),\n hostId,\n ...(orgId ? { orgId } : {}),\n },\n {\n ...(ownerUid ? { skipEmailFor: [ownerUid] } : {}),\n ...(options.emailDetails ? { emailDetails: options.emailDetails } : {}),\n ...(options.replyTo ? { replyTo: options.replyTo } : {}),\n },\n )\n } catch (error) {\n console.error('host manager notification failed', error)\n }\n}\n\n/*\n * The fan-out's public doors. Most callers start a notification with\n * `void notify…()` beside the mutation it reports, so each door hands its\n * work to the platform's `waitUntil` (`keep-alive.ts`): the push and the email\n * after the feed write are no longer cut off when the response goes out.\n */\n\n/** {@link notifyUsersNow}, kept alive past the response. */\nexport function notifyUsers(...args: Parameters<typeof notifyUsersNow>): Promise<void> {\n return keepAlive(notifyUsersNow(...args))\n}\n\n/** {@link notifyStaffNow}, kept alive past the response. */\nexport function notifyStaff(...args: Parameters<typeof notifyStaffNow>): Promise<void> {\n return keepAlive(notifyStaffNow(...args))\n}\n\n/** {@link notifyStaffConsoleNow}, kept alive past the response. */\nexport function notifyStaffConsole(...args: Parameters<typeof notifyStaffConsoleNow>): Promise<void> {\n return keepAlive(notifyStaffConsoleNow(...args))\n}\n\n/** {@link notifyOrgAdminsNow}, kept alive past the response. */\nexport function notifyOrgAdmins(...args: Parameters<typeof notifyOrgAdminsNow>): Promise<void> {\n return keepAlive(notifyOrgAdminsNow(...args))\n}\n\n/** {@link notifyHostManagersNow}, kept alive past the response. */\nexport function notifyHostManagers(...args: Parameters<typeof notifyHostManagersNow>): Promise<void> {\n return keepAlive(notifyHostManagersNow(...args))\n}\n"],"names":["buildRoute","NOTIFICATION_SELF_SENT_EMAIL_TYPES","NOTIFICATION_SETTINGS_FIELD","normalizeNotificationLink","notificationChannelEnabled","Route","operatorAlertForNotificationType","isEmailConfigured","sendEmail","notificationPushEnabled","NOTIFICATION_SOUND_FIELD","notificationSound","notificationEmailAction","notificationLabel","PLATFORM_BRANDING_PROFILE","platformConsoleOrigin","FieldValue","withoutMailWithheldAccounts","findUserByUidAcrossPools","listStaffUidsAcrossPools","filterSuppressedEmails","meterOrgEmail","meterPlatformEmail","firebaseAdmin","keepAlive","mobilePushEnabled","mobilePushSenders","listOrgMembers","loadSystemEmail","renderLoadedSystemEmail","systemEmailBrand","systemEmailContent","firestore","app","NOTIFY_EMAIL_MAX_DETAILS_CHARS","formatNotificationEmailDetails","details","text","map","label","value","trim","filter","join","length","slice","trimEnd","NOTIFY_EMAIL_MAX_LOOKUPS","NOTIFY_EMAIL_MAX_SENDS","emailNotification","uids","payload","known","audience","emailDetails","replyTo","context","origin","settingsUrl","MANAGE_NOTIFICATION_SETTINGS","notificationEmailContext","url","notificationEmailUrl","eyebrow","line","Boolean","loaded","catch","fallbackText","title","body","lookups","sent","uid","address","String","toLowerCase","includes","pooled","record","email","recipients","rendered","brand","merge","type","productName","actionLabel","options","result","to","subject","fromName","headers","orgId","undefined","org","db","host","Promise","all","collection","doc","get","hostId","resolve","slug","subdomain","orgName","siteName","exists","data","orgSlug","hostSubdomain","error","console","link","test","startsWith","MANAGE_NOTIFICATIONS","notifyUsersNow","targets","Set","userDocs","getAll","scope","batch","count","mailTo","pushTo","sounds","userDoc","settings","legacy","set","id","read","createdAt","serverTimestamp","push","skipEmailFor","commit","send","skipEmail","has","reachable","emails","staffUidCache","STAFF_CACHE_MS","listStaffUids","now","Date","at","notifyStaffNow","alert","raiseOperatorAlert","level","notifyStaffConsole","notifyStaffConsoleNow","notifyUsers","notifyOrgAdminsNow","members","admins","member","role","$id","hostDisplayName","withSiteName","site","split","notifyHostManagersNow","memberRoles","managers","Object","entries","ownerUid","skipOwnerEmail","args","notifyStaff","notifyOrgAdmins","notifyHostManagers"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,kCAAkC,EAClCC,2BAA2B,EAC3BC,yBAAyB,EACzBC,0BAA0B,EAE1BC,KAAK,QAEA,sBAAqB;AAC5B,SAASC,gCAAgC,QAAQ,8CAA6C;AAC9F,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,uBAAuB,QAAQ,2CAA0C;AAClF,SAASC,wBAAwB,EAAEC,iBAAiB,QAAQ,6CAA4C;AACxG,SAASC,uBAAuB,EAAEC,iBAAiB,QAAQ,uCAAsC;AACjG,SAASC,yBAAyB,EAAEC,qBAAqB,QAAQ,wCAAuC;AACxG,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,2BAA2B,QAAQ,oBAAgB;AAC5D,SAASC,wBAAwB,EAAEC,wBAAwB,QAAQ,kBAAc;AACjF,SAASC,sBAAsB,QAAQ,yBAAqB;AAC5D,SAASC,aAAa,EAAEC,kBAAkB,QAAQ,sBAAkB;AACpE,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,SAAS,QAAQ,kBAAc;AACxC,SAASC,iBAAiB,EAAEC,iBAAiB,QAAQ,0BAAsB;AAC3E,SAASC,cAAc,QAAQ,qBAAiB;AAChD,SACEC,eAAe,EACfC,uBAAuB,EACvBC,gBAAgB,EAChBC,kBAAkB,QAEb,2BAAuB;AAE9B,MAAMC,YAAY,IAAMT,cAAcU,G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;QAAC,IAAI,CAAC;IAG5D,EAAE,OAAO2D,OAAO;QACdC,QAAQD,KAAK,CAAC,oCAAoCA;IACpD;AACF;AAEA;;;;;CAKC,GAED,0DAA0D,GAC1D,OAAO,SAAS6C,YAAY,GAAGkB,IAAuC;IACpE,OAAOzJ,UAAUgG,kBAAkByD;AACrC;AAEA,0DAA0D,GAC1D,OAAO,SAASC,YAAY,GAAGD,IAAuC;IACpE,OAAOzJ,UAAUiI,kBAAkBwB;AACrC;AAEA,iEAAiE,GACjE,OAAO,SAASpB,mBAAmB,GAAGoB,IAA8C;IAClF,OAAOzJ,UAAUsI,yBAAyBmB;AAC5C;AAEA,8DAA8D,GAC9D,OAAO,SAASE,gBAAgB,GAAGF,IAA2C;IAC5E,OAAOzJ,UAAUwI,sBAAsBiB;AACzC;AAEA,iEAAiE,GACjE,OAAO,SAASG,mBAAmB,GAAGH,IAA8C;IAClF,OAAOzJ,UAAUkJ,yBAAyBO;AAC5C"}
@@ -39,10 +39,16 @@ import { type DocumentReference, type Transaction } from 'firebase-admin/firesto
39
39
  /** A starter resolved for a create: its payload, and the listing it came from. */
40
40
  export interface SiteStarterInstall {
41
41
  payload: SiteStarterPayload;
42
+ /**
43
+ * The listing it came from. `kind` is the kind of site the listing names
44
+ * (AGL-4049), which the site records over the one its stored pages carry:
45
+ * a listing's kind is kept current by its publisher and by staff.
46
+ */
42
47
  listing: {
43
48
  listingId: string;
44
49
  version: string | number;
45
50
  displayName: string;
51
+ kind?: string | null;
46
52
  };
47
53
  }
48
54
  /** Every document a starter's site is born with, ids minted, ready to queue. */
@@ -98,7 +104,8 @@ export interface SiteStarterPickRefusal {
98
104
  * site can be created from it (AGL-4049). Every refusal is decided before the
99
105
  * site exists, so a refused pick creates nothing, and a 402 is answered with
100
106
  * what the person needs to buy it: the listing and its price. Once bought,
101
- * the same request again creates the site.
107
+ * the same request again creates the site. Every refusal names the listing
108
+ * it refused, so Create site can tell a refused pick from a refused name.
102
109
  *
103
110
  * `resolved` is what the starter source answered; `pagesAllowed` is the
104
111
  * plan's `screensPerHost`.
@@ -190,7 +190,8 @@ const text = (value)=>typeof value === 'string' ? value.trim() : '';
190
190
  * site can be created from it (AGL-4049). Every refusal is decided before the
191
191
  * site exists, so a refused pick creates nothing, and a 402 is answered with
192
192
  * what the person needs to buy it: the listing and its price. Once bought,
193
- * the same request again creates the site.
193
+ * the same request again creates the site. Every refusal names the listing
194
+ * it refused, so Create site can tell a refused pick from a refused name.
194
195
  *
195
196
  * `resolved` is what the starter source answered; `pagesAllowed` is the
196
197
  * plan's `screensPerHost`.
@@ -227,7 +228,8 @@ const text = (value)=>typeof value === 'string' ? value.trim() : '';
227
228
  return {
228
229
  status: 409,
229
230
  body: {
230
- error: 'This starter needs the AI start, which is coming soon'
231
+ error: 'This starter needs the AI start, which is coming soon',
232
+ listingId: input.listingId
231
233
  }
232
234
  };
233
235
  }
@@ -236,7 +238,8 @@ const text = (value)=>typeof value === 'string' ? value.trim() : '';
236
238
  return {
237
239
  status: 403,
238
240
  body: {
239
- error: `This starter has ${pages} pages; your plan includes ${input.pagesAllowed}. ` + 'Pick a smaller starter or upgrade in Billing.'
241
+ error: `This starter has ${pages} pages; your plan includes ${input.pagesAllowed}. ` + 'Pick a smaller starter or upgrade in Billing.',
242
+ listingId: input.listingId
240
243
  }
241
244
  };
242
245
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/provision-starter.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 { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { SCREEN_ROOT_PATH } from '@aglyn/aglyn/app-utils/screen-slug'\nimport type {\n SiteStarterChoice,\n SiteStarterPayload,\n} from '@aglyn/aglyn/app-utils/site-starter'\nimport { starterLinksById } from '@aglyn/aglyn/app-utils/site-starter-links'\nimport { planSiteStarterTheme } from '@aglyn/aglyn/app-utils/site-starter-theme'\nimport { encodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport {\n THEME_LIBRARY_COLLECTION,\n type ThemeLibraryEntryWrite,\n} from '@aglyn/aglyn/app-utils/theme-library'\nimport { listServerThemePresets } from '@aglyn/aglyn/plugin-manager/plugin-theme-presets'\nimport {\n FieldValue,\n type DocumentReference,\n type Transaction,\n} from 'firebase-admin/firestore'\n\n/**\n * A site created from a site starter (AGL-4049): the starter twin of the\n * default site's writes (`defaultSiteWrites` and `queueStarterPages` in the\n * console's `provision-host.ts`), written by the same create transaction.\n *\n * Every page the starter carries becomes a page of the new site, its first\n * version holding the starter's nodes; the shared layout becomes the site's\n * header and footer, and every page sits in it; the theme is planned against\n * the empty host (`planSiteStarterTheme`). A page routed in the starter is\n * routed and published on the new site, and the Home page at `/` is named\n * `defaultHomeScreenId`: the platform-made page the owner's own home page\n * replaces (AGL-3478). A page with no address, or one the starter marks\n * unpublished, is a draft.\n *\n * Nodes are copied as published. A link to another page travels by slug in\n * the starter (`site-starter-links.ts`) and becomes the new page's id here;\n * a token such as `{{host.businessName}}` renders per site on its own, so\n * nothing is substituted.\n */\n\n/** A starter resolved for a create: its payload, and the listing it came from. */\nexport interface SiteStarterInstall {\n payload: SiteStarterPayload\n listing: { listingId: string; version: string | number; displayName: string }\n}\n\n/** Every document a starter's site is born with, ids minted, ready to queue. */\nexport interface SiteStarterWrites {\n /** The Home page at `/`; `null` only for a payload that failed its check. */\n homeScreenId: string | null\n /** Every published page: screen id → slug, the host's `screens` map. */\n routing: Record<string, string>\n screens: Array<{\n id: string\n versionId: string\n screen: Record<string, unknown>\n version: Record<string, unknown>\n }>\n layout: {\n id: string\n versionId: string\n layout: Record<string, unknown>\n version: Record<string, unknown>\n }\n /** Theme fields for the host's create, from `planSiteStarterTheme`. */\n host: Record<string, unknown>\n /** Theme library entries to create under the host. */\n themeEntries: ThemeLibraryEntryWrite[]\n}\n\nconst isRecord = (value: unknown): value is Record<string, any> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n\nconst text = (value: unknown): string =>\n typeof value === 'string' ? value.trim() : ''\n\n/** Nodes as a version stores them: msgpack at rest, as `/api/hosts/versions` writes them. */\nfunction storedNodes(nodes: Record<string, unknown>): unknown {\n const packed = encodeStoredNodes(nodes)\n return packed ? Buffer.from(packed) : nodes\n}\n\n/**\n * The documents a site created from `install` starts with, every id minted:\n * the pages' ids first, so each page's links and the layout's can name them.\n */\nexport function siteStarterWrites(install: SiteStarterInstall): SiteStarterWrites {\n const now = () => FieldValue.serverTimestamp()\n const payload = install.payload\n const pages = (Array.isArray(payload.screens) ? payload.screens : [])\n .filter(isRecord)\n .map((screen) => ({ screen, id: createResourceUid(), versionId: createResourceUid() }))\n const layoutId = createResourceUid()\n const layoutVersionId = createResourceUid()\n\n // Routed: a page with an address that is not marked unpublished, the\n // first to claim an address keeping it. Links resolve to routed pages\n // first, then to a draft that names an address nobody routes.\n const routing: Record<string, string> = {}\n const slugToId: Record<string, string> = {}\n const routed = new Set<string>()\n for (const page of pages) {\n const slug = text(page.screen['slug'])\n if (!slug || page.screen['published'] === false || slug in slugToId) continue\n routing[page.id] = slug\n slugToId[slug] = page.id\n routed.add(page.id)\n }\n for (const page of pages) {\n const slug = text(page.screen['slug'])\n if (slug && !(slug in slugToId)) slugToId[slug] = page.id\n }\n const homeScreenId =\n Object.keys(routing).find((id) => routing[id] === SCREEN_ROOT_PATH) ?? null\n\n const screens = pages.map(({ screen, id, versionId }) => {\n const isRouted = routed.has(id)\n const fields = {\n displayName: text(screen['displayName']) || 'Page',\n ...(isRouted ? { slug: routing[id] } : {}),\n versionId,\n }\n const description = text(screen['description'])\n const nodes = starterLinksById(isRecord(screen['nodes']) ? screen['nodes'] : {}, slugToId)\n return {\n id,\n versionId,\n screen: {\n ...fields,\n ...artifactCreateListKeys('screens', fields),\n layoutId,\n ...(isRecord(screen['seo']) ? { seo: screen['seo'] } : {}),\n ...(description ? { description } : {}),\n // What `publishScreenRoute` stamps, so the console lists a routed\n // page as Published rather than as a draft that happens to be served.\n ...(isRouted ? { publishedAt: now() } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n version: {\n screenId: id,\n displayName: 'Initial version',\n nodes: storedNodes(nodes),\n createdAt: now(),\n updatedAt: now(),\n },\n }\n })\n\n const source = isRecord(payload.layout) ? payload.layout : {}\n const layoutFields = {\n displayName: text(source['displayName']) || 'Site header and footer',\n versionId: layoutVersionId,\n }\n const layoutDescription = text(source['description'])\n const layoutNodes = starterLinksById(isRecord(source['nodes']) ? source['nodes'] : {}, slugToId)\n const props = Array.isArray(source['props']) && source['props'].length ? source['props'] : null\n\n const theme = planSiteStarterTheme({\n theme: payload.theme,\n presets: listServerThemePresets(),\n listing: install.listing,\n newId: createResourceUid,\n })\n\n return {\n homeScreenId,\n routing,\n screens,\n layout: {\n id: layoutId,\n versionId: layoutVersionId,\n layout: {\n ...layoutFields,\n ...artifactCreateListKeys('layouts', layoutFields),\n ...(layoutDescription ? { description: layoutDescription } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n version: {\n layoutId,\n displayName: 'Initial version',\n nodes: storedNodes(layoutNodes),\n // The properties the layout's tree binds to (AGL-2932), on the\n // version it is served from, as Use template writes them.\n ...(props ? { props } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n },\n host: theme.host,\n themeEntries: theme.entries,\n }\n}\n\n/**\n * Queues a starter's documents in the create transaction: every page and its\n * first version, the layout and its first version (which carries the host\n * id, as the default layout's does), and the theme library entries. An empty\n * host's theme plan creates entries and nothing else, so a create is all a\n * new site's library takes.\n */\nexport function queueSiteStarterWrites(\n tx: Transaction,\n hostRef: DocumentReference,\n hostId: string,\n writes: SiteStarterWrites,\n): void {\n for (const page of writes.screens) {\n const pageRef = hostRef.collection('screens').doc(page.id)\n tx.set(pageRef, page.screen)\n tx.set(pageRef.collection('versions').doc(page.versionId), page.version)\n }\n const layoutRef = hostRef.collection('layouts').doc(writes.layout.id)\n tx.set(layoutRef, writes.layout.layout)\n tx.set(layoutRef.collection('versions').doc(writes.layout.versionId), {\n ...writes.layout.version,\n hostId,\n })\n const library = hostRef.collection(THEME_LIBRARY_COLLECTION)\n for (const entry of writes.themeEntries) {\n if (entry.op !== 'create') continue\n tx.set(library.doc(entry.id), {\n ...(entry.data as unknown as Record<string, unknown>),\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n}\n\n/** A listing id as a document id may be one: no path separator, nothing reserved. */\nconst LISTING_ID = /^[A-Za-z0-9_-]{1,128}$/\n/** A pinned version: the number of one of the listing's versions. */\nconst LISTING_VERSION = /^[1-9][0-9]{0,8}$/\n\n/**\n * A create request's starter pick (`body.starter`), or `null` when it is not\n * one: an object naming a listing id, and optionally the version it pins.\n * The id becomes a document path on the way to the listing, so anything that\n * could name another document is not a pick.\n */\nexport function readSiteStarterChoice(value: unknown): SiteStarterChoice | null {\n if (!isRecord(value)) return null\n const listingId = text(value['listingId'])\n if (!LISTING_ID.test(listingId) || /^__.*__$/.test(listingId)) return null\n const pinned = value['version']\n if (pinned === undefined || pinned === null) return { listingId }\n const version = typeof pinned === 'number' ? String(pinned) : text(pinned)\n return LISTING_VERSION.test(version) ? { listingId, version } : null\n}\n\n/** The answer a create gives a starter pick it refuses: a status and its JSON body. */\nexport interface SiteStarterPickRefusal {\n status: number\n body: Record<string, unknown>\n}\n\n/**\n * Why a create refuses the starter it was asked for, or `null` when the\n * site can be created from it (AGL-4049). Every refusal is decided before the\n * site exists, so a refused pick creates nothing, and a 402 is answered with\n * what the person needs to buy it: the listing and its price. Once bought,\n * the same request again creates the site.\n *\n * `resolved` is what the starter source answered; `pagesAllowed` is the\n * plan's `screensPerHost`.\n */\nexport function siteStarterPickRefusal(\n resolved: SiteStarterPayload | { error: string; status: 402 | 403 | 404; priceUsd?: number },\n input: { listingId: string; pagesAllowed: number },\n): SiteStarterPickRefusal | null {\n if (!isRecord(resolved)) {\n return { status: 404, body: { error: 'That starter is no longer available', listingId: input.listingId } }\n }\n if ('error' in resolved) {\n const status = [402, 403, 404].includes(resolved.status) ? resolved.status : 404\n return {\n status,\n body: {\n error: resolved.error,\n ...(status === 402 ? { code: 'purchase_required' } : {}),\n listingId: input.listingId,\n ...(typeof resolved.priceUsd === 'number' ? { priceUsd: resolved.priceUsd } : {}),\n },\n }\n }\n if (resolved.mode === 'ai') {\n return { status: 409, body: { error: 'This starter needs the AI start, which is coming soon' } }\n }\n const pages = Array.isArray(resolved.screens) ? resolved.screens.length : 0\n if (pages > input.pagesAllowed) {\n return {\n status: 403,\n body: {\n error:\n `This starter has ${pages} pages; your plan includes ${input.pagesAllowed}. ` +\n 'Pick a smaller starter or upgrade in Billing.',\n },\n }\n }\n return null\n}\n"],"names":["artifactCreateListKeys","createResourceUid","SCREEN_ROOT_PATH","starterLinksById","planSiteStarterTheme","encodeStoredNodes","THEME_LIBRARY_COLLECTION","listServerThemePresets","FieldValue","isRecord","value","Array","isArray","text","trim","storedNodes","nodes","packed","Buffer","from","siteStarterWrites","install","Object","now","serverTimestamp","payload","pages","screens","filter","map","screen","id","versionId","layoutId","layoutVersionId","routing","slugToId","routed","Set","page","slug","add","homeScreenId","keys","find","isRouted","has","fields","displayName","description","seo","publishedAt","createdAt","updatedAt","version","screenId","source","layout","layoutFields","layoutDescription","layoutNodes","props","length","theme","presets","listing","newId","host","themeEntries","entries","queueSiteStarterWrites","tx","hostRef","hostId","writes","pageRef","collection","doc","set","layoutRef","library","entry","op","data","LISTING_ID","LISTING_VERSION","readSiteStarterChoice","listingId","test","pinned","undefined","String","siteStarterPickRefusal","resolved","input","status","body","error","includes","code","priceUsd","mode","pagesAllowed"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,gBAAgB,QAAQ,qCAAoC;AAKrE,SAASC,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,4CAA2C;AAChF,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SACEC,wBAAwB,QAEnB,uCAAsC;AAC7C,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,UAAU,QAGL,2BAA0B;AAoDjC,MAAMC,WAAW,CAACC,QAChB,CAAC,CAACA,SAAS,OAAOA,UAAU,YAAY,CAACC,MAAMC,OAAO,CAACF;AAEzD,MAAMG,OAAO,CAACH,QACZ,OAAOA,UAAU,WAAWA,MAAMI,IAAI,KAAK;AAE7C,2FAA2F,GAC3F,SAASC,YAAYC,KAA8B;IACjD,MAAMC,SAASZ,kBAAkBW;IACjC,OAAOC,SAASC,OAAOC,IAAI,CAACF,UAAUD;AACxC;AAEA;;;CAGC,GACD,OAAO,SAASI,kBAAkBC,OAA2B;QA2BzDC;IA1BF,MAAMC,MAAM,IAAMf,WAAWgB,eAAe;IAC5C,MAAMC,UAAUJ,QAAQI,OAAO;IAC/B,MAAMC,QAAQ,AAACf,CAAAA,MAAMC,OAAO,CAACa,QAAQE,OAAO,IAAIF,QAAQE,OAAO,GAAG,EAAE,AAAD,EAChEC,MAAM,CAACnB,UACPoB,GAAG,CAAC,CAACC,SAAY,CAAA;YAAEA;YAAQC,IAAI9B;YAAqB+B,WAAW/B;QAAoB,CAAA;IACtF,MAAMgC,WAAWhC;IACjB,MAAMiC,kBAAkBjC;IAExB,qEAAqE;IACrE,sEAAsE;IACtE,8DAA8D;IAC9D,MAAMkC,UAAkC,CAAC;IACzC,MAAMC,WAAmC,CAAC;IAC1C,MAAMC,SAA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AAO;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/provision-starter.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 { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { SCREEN_ROOT_PATH } from '@aglyn/aglyn/app-utils/screen-slug'\nimport type {\n SiteStarterChoice,\n SiteStarterPayload,\n} from '@aglyn/aglyn/app-utils/site-starter'\nimport { starterLinksById } from '@aglyn/aglyn/app-utils/site-starter-links'\nimport { planSiteStarterTheme } from '@aglyn/aglyn/app-utils/site-starter-theme'\nimport { encodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport {\n THEME_LIBRARY_COLLECTION,\n type ThemeLibraryEntryWrite,\n} from '@aglyn/aglyn/app-utils/theme-library'\nimport { listServerThemePresets } from '@aglyn/aglyn/plugin-manager/plugin-theme-presets'\nimport {\n FieldValue,\n type DocumentReference,\n type Transaction,\n} from 'firebase-admin/firestore'\n\n/**\n * A site created from a site starter (AGL-4049): the starter twin of the\n * default site's writes (`defaultSiteWrites` and `queueStarterPages` in the\n * console's `provision-host.ts`), written by the same create transaction.\n *\n * Every page the starter carries becomes a page of the new site, its first\n * version holding the starter's nodes; the shared layout becomes the site's\n * header and footer, and every page sits in it; the theme is planned against\n * the empty host (`planSiteStarterTheme`). A page routed in the starter is\n * routed and published on the new site, and the Home page at `/` is named\n * `defaultHomeScreenId`: the platform-made page the owner's own home page\n * replaces (AGL-3478). A page with no address, or one the starter marks\n * unpublished, is a draft.\n *\n * Nodes are copied as published. A link to another page travels by slug in\n * the starter (`site-starter-links.ts`) and becomes the new page's id here;\n * a token such as `{{host.businessName}}` renders per site on its own, so\n * nothing is substituted.\n */\n\n/** A starter resolved for a create: its payload, and the listing it came from. */\nexport interface SiteStarterInstall {\n payload: SiteStarterPayload\n /**\n * The listing it came from. `kind` is the kind of site the listing names\n * (AGL-4049), which the site records over the one its stored pages carry:\n * a listing's kind is kept current by its publisher and by staff.\n */\n listing: { listingId: string; version: string | number; displayName: string; kind?: string | null }\n}\n\n/** Every document a starter's site is born with, ids minted, ready to queue. */\nexport interface SiteStarterWrites {\n /** The Home page at `/`; `null` only for a payload that failed its check. */\n homeScreenId: string | null\n /** Every published page: screen id → slug, the host's `screens` map. */\n routing: Record<string, string>\n screens: Array<{\n id: string\n versionId: string\n screen: Record<string, unknown>\n version: Record<string, unknown>\n }>\n layout: {\n id: string\n versionId: string\n layout: Record<string, unknown>\n version: Record<string, unknown>\n }\n /** Theme fields for the host's create, from `planSiteStarterTheme`. */\n host: Record<string, unknown>\n /** Theme library entries to create under the host. */\n themeEntries: ThemeLibraryEntryWrite[]\n}\n\nconst isRecord = (value: unknown): value is Record<string, any> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n\nconst text = (value: unknown): string =>\n typeof value === 'string' ? value.trim() : ''\n\n/** Nodes as a version stores them: msgpack at rest, as `/api/hosts/versions` writes them. */\nfunction storedNodes(nodes: Record<string, unknown>): unknown {\n const packed = encodeStoredNodes(nodes)\n return packed ? Buffer.from(packed) : nodes\n}\n\n/**\n * The documents a site created from `install` starts with, every id minted:\n * the pages' ids first, so each page's links and the layout's can name them.\n */\nexport function siteStarterWrites(install: SiteStarterInstall): SiteStarterWrites {\n const now = () => FieldValue.serverTimestamp()\n const payload = install.payload\n const pages = (Array.isArray(payload.screens) ? payload.screens : [])\n .filter(isRecord)\n .map((screen) => ({ screen, id: createResourceUid(), versionId: createResourceUid() }))\n const layoutId = createResourceUid()\n const layoutVersionId = createResourceUid()\n\n // Routed: a page with an address that is not marked unpublished, the\n // first to claim an address keeping it. Links resolve to routed pages\n // first, then to a draft that names an address nobody routes.\n const routing: Record<string, string> = {}\n const slugToId: Record<string, string> = {}\n const routed = new Set<string>()\n for (const page of pages) {\n const slug = text(page.screen['slug'])\n if (!slug || page.screen['published'] === false || slug in slugToId) continue\n routing[page.id] = slug\n slugToId[slug] = page.id\n routed.add(page.id)\n }\n for (const page of pages) {\n const slug = text(page.screen['slug'])\n if (slug && !(slug in slugToId)) slugToId[slug] = page.id\n }\n const homeScreenId =\n Object.keys(routing).find((id) => routing[id] === SCREEN_ROOT_PATH) ?? null\n\n const screens = pages.map(({ screen, id, versionId }) => {\n const isRouted = routed.has(id)\n const fields = {\n displayName: text(screen['displayName']) || 'Page',\n ...(isRouted ? { slug: routing[id] } : {}),\n versionId,\n }\n const description = text(screen['description'])\n const nodes = starterLinksById(isRecord(screen['nodes']) ? screen['nodes'] : {}, slugToId)\n return {\n id,\n versionId,\n screen: {\n ...fields,\n ...artifactCreateListKeys('screens', fields),\n layoutId,\n ...(isRecord(screen['seo']) ? { seo: screen['seo'] } : {}),\n ...(description ? { description } : {}),\n // What `publishScreenRoute` stamps, so the console lists a routed\n // page as Published rather than as a draft that happens to be served.\n ...(isRouted ? { publishedAt: now() } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n version: {\n screenId: id,\n displayName: 'Initial version',\n nodes: storedNodes(nodes),\n createdAt: now(),\n updatedAt: now(),\n },\n }\n })\n\n const source = isRecord(payload.layout) ? payload.layout : {}\n const layoutFields = {\n displayName: text(source['displayName']) || 'Site header and footer',\n versionId: layoutVersionId,\n }\n const layoutDescription = text(source['description'])\n const layoutNodes = starterLinksById(isRecord(source['nodes']) ? source['nodes'] : {}, slugToId)\n const props = Array.isArray(source['props']) && source['props'].length ? source['props'] : null\n\n const theme = planSiteStarterTheme({\n theme: payload.theme,\n presets: listServerThemePresets(),\n listing: install.listing,\n newId: createResourceUid,\n })\n\n return {\n homeScreenId,\n routing,\n screens,\n layout: {\n id: layoutId,\n versionId: layoutVersionId,\n layout: {\n ...layoutFields,\n ...artifactCreateListKeys('layouts', layoutFields),\n ...(layoutDescription ? { description: layoutDescription } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n version: {\n layoutId,\n displayName: 'Initial version',\n nodes: storedNodes(layoutNodes),\n // The properties the layout's tree binds to (AGL-2932), on the\n // version it is served from, as Use template writes them.\n ...(props ? { props } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n },\n host: theme.host,\n themeEntries: theme.entries,\n }\n}\n\n/**\n * Queues a starter's documents in the create transaction: every page and its\n * first version, the layout and its first version (which carries the host\n * id, as the default layout's does), and the theme library entries. An empty\n * host's theme plan creates entries and nothing else, so a create is all a\n * new site's library takes.\n */\nexport function queueSiteStarterWrites(\n tx: Transaction,\n hostRef: DocumentReference,\n hostId: string,\n writes: SiteStarterWrites,\n): void {\n for (const page of writes.screens) {\n const pageRef = hostRef.collection('screens').doc(page.id)\n tx.set(pageRef, page.screen)\n tx.set(pageRef.collection('versions').doc(page.versionId), page.version)\n }\n const layoutRef = hostRef.collection('layouts').doc(writes.layout.id)\n tx.set(layoutRef, writes.layout.layout)\n tx.set(layoutRef.collection('versions').doc(writes.layout.versionId), {\n ...writes.layout.version,\n hostId,\n })\n const library = hostRef.collection(THEME_LIBRARY_COLLECTION)\n for (const entry of writes.themeEntries) {\n if (entry.op !== 'create') continue\n tx.set(library.doc(entry.id), {\n ...(entry.data as unknown as Record<string, unknown>),\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n}\n\n/** A listing id as a document id may be one: no path separator, nothing reserved. */\nconst LISTING_ID = /^[A-Za-z0-9_-]{1,128}$/\n/** A pinned version: the number of one of the listing's versions. */\nconst LISTING_VERSION = /^[1-9][0-9]{0,8}$/\n\n/**\n * A create request's starter pick (`body.starter`), or `null` when it is not\n * one: an object naming a listing id, and optionally the version it pins.\n * The id becomes a document path on the way to the listing, so anything that\n * could name another document is not a pick.\n */\nexport function readSiteStarterChoice(value: unknown): SiteStarterChoice | null {\n if (!isRecord(value)) return null\n const listingId = text(value['listingId'])\n if (!LISTING_ID.test(listingId) || /^__.*__$/.test(listingId)) return null\n const pinned = value['version']\n if (pinned === undefined || pinned === null) return { listingId }\n const version = typeof pinned === 'number' ? String(pinned) : text(pinned)\n return LISTING_VERSION.test(version) ? { listingId, version } : null\n}\n\n/** The answer a create gives a starter pick it refuses: a status and its JSON body. */\nexport interface SiteStarterPickRefusal {\n status: number\n body: Record<string, unknown>\n}\n\n/**\n * Why a create refuses the starter it was asked for, or `null` when the\n * site can be created from it (AGL-4049). Every refusal is decided before the\n * site exists, so a refused pick creates nothing, and a 402 is answered with\n * what the person needs to buy it: the listing and its price. Once bought,\n * the same request again creates the site. Every refusal names the listing\n * it refused, so Create site can tell a refused pick from a refused name.\n *\n * `resolved` is what the starter source answered; `pagesAllowed` is the\n * plan's `screensPerHost`.\n */\nexport function siteStarterPickRefusal(\n resolved: SiteStarterPayload | { error: string; status: 402 | 403 | 404; priceUsd?: number },\n input: { listingId: string; pagesAllowed: number },\n): SiteStarterPickRefusal | null {\n if (!isRecord(resolved)) {\n return { status: 404, body: { error: 'That starter is no longer available', listingId: input.listingId } }\n }\n if ('error' in resolved) {\n const status = [402, 403, 404].includes(resolved.status) ? resolved.status : 404\n return {\n status,\n body: {\n error: resolved.error,\n ...(status === 402 ? { code: 'purchase_required' } : {}),\n listingId: input.listingId,\n ...(typeof resolved.priceUsd === 'number' ? { priceUsd: resolved.priceUsd } : {}),\n },\n }\n }\n if (resolved.mode === 'ai') {\n return {\n status: 409,\n body: { error: 'This starter needs the AI start, which is coming soon', listingId: input.listingId },\n }\n }\n const pages = Array.isArray(resolved.screens) ? resolved.screens.length : 0\n if (pages > input.pagesAllowed) {\n return {\n status: 403,\n body: {\n error:\n `This starter has ${pages} pages; your plan includes ${input.pagesAllowed}. ` +\n 'Pick a smaller starter or upgrade in Billing.',\n listingId: input.listingId,\n },\n }\n }\n return null\n}\n"],"names":["artifactCreateListKeys","createResourceUid","SCREEN_ROOT_PATH","starterLinksById","planSiteStarterTheme","encodeStoredNodes","THEME_LIBRARY_COLLECTION","listServerThemePresets","FieldValue","isRecord","value","Array","isArray","text","trim","storedNodes","nodes","packed","Buffer","from","siteStarterWrites","install","Object","now","serverTimestamp","payload","pages","screens","filter","map","screen","id","versionId","layoutId","layoutVersionId","routing","slugToId","routed","Set","page","slug","add","homeScreenId","keys","find","isRouted","has","fields","displayName","description","seo","publishedAt","createdAt","updatedAt","version","screenId","source","layout","layoutFields","layoutDescription","layoutNodes","props","length","theme","presets","listing","newId","host","themeEntries","entries","queueSiteStarterWrites","tx","hostRef","hostId","writes","pageRef","collection","doc","set","layoutRef","library","entry","op","data","LISTING_ID","LISTING_VERSION","readSiteStarterChoice","listingId","test","pinned","undefined","String","siteStarterPickRefusal","resolved","input","status","body","error","includes","code","priceUsd","mode","pagesAllowed"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,gBAAgB,QAAQ,qCAAoC;AAKrE,SAASC,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,4CAA2C;AAChF,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SACEC,wBAAwB,QAEnB,uCAAsC;AAC7C,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,UAAU,QAGL,2BAA0B;AAyDjC,MAAMC,WAAW,CAACC,QAChB,CAAC,CAACA,SAAS,OAAOA,UAAU,YAAY,CAACC,MAAMC,OAAO,CAACF;AAEzD,MAAMG,OAAO,CAACH,QACZ,OAAOA,UAAU,WAAWA,MAAMI,IAAI,KAAK;AAE7C,2FAA2F,GAC3F,SAASC,YAAYC,KAA8B;IACjD,MAAMC,SAASZ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F,WAAW,MAAM;gBAAEI,MAAM;YAAoB,IAAI,CAAC;gBACtDZ,WAAWO,MAAMP,SAAS;eACtB,OAAOM,SAASO,QAAQ,KAAK,WAAW;gBAAEA,UAAUP,SAASO,QAAQ;YAAC,IAAI,CAAC;QAEnF;IACF;IACA,IAAIP,SAASQ,IAAI,KAAK,MAAM;QAC1B,OAAO;YACLN,QAAQ;YACRC,MAAM;gBAAEC,OAAO;gBAAyDV,WAAWO,MAAMP,SAAS;YAAC;QACrG;IACF;IACA,MAAM7D,QAAQf,MAAMC,OAAO,CAACiF,SAASlE,OAAO,IAAIkE,SAASlE,OAAO,CAACmC,MAAM,GAAG;IAC1E,IAAIpC,QAAQoE,MAAMQ,YAAY,EAAE;QAC9B,OAAO;YACLP,QAAQ;YACRC,MAAM;gBACJC,OACE,CAAC,iBAAiB,EAAEvE,MAAM,2BAA2B,EAAEoE,MAAMQ,YAAY,CAAC,EAAE,CAAC,GAC7E;gBACFf,WAAWO,MAAMP,SAAS;YAC5B;QACF;IACF;IACA,OAAO;AACT"}
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import type { Writable } from 'node:stream';
18
18
  import { type VisitorUploadFile, type VisitorUploadKind, type VisitorUploadScope } from '@aglyn/aglyn/app-utils/visitor-upload';
19
+ import { type UploadStorageRefusal } from '@aglyn/aglyn/plugin-manager/plugin-upload-storage-gate';
19
20
  /** The few Storage calls this makes, so a spec can stand in for the bucket. */
20
21
  export interface VisitorUploadObject {
21
22
  generateSignedPostPolicyV4(options: {
@@ -48,11 +49,25 @@ export interface VisitorUploadObjectMetadata {
48
49
  contentType?: string;
49
50
  metadata?: Record<string, string | null | undefined> | null;
50
51
  }
52
+ /** An object as a listing answers it: its name, its metadata, and a way to delete it. */
53
+ export interface VisitorUploadListedObject {
54
+ name: string;
55
+ metadata?: VisitorUploadObjectMetadata | null;
56
+ delete(options?: {
57
+ ignoreNotFound?: boolean;
58
+ }): Promise<unknown>;
59
+ }
51
60
  export interface VisitorUploadBucket {
52
61
  file(path: string): VisitorUploadObject;
53
- deleteFiles(options: {
62
+ /** Every object under a prefix, with its metadata (Storage answers `[files, nextQuery, response]`). */
63
+ getFiles(options: {
54
64
  prefix: string;
55
- }): Promise<unknown>;
65
+ }): Promise<[VisitorUploadListedObject[], ...unknown[]]>;
66
+ }
67
+ /** How a kept file moves its site's storage counter: `+` when kept, `-` when deleted. */
68
+ export interface VisitorUploadStorageDelta {
69
+ bytes: number;
70
+ files: number;
56
71
  }
57
72
  export interface VisitorUploadDeps {
58
73
  bucket(): VisitorUploadBucket;
@@ -70,6 +85,20 @@ export interface VisitorUploadDeps {
70
85
  now(): number;
71
86
  /** A fresh upload id: a path segment no one can guess. */
72
87
  newId(): string;
88
+ /**
89
+ * Moves the site's storage counter (`hosts/{hostId}/counters/media`) by a
90
+ * kept file: its bytes in `bytes`, the figure every storage reader reads,
91
+ * and in the kept files' own share beside it.
92
+ */
93
+ countStorage(hostId: string, delta: VisitorUploadStorageDelta): Promise<void>;
94
+ /**
95
+ * The workspace's storage band, asked before a MEMBER's file is taken:
96
+ * `null` to take it. Never asked for a visitor's. Absent, the file is taken.
97
+ */
98
+ storageGate?(input: {
99
+ hostId: string;
100
+ bytes: number;
101
+ }): Promise<UploadStorageRefusal | null>;
73
102
  }
74
103
  export declare function defaultVisitorUploadDeps(): VisitorUploadDeps;
75
104
  /** One rate limit: so many in so long. */
@@ -101,7 +130,7 @@ export type VisitorUploadRefusal = {
101
130
  ok: false;
102
131
  status: number;
103
132
  error: string;
104
- code: 'type' | 'size' | 'empty' | 'scope' | 'rate' | 'paused' | 'ticket' | 'missing' | 'inspection' | 'unchecked';
133
+ code: 'type' | 'size' | 'empty' | 'scope' | 'rate' | 'paused' | 'storage' | 'ticket' | 'missing' | 'inspection' | 'unchecked';
105
134
  retryAfterSeconds?: number;
106
135
  };
107
136
  export interface VisitorUploadTicket {
@@ -124,9 +153,10 @@ export interface VisitorUploadTicket {
124
153
  /**
125
154
  * A ticket and a signed upload for ONE file, after the caller's route has
126
155
  * decided the caller may upload for `scope`. Spends the rate limits; refused
127
- * while the platform's uploads are paused. `maxBytes` narrows the 25 MB
128
- * ceiling, never widens it; `kinds` narrows the types taken (a form field
129
- * that asks for PDFs only), never widens them.
156
+ * while the platform's uploads are paused, and a member's file when the
157
+ * workspace's storage band refuses it (never a visitor's). `maxBytes`
158
+ * narrows the 25 MB ceiling, never widens it; `kinds` narrows the types
159
+ * taken (a form field that asks for PDFs only), never widens them.
130
160
  */
131
161
  export declare function mintVisitorUploadTicket(deps: VisitorUploadDeps, input: {
132
162
  scope: VisitorUploadScope;
@@ -151,10 +181,10 @@ export declare function finalizeVisitorUpload(deps: VisitorUploadDeps, input: {
151
181
  } | VisitorUploadRefusal>;
152
182
  /** A kept file's record, by its id within `scope`; null when there is none. */
153
183
  export declare function readVisitorUpload(deps: Pick<VisitorUploadDeps, 'bucket'>, scope: VisitorUploadScope, id: string): Promise<VisitorUploadFile | null>;
154
- /** Deletes one kept file. Gone already is fine. */
155
- export declare function deleteVisitorUpload(deps: Pick<VisitorUploadDeps, 'bucket'>, path: string): Promise<void>;
156
- /** Deletes every kept file of one purpose and record. */
157
- export declare function deleteVisitorUploads(deps: Pick<VisitorUploadDeps, 'bucket'>, scope: VisitorUploadScope): Promise<void>;
184
+ /** Deletes one kept file and releases its bytes. Gone already is fine. */
185
+ export declare function deleteVisitorUpload(deps: Pick<VisitorUploadDeps, 'bucket' | 'countStorage'>, path: string): Promise<void>;
186
+ /** Deletes every kept file of one purpose and record, and releases their bytes. */
187
+ export declare function deleteVisitorUploads(deps: Pick<VisitorUploadDeps, 'bucket' | 'countStorage'>, scope: VisitorUploadScope): Promise<void>;
158
188
  /** The headers a kept file is served with. */
159
189
  export declare function visitorUploadResponseHeaders(file: Pick<VisitorUploadFile, 'name' | 'contentType'>): Record<string, string>;
160
190
  /** The response a gated route streams a kept file into. */
@@ -18,7 +18,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { pipeline } from "node:stream/promises";
19
19
  import { inspectUploadBytes, UPLOAD_INSPECTION_HEAD_BYTES } from "@aglyn/aglyn/app-utils/upload-inspection";
20
20
  import { isSvgUploadType, sanitizeSvgBuffer } from "@aglyn/aglyn/app-utils/sanitize-svg";
21
- import { checkVisitorUploadRequest, isVisitorUploadScope, isVisitorUploadSegment, visitorUploadFinalPath, visitorUploadFolder, visitorUploadIsInline, visitorUploadPendingPath, visitorUploadTypeOf, VISITOR_UPLOAD_MAX_BYTES, VISITOR_UPLOAD_TICKET_TTL_MS } from "@aglyn/aglyn/app-utils/visitor-upload";
21
+ import { checkVisitorUploadRequest, isVisitorUploadScope, isVisitorUploadSegment, visitorUploadFinalPath, visitorUploadFolder, visitorUploadIsInline, visitorUploadPendingPath, visitorUploadTypeOf, VISITOR_UPLOAD_COUNTER_BYTES, VISITOR_UPLOAD_COUNTER_FILES, VISITOR_UPLOAD_MAX_BYTES, VISITOR_UPLOAD_TICKET_TTL_MS } from "@aglyn/aglyn/app-utils/visitor-upload";
22
+ import { uploadStorageGate } from "@aglyn/aglyn/plugin-manager/plugin-upload-storage-gate";
22
23
  import firebaseAdmin from "./firebase-admin.js";
23
24
  import { featureLockdownRefusal } from "./lockdown.js";
24
25
  import { consumeRateLimit } from "./rate-limit-store.js";
@@ -37,7 +38,24 @@ export function defaultVisitorUploadDeps() {
37
38
  return secret;
38
39
  },
39
40
  now: ()=>Date.now(),
40
- newId: ()=>randomBytes(12).toString('hex')
41
+ newId: ()=>randomBytes(12).toString('hex'),
42
+ countStorage: async (hostId, delta)=>{
43
+ const increment = firebaseAdmin.firestore.FieldValue.increment;
44
+ await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('counters').doc('media').set({
45
+ bytes: increment(delta.bytes),
46
+ [VISITOR_UPLOAD_COUNTER_BYTES]: increment(delta.bytes),
47
+ [VISITOR_UPLOAD_COUNTER_FILES]: increment(delta.files)
48
+ }, {
49
+ merge: true
50
+ });
51
+ },
52
+ // The console registers the band (`core.upload-storage-gate`); the site
53
+ // app registers none and never takes a member's file.
54
+ storageGate: async (input)=>{
55
+ var _ref;
56
+ var _uploadStorageGate;
57
+ return (_ref = await ((_uploadStorageGate = uploadStorageGate()) == null ? void 0 : _uploadStorageGate.check(input))) != null ? _ref : null;
58
+ }
41
59
  };
42
60
  }
43
61
  /**
@@ -97,9 +115,10 @@ function mintTicket(secret, payload) {
97
115
  /**
98
116
  * A ticket and a signed upload for ONE file, after the caller's route has
99
117
  * decided the caller may upload for `scope`. Spends the rate limits; refused
100
- * while the platform's uploads are paused. `maxBytes` narrows the 25 MB
101
- * ceiling, never widens it; `kinds` narrows the types taken (a form field
102
- * that asks for PDFs only), never widens them.
118
+ * while the platform's uploads are paused, and a member's file when the
119
+ * workspace's storage band refuses it (never a visitor's). `maxBytes`
120
+ * narrows the 25 MB ceiling, never widens it; `kinds` narrows the types
121
+ * taken (a form field that asks for PDFs only), never widens them.
103
122
  */ export async function mintVisitorUploadTicket(deps, input) {
104
123
  var _input_limits;
105
124
  const { scope } = input;
@@ -112,6 +131,15 @@ function mintTicket(secret, payload) {
112
131
  if (await deps.uploadsPaused()) {
113
132
  return refusal(423, 'paused', 'Uploads are paused for a moment. Try again a little later.');
114
133
  }
134
+ // A member's file meets the storage band a library upload meets; a
135
+ // visitor's is never refused for the business's storage (see STORAGE).
136
+ if ('uid' in input.caller && deps.storageGate) {
137
+ const full = await deps.storageGate({
138
+ hostId: scope.hostId,
139
+ bytes: checked.upload.size
140
+ });
141
+ if (full) return refusal(full.status, 'storage', full.error);
142
+ }
115
143
  const limits = (_input_limits = input.limits) != null ? _input_limits : VISITOR_UPLOAD_LIMITS;
116
144
  for (const [key, rate] of [
117
145
  [
@@ -176,14 +204,43 @@ function mintTicket(secret, payload) {
176
204
  /*------------------------------------------
177
205
  * Finalize
178
206
  *-----------------------------------------*/ const first = (answer)=>answer[0];
207
+ /**
208
+ * The custom metadata key a kept file carries once its bytes are in its
209
+ * site's storage counter. A file kept before files were counted has none, so
210
+ * deleting it releases nothing it never added.
211
+ */ const STORAGE_COUNTED = 'storageCounted';
179
212
  /** The custom metadata a kept file carries, which is how its record is read back. */ function keptMetadata(name, uploadedAtMs) {
180
213
  return {
181
214
  name,
182
215
  uploadedAtMs: String(uploadedAtMs),
183
216
  // Never a download token: nothing but the Admin SDK reads the object.
184
- firebaseStorageDownloadTokens: null
217
+ firebaseStorageDownloadTokens: null,
218
+ [STORAGE_COUNTED]: '1'
185
219
  };
186
220
  }
221
+ /**
222
+ * Adds a file just kept to its site's storage. Never the uploader's problem:
223
+ * the file stays kept whatever the counter does, and if the counter could
224
+ * not be moved the file's mark comes off, so deleting it later releases
225
+ * nothing it never added.
226
+ */ async function countKept(deps, hostId, size, kept) {
227
+ try {
228
+ await deps.countStorage(hostId, {
229
+ bytes: size,
230
+ files: 1
231
+ });
232
+ } catch (error) {
233
+ console.error('a kept upload was not counted toward storage', {
234
+ hostId,
235
+ error
236
+ });
237
+ await kept.setMetadata({
238
+ metadata: {
239
+ [STORAGE_COUNTED]: null
240
+ }
241
+ }).catch(()=>undefined);
242
+ }
243
+ }
187
244
  /** A kept file's record from its object's metadata, or null when it is not one. */ function recordFromMetadata(path, id, metadata) {
188
245
  var _metadata_contentType, _ref;
189
246
  var _metadata_metadata, _metadata_metadata1;
@@ -285,6 +342,7 @@ function mintTicket(secret, payload) {
285
342
  await pending.delete({
286
343
  ignoreNotFound: true
287
344
  }).catch(()=>undefined);
345
+ await countKept(deps, scope.hostId, sanitized.buffer.length, kept);
288
346
  return {
289
347
  ok: true,
290
348
  file: {
@@ -303,6 +361,7 @@ function mintTicket(secret, payload) {
303
361
  contentDisposition: disposition,
304
362
  metadata: keptMetadata(ticket.n, uploadedAtMs)
305
363
  });
364
+ await countKept(deps, scope.hostId, size, kept);
306
365
  return {
307
366
  ok: true,
308
367
  file: {
@@ -324,17 +383,70 @@ function mintTicket(secret, payload) {
324
383
  if (!first(await file.exists())) return null;
325
384
  return recordFromMetadata(path, id, first(await file.getMetadata()));
326
385
  }
327
- /** Deletes one kept file. Gone already is fine. */ export async function deleteVisitorUpload(deps, path) {
386
+ const isNotFound = (error)=>Number(error == null ? void 0 : error.code) === 404;
387
+ /** Deletes one object; true only when this call is the one that removed it. */ async function deleteObject(object) {
388
+ try {
389
+ await object.delete();
390
+ return true;
391
+ } catch (error) {
392
+ if (isNotFound(error)) return false;
393
+ throw error;
394
+ }
395
+ }
396
+ /**
397
+ * Takes deleted files' bytes off their site's storage: the ones that were
398
+ * counted, by the size each was kept at. Never throws, so a counter that
399
+ * could not be moved never fails the delete it follows.
400
+ */ async function releaseCounted(deps, hostId, deleted) {
401
+ let bytes = 0;
402
+ let files = 0;
403
+ for (const metadata of deleted){
404
+ var _metadata_metadata;
405
+ if ((metadata == null ? void 0 : (_metadata_metadata = metadata.metadata) == null ? void 0 : _metadata_metadata[STORAGE_COUNTED]) !== '1') continue;
406
+ const size = Number(metadata.size);
407
+ if (!Number.isSafeInteger(size) || size <= 0) continue;
408
+ bytes += size;
409
+ files += 1;
410
+ }
411
+ if (!files) return;
412
+ try {
413
+ await deps.countStorage(hostId, {
414
+ bytes: -bytes,
415
+ files: -files
416
+ });
417
+ } catch (error) {
418
+ console.error('deleted uploads were not taken off storage', {
419
+ hostId,
420
+ bytes,
421
+ files,
422
+ error
423
+ });
424
+ }
425
+ }
426
+ /** Deletes one kept file and releases its bytes. Gone already is fine. */ export async function deleteVisitorUpload(deps, path) {
427
+ var _path_split_;
328
428
  if (!path.startsWith('hosts/') || !path.includes('/private/uploads/')) return;
329
- await deps.bucket().file(path).delete({
330
- ignoreNotFound: true
331
- });
429
+ const hostId = (_path_split_ = path.split('/')[1]) != null ? _path_split_ : '';
430
+ if (!isVisitorUploadSegment(hostId)) return;
431
+ const file = deps.bucket().file(path);
432
+ let metadata;
433
+ try {
434
+ metadata = first(await file.getMetadata());
435
+ } catch (error) {
436
+ if (isNotFound(error)) return;
437
+ throw error;
438
+ }
439
+ if (await deleteObject(file)) await releaseCounted(deps, hostId, [
440
+ metadata
441
+ ]);
332
442
  }
333
- /** Deletes every kept file of one purpose and record. */ export async function deleteVisitorUploads(deps, scope) {
443
+ /** Deletes every kept file of one purpose and record, and releases their bytes. */ export async function deleteVisitorUploads(deps, scope) {
334
444
  if (!isVisitorUploadScope(scope)) return;
335
- await deps.bucket().deleteFiles({
445
+ const [listed = []] = await deps.bucket().getFiles({
336
446
  prefix: visitorUploadFolder(scope)
337
447
  });
448
+ const deleted = await Promise.all(listed.map(async (object)=>await deleteObject(object) ? object.metadata : null));
449
+ await releaseCounted(deps, scope.hostId, deleted);
338
450
  }
339
451
  /** An ASCII stand-in for a header, and the real name encoded beside it. */ function contentDisposition(name, contentType) {
340
452
  const ascii = name.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_') || 'file';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/visitor-upload.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 { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\nimport { pipeline } from 'node:stream/promises'\nimport type { Writable } from 'node:stream'\nimport {\n inspectUploadBytes,\n UPLOAD_INSPECTION_HEAD_BYTES,\n} from '@aglyn/aglyn/app-utils/upload-inspection'\nimport { isSvgUploadType, sanitizeSvgBuffer } from '@aglyn/aglyn/app-utils/sanitize-svg'\nimport {\n checkVisitorUploadRequest,\n isVisitorUploadScope,\n isVisitorUploadSegment,\n visitorUploadFinalPath,\n visitorUploadFolder,\n visitorUploadIsInline,\n visitorUploadPendingPath,\n visitorUploadTypeOf,\n VISITOR_UPLOAD_MAX_BYTES,\n VISITOR_UPLOAD_TICKET_TTL_MS,\n type VisitorUploadFile,\n type VisitorUploadKind,\n type VisitorUploadScope,\n} from '@aglyn/aglyn/app-utils/visitor-upload'\nimport firebaseAdmin from './firebase-admin'\nimport { featureLockdownRefusal } from './lockdown'\nimport { consumeRateLimit } from './rate-limit-store'\n\n/*==========================================\n * TAKING A FILE FROM A SITE'S VISITOR, OR A MEMBER (AGL-4096).\n *\n * Two calls a plugin's own routes make, after deciding for themselves who may\n * upload for what (a quote's signed link, a form's binding, a member's key):\n *\n * mintVisitorUploadTicket → a TICKET and a signed upload for one file of a\n * declared name, type and size, to a PENDING\n * path scoped to (site, purpose, record);\n * finalizeVisitorUpload → reads what arrived there, checks its size and\n * bytes (`inspectUploadBytes`), strips script\n * from an SVG, moves it to the record's private\n * folder and answers its {@link VisitorUploadFile}.\n *\n * And three for afterwards: {@link readVisitorUpload} (a kept file's record,\n * by id, so a later submit names files by id and nothing else),\n * {@link sendVisitorUploadFile} (serve one through a gated route) and\n * {@link deleteVisitorUpload} / {@link deleteVisitorUploads}.\n *\n * THE UPLOAD IS A SIGNED POST POLICY, not a signed PUT URL. A site lives on\n * any domain, and the bucket's cross-origin list names the console's\n * addresses one by one and never `*` (AGL-1452), so a browser on a\n * customer's domain could not make the PUT. A form post needs no such\n * permission. The policy binds the exact object, the type and the size range\n * and lapses after {@link VISITOR_UPLOAD_TICKET_TTL_MS}, so Storage itself\n * refuses anything else; finalize then checks again, because the bytes are\n * what matter.\n *\n * THE TICKET is `<payload>.<signature>`: the scope, the upload's id, its\n * type, size and name and when it lapses, HMAC-signed under\n * `TOKEN_SIGNING_SECRET` with a `visitor-upload:` prefix so it cannot be\n * replayed as any other token. Nothing is stored per ticket. It is an\n * internal handle for the seconds between upload and finalize, never a state\n * anyone sees.\n *\n * WHAT IS NEVER FINALIZED is deleted by the bucket's lifecycle a day after it\n * arrived: `visitor-uploads-pending/` in `cloud/media-bucket-lifecycle.json`.\n * A refused finalize deletes its object at once.\n *\n * THE KEPT FILE has no download token and lives under `hosts/{hostId}/private/`,\n * so only the Admin SDK reads it, the site's erasure deletes it with the\n * site, and a route that checked the caller serves it\n * ({@link sendVisitorUploadFile}: `nosniff`, a sandboxing CSP, and\n * `attachment` for everything but the raster images a browser draws safely).\n *\n * Abuse: each ticket spends a per-caller and a per-site rate limit, the\n * platform's uploads pause (`uploads` lockdown feature) refuses new tickets,\n * and the plugin route sits behind the site dispatcher's cross-origin check,\n * lockdown and visitor-write limit.\n *=========================================*/\n\n/** The few Storage calls this makes, so a spec can stand in for the bucket. */\nexport interface VisitorUploadObject {\n generateSignedPostPolicyV4(options: {\n expires: number\n conditions?: unknown[]\n fields?: Record<string, string>\n }): Promise<[{ url: string; fields: Record<string, string> }] | Array<{ url: string; fields: Record<string, string> }>>\n exists(): Promise<[boolean] | boolean[]>\n getMetadata(): Promise<[VisitorUploadObjectMetadata] | VisitorUploadObjectMetadata[]>\n download(options?: { start?: number; end?: number }): Promise<[Buffer] | Buffer[]>\n save(data: Buffer, options: Record<string, unknown>): Promise<unknown>\n move(destination: string): Promise<unknown>\n setMetadata(metadata: Record<string, unknown>): Promise<unknown>\n delete(options?: { ignoreNotFound?: boolean }): Promise<unknown>\n createReadStream(): NodeJS.ReadableStream\n}\n\nexport interface VisitorUploadObjectMetadata {\n size?: string | number\n contentType?: string\n metadata?: Record<string, string | null | undefined> | null\n}\n\nexport interface VisitorUploadBucket {\n file(path: string): VisitorUploadObject\n deleteFiles(options: { prefix: string }): Promise<unknown>\n}\n\nexport interface VisitorUploadDeps {\n bucket(): VisitorUploadBucket\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean; resetMs: number }>\n /** Whether the platform's uploads pause (`uploads` lockdown feature) is on. */\n uploadsPaused(): Promise<boolean>\n /** The secret tickets are signed with. Throws when none is configured. */\n secret(): string\n now(): number\n /** A fresh upload id: a path segment no one can guess. */\n newId(): string\n}\n\nexport function defaultVisitorUploadDeps(): VisitorUploadDeps {\n return {\n // The bucket the site's `connect-src` admits by name (`security-origins.js`,\n // `visitorUploadConnectSource`), so the browser's post is allowed to leave.\n bucket: () =>\n firebaseAdmin\n .app()\n .storage()\n .bucket(process.env['NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET'] || undefined) as unknown as VisitorUploadBucket,\n consumeRateLimit: (key, options) => consumeRateLimit(key, options),\n uploadsPaused: async () => (await featureLockdownRefusal({ feature: 'uploads' })) !== null,\n secret: () => {\n const secret = process.env['TOKEN_SIGNING_SECRET']\n if (!secret) throw new Error('TOKEN_SIGNING_SECRET is not configured')\n return secret\n },\n now: () => Date.now(),\n newId: () => randomBytes(12).toString('hex'),\n }\n}\n\n/** One rate limit: so many in so long. */\nexport interface VisitorUploadRate {\n limit: number\n windowMs: number\n}\n\n/** The limits a ticket spends, per caller on a site and per site. */\nexport interface VisitorUploadLimits {\n perCaller: VisitorUploadRate\n perSite: VisitorUploadRate\n}\n\n/**\n * Tickets per caller on one site: 30 in ten minutes is three full\n * submissions of ten files; per site, 300 an hour across everyone.\n */\nexport const VISITOR_UPLOAD_LIMITS: VisitorUploadLimits = {\n perCaller: { limit: 30, windowMs: 10 * 60_000 },\n perSite: { limit: 300, windowMs: 60 * 60_000 },\n}\n\n/** Finalizes per caller on one site, per ten minutes: a retry or two per ticket. */\nexport const VISITOR_UPLOAD_FINALIZE_LIMIT: VisitorUploadRate = { limit: 60, windowMs: 10 * 60_000 }\n\n/** How long after its upload lapses a ticket may still be finalized: a slow connection's last bytes. */\nexport const VISITOR_UPLOAD_FINALIZE_GRACE_MS = 60 * 60_000\n\n/** Who is uploading: an address for a visitor, a uid for a member. Keys the per-caller limit. */\nexport type VisitorUploadCaller = { ip: string } | { uid: string }\n\nexport type VisitorUploadRefusal = {\n ok: false\n status: number\n error: string\n code: 'type' | 'size' | 'empty' | 'scope' | 'rate' | 'paused' | 'ticket' | 'missing' | 'inspection' | 'unchecked'\n retryAfterSeconds?: number\n}\n\nconst refusal = (\n status: number,\n code: VisitorUploadRefusal['code'],\n error: string,\n extra: Partial<VisitorUploadRefusal> = {},\n): VisitorUploadRefusal => ({ ok: false, status, code, error, ...extra })\n\nconst callerKey = (caller: VisitorUploadCaller) => ('uid' in caller ? `uid:${caller.uid}` : `ip:${caller.ip || 'no-address'}`)\n\n/*------------------------------------------\n * The ticket\n *-----------------------------------------*/\n\ninterface TicketPayload {\n h: string\n p: string\n i: string\n u: string\n t: string\n s: number\n n: string\n e: number\n}\n\nfunction signTicket(secret: string, payload: string): string {\n return createHmac('sha256', secret).update(`visitor-upload:${payload}`).digest('base64url')\n}\n\nfunction mintTicket(secret: string, payload: TicketPayload): string {\n const encoded = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')\n return `${encoded}.${signTicket(secret, encoded)}`\n}\n\n/** A ticket's payload when its signature holds, else null. Expiry is the caller's to judge. */\nfunction readTicket(secret: string, ticket: unknown): TicketPayload | null {\n if (typeof ticket !== 'string' || ticket.length > 2_000) return null\n const separator = ticket.lastIndexOf('.')\n if (separator <= 0) return null\n const encoded = ticket.slice(0, separator)\n const presented = Buffer.from(ticket.slice(separator + 1))\n const expected = Buffer.from(signTicket(secret, encoded))\n if (presented.length !== expected.length || !timingSafeEqual(presented, expected)) return null\n try {\n const payload = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as TicketPayload\n if (\n !isVisitorUploadScope({ hostId: payload.h, purpose: payload.p, purposeId: payload.i }) ||\n !isVisitorUploadSegment(payload.u) ||\n !visitorUploadTypeOf(String(payload.t)) ||\n !Number.isSafeInteger(payload.s) ||\n typeof payload.n !== 'string' ||\n !Number.isSafeInteger(payload.e)\n ) {\n return null\n }\n return payload\n } catch {\n return null\n }\n}\n\n/*------------------------------------------\n * Mint\n *-----------------------------------------*/\n\nexport interface VisitorUploadTicket {\n ok: true\n /** Handed back to finalize. */\n ticket: string\n /** The signed form post: where, and the fields that go before the file. */\n upload: { url: string; fields: Record<string, string> }\n /** The file as it will be kept. */\n file: { id: string; name: string; contentType: string; size: number }\n}\n\n/**\n * A ticket and a signed upload for ONE file, after the caller's route has\n * decided the caller may upload for `scope`. Spends the rate limits; refused\n * while the platform's uploads are paused. `maxBytes` narrows the 25 MB\n * ceiling, never widens it; `kinds` narrows the types taken (a form field\n * that asks for PDFs only), never widens them.\n */\nexport async function mintVisitorUploadTicket(\n deps: VisitorUploadDeps,\n input: {\n scope: VisitorUploadScope\n request: unknown\n caller: VisitorUploadCaller\n limits?: VisitorUploadLimits\n maxBytes?: number\n kinds?: readonly VisitorUploadKind[]\n },\n): Promise<VisitorUploadTicket | VisitorUploadRefusal> {\n const { scope } = input\n if (!isVisitorUploadScope(scope)) return refusal(400, 'scope', 'This upload is missing what it is for.')\n const checked = checkVisitorUploadRequest(input.request, { maxBytes: input.maxBytes, kinds: input.kinds })\n if ('error' in checked) return refusal(checked.code === 'size' ? 413 : 400, checked.code, checked.error)\n if (await deps.uploadsPaused()) {\n return refusal(423, 'paused', 'Uploads are paused for a moment. Try again a little later.')\n }\n const limits = input.limits ?? VISITOR_UPLOAD_LIMITS\n for (const [key, rate] of [\n [`visitor-upload:${scope.hostId}:${callerKey(input.caller)}`, limits.perCaller],\n [`visitor-upload-site:${scope.hostId}`, limits.perSite],\n ] as const) {\n const spent = await deps.consumeRateLimit(key, rate)\n if (!spent.allowed) {\n return refusal(429, 'rate', 'Too many files at once. Wait a few minutes and try again.', {\n retryAfterSeconds: Math.max(1, Math.ceil((spent.resetMs - deps.now()) / 1000)),\n })\n }\n }\n\n const { upload } = checked\n const id = deps.newId()\n const expiresAtMs = deps.now() + VISITOR_UPLOAD_TICKET_TTL_MS\n const answer = await deps\n .bucket()\n .file(visitorUploadPendingPath(scope, id))\n .generateSignedPostPolicyV4({\n expires: expiresAtMs,\n // Storage refuses a post of any other size, type or object: each\n // field below is also an exact-match condition of the policy.\n conditions: [['content-length-range', 1, upload.size]],\n fields: { 'Content-Type': upload.type.contentType },\n })\n const signed = answer[0]\n return {\n ok: true,\n ticket: mintTicket(deps.secret(), {\n h: scope.hostId,\n p: scope.purpose,\n i: scope.purposeId,\n u: id,\n t: upload.type.contentType,\n s: upload.size,\n n: upload.name,\n e: expiresAtMs,\n }),\n upload: { url: signed.url, fields: signed.fields },\n file: { id, name: upload.name, contentType: upload.type.contentType, size: upload.size },\n }\n}\n\n/*------------------------------------------\n * Finalize\n *-----------------------------------------*/\n\nconst first = <T,>(answer: [T] | T[]): T => answer[0] as T\n\n/** The custom metadata a kept file carries, which is how its record is read back. */\nfunction keptMetadata(name: string, uploadedAtMs: number): Record<string, string | null> {\n return {\n name,\n uploadedAtMs: String(uploadedAtMs),\n // Never a download token: nothing but the Admin SDK reads the object.\n firebaseStorageDownloadTokens: null,\n }\n}\n\n/** A kept file's record from its object's metadata, or null when it is not one. */\nfunction recordFromMetadata(path: string, id: string, metadata: VisitorUploadObjectMetadata): VisitorUploadFile | null {\n const contentType = String(metadata.contentType ?? '')\n const size = Number(metadata.size)\n const name = String(metadata.metadata?.['name'] ?? '')\n if (!visitorUploadTypeOf(contentType) || !Number.isSafeInteger(size) || size <= 0 || !name) return null\n return {\n id,\n name,\n contentType,\n size,\n path,\n uploadedAtMs: Number(metadata.metadata?.['uploadedAtMs']) || 0,\n }\n}\n\n/**\n * Checks and keeps the file a ticket signed for. The ticket must be one this\n * signed, for this `scope`, not long lapsed. Idempotent: a retried finalize\n * of a file already kept answers its record.\n */\nexport async function finalizeVisitorUpload(\n deps: VisitorUploadDeps,\n input: { scope: VisitorUploadScope; ticket: unknown; caller: VisitorUploadCaller },\n): Promise<{ ok: true; file: VisitorUploadFile } | VisitorUploadRefusal> {\n const { scope } = input\n if (!isVisitorUploadScope(scope)) return refusal(400, 'scope', 'This upload is missing what it is for.')\n const spent = await deps.consumeRateLimit(\n `visitor-upload-finalize:${scope.hostId}:${callerKey(input.caller)}`,\n VISITOR_UPLOAD_FINALIZE_LIMIT,\n )\n if (!spent.allowed) {\n return refusal(429, 'rate', 'Too many files at once. Wait a few minutes and try again.', {\n retryAfterSeconds: Math.max(1, Math.ceil((spent.resetMs - deps.now()) / 1000)),\n })\n }\n const ticket = readTicket(deps.secret(), input.ticket)\n const lapsed = 'This upload took too long. Send the file again.'\n if (\n !ticket ||\n ticket.h !== scope.hostId ||\n ticket.p !== scope.purpose ||\n ticket.i !== scope.purposeId\n ) {\n return refusal(400, 'ticket', lapsed)\n }\n if (deps.now() > ticket.e + VISITOR_UPLOAD_FINALIZE_GRACE_MS) return refusal(410, 'ticket', lapsed)\n\n const bucket = deps.bucket()\n const finalPath = visitorUploadFinalPath(scope, ticket.u)\n const kept = bucket.file(finalPath)\n if (first(await kept.exists())) {\n const record = recordFromMetadata(finalPath, ticket.u, first(await kept.getMetadata()))\n if (record) return { ok: true, file: record }\n }\n\n const pending = bucket.file(visitorUploadPendingPath(scope, ticket.u))\n if (!first(await pending.exists())) {\n return refusal(409, 'missing', `We didn’t receive ${ticket.n}. Try sending it again.`)\n }\n const discard = async <T,>(answer: T): Promise<T> => {\n await pending.delete({ ignoreNotFound: true }).catch(() => undefined)\n return answer\n }\n const metadata = first(await pending.getMetadata())\n const size = Number(metadata.size)\n const contentType = String(metadata.contentType ?? '')\n if (contentType !== ticket.t) {\n return discard(refusal(415, 'type', `${ticket.n} arrived as a different kind of file. Send it again.`))\n }\n if (!Number.isSafeInteger(size) || size <= 0) return discard(refusal(400, 'empty', `${ticket.n} is empty.`))\n if (size > ticket.s || size > VISITOR_UPLOAD_MAX_BYTES) {\n return discard(refusal(413, 'size', `${ticket.n} is larger than it said it was. Send it again.`))\n }\n\n // The bytes against the type: a few KB from the front, or all of an SVG,\n // which is text and is stripped of script below. Unlike the console's\n // media route this fails CLOSED: a visitor's file that could not be looked\n // at is not kept.\n let bytes: Buffer\n try {\n bytes = isSvgUploadType(contentType)\n ? first(await pending.download())\n : first(await pending.download({ start: 0, end: Math.min(size, UPLOAD_INSPECTION_HEAD_BYTES) - 1 }))\n } catch {\n return discard(refusal(503, 'unchecked', `${ticket.n} could not be checked. Send it again.`))\n }\n const inspected = inspectUploadBytes({ bytes, contentType, fileName: ticket.n })\n if (inspected) return discard(refusal(415, 'inspection', inspected.message))\n\n const uploadedAtMs = deps.now()\n const disposition = contentDisposition(ticket.n, contentType)\n if (isSvgUploadType(contentType)) {\n const sanitized = sanitizeSvgBuffer(bytes)\n await kept.save(sanitized.buffer, {\n resumable: false,\n contentType,\n metadata: {\n cacheControl: 'private, no-store',\n contentDisposition: disposition,\n metadata: keptMetadata(ticket.n, uploadedAtMs),\n },\n })\n await pending.delete({ ignoreNotFound: true }).catch(() => undefined)\n return {\n ok: true,\n file: { id: ticket.u, name: ticket.n, contentType, size: sanitized.buffer.length, path: finalPath, uploadedAtMs },\n }\n }\n await pending.move(finalPath)\n await kept.setMetadata({\n cacheControl: 'private, no-store',\n contentDisposition: disposition,\n metadata: keptMetadata(ticket.n, uploadedAtMs),\n })\n return { ok: true, file: { id: ticket.u, name: ticket.n, contentType, size, path: finalPath, uploadedAtMs } }\n}\n\n/*------------------------------------------\n * Afterwards\n *-----------------------------------------*/\n\n/** A kept file's record, by its id within `scope`; null when there is none. */\nexport async function readVisitorUpload(\n deps: Pick<VisitorUploadDeps, 'bucket'>,\n scope: VisitorUploadScope,\n id: string,\n): Promise<VisitorUploadFile | null> {\n if (!isVisitorUploadScope(scope) || !isVisitorUploadSegment(id)) return null\n const path = visitorUploadFinalPath(scope, id)\n const file = deps.bucket().file(path)\n if (!first(await file.exists())) return null\n return recordFromMetadata(path, id, first(await file.getMetadata()))\n}\n\n/** Deletes one kept file. Gone already is fine. */\nexport async function deleteVisitorUpload(deps: Pick<VisitorUploadDeps, 'bucket'>, path: string): Promise<void> {\n if (!path.startsWith('hosts/') || !path.includes('/private/uploads/')) return\n await deps.bucket().file(path).delete({ ignoreNotFound: true })\n}\n\n/** Deletes every kept file of one purpose and record. */\nexport async function deleteVisitorUploads(deps: Pick<VisitorUploadDeps, 'bucket'>, scope: VisitorUploadScope): Promise<void> {\n if (!isVisitorUploadScope(scope)) return\n await deps.bucket().deleteFiles({ prefix: visitorUploadFolder(scope) })\n}\n\n/** An ASCII stand-in for a header, and the real name encoded beside it. */\nfunction contentDisposition(name: string, contentType: string): string {\n const ascii = name.replace(/[^\\x20-\\x7e]/g, '_').replace(/[\"\\\\]/g, '_') || 'file'\n const kind = visitorUploadIsInline(contentType) ? 'inline' : 'attachment'\n return `${kind}; filename=\"${ascii}\"; filename*=UTF-8''${encodeURIComponent(name)}`\n}\n\n/** The headers a kept file is served with. */\nexport function visitorUploadResponseHeaders(file: Pick<VisitorUploadFile, 'name' | 'contentType'>): Record<string, string> {\n return {\n 'Content-Type': file.contentType,\n 'Content-Disposition': contentDisposition(file.name, file.contentType),\n 'X-Content-Type-Options': 'nosniff',\n // Whatever the bytes turn out to be, they run nothing and load nothing.\n 'Content-Security-Policy': \"default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox\",\n 'Cache-Control': 'private, no-store',\n 'X-Robots-Tag': 'noindex, nofollow',\n 'Referrer-Policy': 'no-referrer',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n }\n}\n\n/** The response a gated route streams a kept file into. */\nexport interface VisitorUploadResponse extends Writable {\n setHeader(name: string, value: string): void\n status(code: number): unknown\n}\n\n/**\n * Streams a kept file to a route's response, after the route has checked the\n * caller. The file is never held whole in memory.\n */\nexport async function sendVisitorUploadFile(\n deps: Pick<VisitorUploadDeps, 'bucket'>,\n res: VisitorUploadResponse,\n file: Pick<VisitorUploadFile, 'path' | 'name' | 'contentType'>,\n): Promise<void> {\n for (const [name, value] of Object.entries(visitorUploadResponseHeaders(file))) res.setHeader(name, value)\n res.status(200)\n await pipeline(deps.bucket().file(file.path).createReadStream(), res)\n}\n"],"names":["createHmac","randomBytes","timingSafeEqual","pipeline","inspectUploadBytes","UPLOAD_INSPECTION_HEAD_BYTES","isSvgUploadType","sanitizeSvgBuffer","checkVisitorUploadRequest","isVisitorUploadScope","isVisitorUploadSegment","visitorUploadFinalPath","visitorUploadFolder","visitorUploadIsInline","visitorUploadPendingPath","visitorUploadTypeOf","VISITOR_UPLOAD_MAX_BYTES","VISITOR_UPLOAD_TICKET_TTL_MS","firebaseAdmin","featureLockdownRefusal","consumeRateLimit","defaultVisitorUploadDeps","bucket","app","storage","process","env","undefined","key","options","uploadsPaused","feature","secret","Error","now","Date","newId","toString","VISITOR_UPLOAD_LIMITS","perCaller","limit","windowMs","perSite","VISITOR_UPLOAD_FINALIZE_LIMIT","VISITOR_UPLOAD_FINALIZE_GRACE_MS","refusal","status","code","error","extra","ok","callerKey","caller","uid","ip","signTicket","payload","update","digest","mintTicket","encoded","Buffer","from","JSON","stringify","readTicket","ticket","length","separator","lastIndexOf","slice","presented","expected","parse","hostId","h","purpose","p","purposeId","i","u","String","t","Number","isSafeInteger","s","n","e","mintVisitorUploadTicket","deps","input","scope","checked","request","maxBytes","kinds","limits","rate","spent","allowed","retryAfterSeconds","Math","max","ceil","resetMs","upload","id","expiresAtMs","answer","file","generateSignedPostPolicyV4","expires","conditions","size","fields","type","contentType","signed","name","url","first","keptMetadata","uploadedAtMs","firebaseStorageDownloadTokens","recordFromMetadata","path","metadata","finalizeVisitorUpload","lapsed","finalPath","kept","exists","record","getMetadata","pending","discard","delete","ignoreNotFound","catch","bytes","download","start","end","min","inspected","fileName","message","disposition","contentDisposition","sanitized","save","buffer","resumable","cacheControl","move","setMetadata","readVisitorUpload","deleteVisitorUpload","startsWith","includes","deleteVisitorUploads","deleteFiles","prefix","ascii","replace","kind","encodeURIComponent","visitorUploadResponseHeaders","sendVisitorUploadFile","res","value","Object","entries","setHeader","createReadStream"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,WAAW,EAAEC,eAAe,QAAQ,cAAa;AACtE,SAASC,QAAQ,QAAQ,uBAAsB;AAE/C,SACEC,kBAAkB,EAClBC,4BAA4B,QACvB,2CAA0C;AACjD,SAASC,eAAe,EAAEC,iBAAiB,QAAQ,sCAAqC;AACxF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GAAG2I,WAAW,CAAC;QAAEC,QAAQtJ,oBAAoB+E;IAAO;AACvE;AAEA,yEAAyE,GACzE,SAASyD,mBAAmB9B,IAAY,EAAEF,WAAmB;IAC3D,MAAM+C,QAAQ7C,KAAK8C,OAAO,CAAC,iBAAiB,KAAKA,OAAO,CAAC,UAAU,QAAQ;IAC3E,MAAMC,OAAOxJ,sBAAsBuG,eAAe,WAAW;IAC7D,OAAO,GAAGiD,KAAK,YAAY,EAAEF,MAAM,oBAAoB,EAAEG,mBAAmBhD,OAAO;AACrF;AAEA,4CAA4C,GAC5C,OAAO,SAASiD,6BAA6B1D,IAAqD;IAChG,OAAO;QACL,gBAAgBA,KAAKO,WAAW;QAChC,uBAAuBgC,mBAAmBvC,KAAKS,IAAI,EAAET,KAAKO,WAAW;QACrE,0BAA0B;QAC1B,wEAAwE;QACxE,2BAA2B;QAC3B,iBAAiB;QACjB,gBAAgB;QAChB,mBAAmB;QACnB,gCAAgC;IAClC;AACF;AAQA;;;CAGC,GACD,OAAO,eAAeoD,sBACpB/E,IAAuC,EACvCgF,GAA0B,EAC1B5D,IAA8D;IAE9D,KAAK,MAAM,CAACS,MAAMoD,MAAM,IAAIC,OAAOC,OAAO,CAACL,6BAA6B1D,OAAQ4D,IAAII,SAAS,CAACvD,MAAMoD;IACpGD,IAAI3H,MAAM,CAAC;IACX,MAAM3C,SAASsF,KAAKnE,MAAM,GAAGuF,IAAI,CAACA,KAAKgB,IAAI,EAAEiD,gBAAgB,IAAIL;AACnE"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/visitor-upload.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 { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\nimport { pipeline } from 'node:stream/promises'\nimport type { Writable } from 'node:stream'\nimport {\n inspectUploadBytes,\n UPLOAD_INSPECTION_HEAD_BYTES,\n} from '@aglyn/aglyn/app-utils/upload-inspection'\nimport { isSvgUploadType, sanitizeSvgBuffer } from '@aglyn/aglyn/app-utils/sanitize-svg'\nimport {\n checkVisitorUploadRequest,\n isVisitorUploadScope,\n isVisitorUploadSegment,\n visitorUploadFinalPath,\n visitorUploadFolder,\n visitorUploadIsInline,\n visitorUploadPendingPath,\n visitorUploadTypeOf,\n VISITOR_UPLOAD_COUNTER_BYTES,\n VISITOR_UPLOAD_COUNTER_FILES,\n VISITOR_UPLOAD_MAX_BYTES,\n VISITOR_UPLOAD_TICKET_TTL_MS,\n type VisitorUploadFile,\n type VisitorUploadKind,\n type VisitorUploadScope,\n} from '@aglyn/aglyn/app-utils/visitor-upload'\nimport {\n uploadStorageGate,\n type UploadStorageRefusal,\n} from '@aglyn/aglyn/plugin-manager/plugin-upload-storage-gate'\nimport firebaseAdmin from './firebase-admin'\nimport { featureLockdownRefusal } from './lockdown'\nimport { consumeRateLimit } from './rate-limit-store'\n\n/*==========================================\n * TAKING A FILE FROM A SITE'S VISITOR, OR A MEMBER (AGL-4096).\n *\n * Two calls a plugin's own routes make, after deciding for themselves who may\n * upload for what (a quote's signed link, a form's binding, a member's key):\n *\n * mintVisitorUploadTicket → a TICKET and a signed upload for one file of a\n * declared name, type and size, to a PENDING\n * path scoped to (site, purpose, record);\n * finalizeVisitorUpload → reads what arrived there, checks its size and\n * bytes (`inspectUploadBytes`), strips script\n * from an SVG, moves it to the record's private\n * folder and answers its {@link VisitorUploadFile}.\n *\n * And three for afterwards: {@link readVisitorUpload} (a kept file's record,\n * by id, so a later submit names files by id and nothing else),\n * {@link sendVisitorUploadFile} (serve one through a gated route) and\n * {@link deleteVisitorUpload} / {@link deleteVisitorUploads}.\n *\n * THE UPLOAD IS A SIGNED POST POLICY, not a signed PUT URL. A site lives on\n * any domain, and the bucket's cross-origin list names the console's\n * addresses one by one and never `*` (AGL-1452), so a browser on a\n * customer's domain could not make the PUT. A form post needs no such\n * permission. The policy binds the exact object, the type and the size range\n * and lapses after {@link VISITOR_UPLOAD_TICKET_TTL_MS}, so Storage itself\n * refuses anything else; finalize then checks again, because the bytes are\n * what matter.\n *\n * THE TICKET is `<payload>.<signature>`: the scope, the upload's id, its\n * type, size and name and when it lapses, HMAC-signed under\n * `TOKEN_SIGNING_SECRET` with a `visitor-upload:` prefix so it cannot be\n * replayed as any other token. Nothing is stored per ticket. It is an\n * internal handle for the seconds between upload and finalize, never a state\n * anyone sees.\n *\n * WHAT IS NEVER FINALIZED is deleted by the bucket's lifecycle a day after it\n * arrived: `visitor-uploads-pending/` in `cloud/media-bucket-lifecycle.json`.\n * A refused finalize deletes its object at once.\n *\n * THE KEPT FILE has no download token and lives under `hosts/{hostId}/private/`,\n * so only the Admin SDK reads it, the site's erasure deletes it with the\n * site, and a route that checked the caller serves it\n * ({@link sendVisitorUploadFile}: `nosniff`, a sandboxing CSP, and\n * `attachment` for everything but the raster images a browser draws safely).\n *\n * Abuse: each ticket spends a per-caller and a per-site rate limit, the\n * platform's uploads pause (`uploads` lockdown feature) refuses new tickets,\n * and the plugin route sits behind the site dispatcher's cross-origin check,\n * lockdown and visitor-write limit.\n *\n * STORAGE. A kept file counts toward the workspace's storage exactly as a\n * media library file does: finalize adds its bytes to the site's storage\n * counter (`hosts/{hostId}/counters/media`, `bytes` plus the\n * `uploadBytes`/`uploadCount` share, see `VISITOR_UPLOAD_COUNTER_BYTES`),\n * the figure the storage band, the Billing meter, the usage alerts and the\n * invoice read. Deleting a kept file takes its bytes off again. A file that\n * was counted carries `storageCounted` in its metadata, so a file kept before\n * files were counted releases nothing it never added, and only the delete\n * that actually removed the object releases its bytes.\n *\n * Who is refused for storage:\n *\n * - A MEMBER's file (a quote's proof, `caller: { uid }`) meets the same band\n * a library upload does, through `core.upload-storage-gate`: refused past\n * the allowance on a plan that does not bill storage, taken and billed past\n * it on one that does, refused past a storage cap the workspace set.\n * - A VISITOR's file (`caller: { ip }`: a customer's artwork on a quote, a\n * form's file) is NEVER refused for the business's storage. The customer\n * cannot free space or upgrade the plan, and a request or an approval lost\n * to the business's storage is a lost customer. The file is kept and\n * counted all the same, so past the allowance a plan that bills storage\n * bills it, a plan that does not stops the business's own uploads until\n * space is freed, and the usage alerts tell the owner either way. What\n * bounds a visitor is what bounded one before: the size and file limits,\n * the rate limits, the uploads pause, and for a form the plan's submission\n * allowance.\n *=========================================*/\n\n/** The few Storage calls this makes, so a spec can stand in for the bucket. */\nexport interface VisitorUploadObject {\n generateSignedPostPolicyV4(options: {\n expires: number\n conditions?: unknown[]\n fields?: Record<string, string>\n }): Promise<[{ url: string; fields: Record<string, string> }] | Array<{ url: string; fields: Record<string, string> }>>\n exists(): Promise<[boolean] | boolean[]>\n getMetadata(): Promise<[VisitorUploadObjectMetadata] | VisitorUploadObjectMetadata[]>\n download(options?: { start?: number; end?: number }): Promise<[Buffer] | Buffer[]>\n save(data: Buffer, options: Record<string, unknown>): Promise<unknown>\n move(destination: string): Promise<unknown>\n setMetadata(metadata: Record<string, unknown>): Promise<unknown>\n delete(options?: { ignoreNotFound?: boolean }): Promise<unknown>\n createReadStream(): NodeJS.ReadableStream\n}\n\nexport interface VisitorUploadObjectMetadata {\n size?: string | number\n contentType?: string\n metadata?: Record<string, string | null | undefined> | null\n}\n\n/** An object as a listing answers it: its name, its metadata, and a way to delete it. */\nexport interface VisitorUploadListedObject {\n name: string\n metadata?: VisitorUploadObjectMetadata | null\n delete(options?: { ignoreNotFound?: boolean }): Promise<unknown>\n}\n\nexport interface VisitorUploadBucket {\n file(path: string): VisitorUploadObject\n /** Every object under a prefix, with its metadata (Storage answers `[files, nextQuery, response]`). */\n getFiles(options: { prefix: string }): Promise<[VisitorUploadListedObject[], ...unknown[]]>\n}\n\n/** How a kept file moves its site's storage counter: `+` when kept, `-` when deleted. */\nexport interface VisitorUploadStorageDelta {\n bytes: number\n files: number\n}\n\nexport interface VisitorUploadDeps {\n bucket(): VisitorUploadBucket\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean; resetMs: number }>\n /** Whether the platform's uploads pause (`uploads` lockdown feature) is on. */\n uploadsPaused(): Promise<boolean>\n /** The secret tickets are signed with. Throws when none is configured. */\n secret(): string\n now(): number\n /** A fresh upload id: a path segment no one can guess. */\n newId(): string\n /**\n * Moves the site's storage counter (`hosts/{hostId}/counters/media`) by a\n * kept file: its bytes in `bytes`, the figure every storage reader reads,\n * and in the kept files' own share beside it.\n */\n countStorage(hostId: string, delta: VisitorUploadStorageDelta): Promise<void>\n /**\n * The workspace's storage band, asked before a MEMBER's file is taken:\n * `null` to take it. Never asked for a visitor's. Absent, the file is taken.\n */\n storageGate?(input: { hostId: string; bytes: number }): Promise<UploadStorageRefusal | null>\n}\n\nexport function defaultVisitorUploadDeps(): VisitorUploadDeps {\n return {\n // The bucket the site's `connect-src` admits by name (`security-origins.js`,\n // `visitorUploadConnectSource`), so the browser's post is allowed to leave.\n bucket: () =>\n firebaseAdmin\n .app()\n .storage()\n .bucket(process.env['NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET'] || undefined) as unknown as VisitorUploadBucket,\n consumeRateLimit: (key, options) => consumeRateLimit(key, options),\n uploadsPaused: async () => (await featureLockdownRefusal({ feature: 'uploads' })) !== null,\n secret: () => {\n const secret = process.env['TOKEN_SIGNING_SECRET']\n if (!secret) throw new Error('TOKEN_SIGNING_SECRET is not configured')\n return secret\n },\n now: () => Date.now(),\n newId: () => randomBytes(12).toString('hex'),\n countStorage: async (hostId, delta) => {\n const increment = firebaseAdmin.firestore.FieldValue.increment\n await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('counters')\n .doc('media')\n .set(\n {\n bytes: increment(delta.bytes),\n [VISITOR_UPLOAD_COUNTER_BYTES]: increment(delta.bytes),\n [VISITOR_UPLOAD_COUNTER_FILES]: increment(delta.files),\n },\n { merge: true },\n )\n },\n // The console registers the band (`core.upload-storage-gate`); the site\n // app registers none and never takes a member's file.\n storageGate: async (input) => (await uploadStorageGate()?.check(input)) ?? null,\n }\n}\n\n/** One rate limit: so many in so long. */\nexport interface VisitorUploadRate {\n limit: number\n windowMs: number\n}\n\n/** The limits a ticket spends, per caller on a site and per site. */\nexport interface VisitorUploadLimits {\n perCaller: VisitorUploadRate\n perSite: VisitorUploadRate\n}\n\n/**\n * Tickets per caller on one site: 30 in ten minutes is three full\n * submissions of ten files; per site, 300 an hour across everyone.\n */\nexport const VISITOR_UPLOAD_LIMITS: VisitorUploadLimits = {\n perCaller: { limit: 30, windowMs: 10 * 60_000 },\n perSite: { limit: 300, windowMs: 60 * 60_000 },\n}\n\n/** Finalizes per caller on one site, per ten minutes: a retry or two per ticket. */\nexport const VISITOR_UPLOAD_FINALIZE_LIMIT: VisitorUploadRate = { limit: 60, windowMs: 10 * 60_000 }\n\n/** How long after its upload lapses a ticket may still be finalized: a slow connection's last bytes. */\nexport const VISITOR_UPLOAD_FINALIZE_GRACE_MS = 60 * 60_000\n\n/** Who is uploading: an address for a visitor, a uid for a member. Keys the per-caller limit. */\nexport type VisitorUploadCaller = { ip: string } | { uid: string }\n\nexport type VisitorUploadRefusal = {\n ok: false\n status: number\n error: string\n code:\n | 'type'\n | 'size'\n | 'empty'\n | 'scope'\n | 'rate'\n | 'paused'\n | 'storage'\n | 'ticket'\n | 'missing'\n | 'inspection'\n | 'unchecked'\n retryAfterSeconds?: number\n}\n\nconst refusal = (\n status: number,\n code: VisitorUploadRefusal['code'],\n error: string,\n extra: Partial<VisitorUploadRefusal> = {},\n): VisitorUploadRefusal => ({ ok: false, status, code, error, ...extra })\n\nconst callerKey = (caller: VisitorUploadCaller) => ('uid' in caller ? `uid:${caller.uid}` : `ip:${caller.ip || 'no-address'}`)\n\n/*------------------------------------------\n * The ticket\n *-----------------------------------------*/\n\ninterface TicketPayload {\n h: string\n p: string\n i: string\n u: string\n t: string\n s: number\n n: string\n e: number\n}\n\nfunction signTicket(secret: string, payload: string): string {\n return createHmac('sha256', secret).update(`visitor-upload:${payload}`).digest('base64url')\n}\n\nfunction mintTicket(secret: string, payload: TicketPayload): string {\n const encoded = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')\n return `${encoded}.${signTicket(secret, encoded)}`\n}\n\n/** A ticket's payload when its signature holds, else null. Expiry is the caller's to judge. */\nfunction readTicket(secret: string, ticket: unknown): TicketPayload | null {\n if (typeof ticket !== 'string' || ticket.length > 2_000) return null\n const separator = ticket.lastIndexOf('.')\n if (separator <= 0) return null\n const encoded = ticket.slice(0, separator)\n const presented = Buffer.from(ticket.slice(separator + 1))\n const expected = Buffer.from(signTicket(secret, encoded))\n if (presented.length !== expected.length || !timingSafeEqual(presented, expected)) return null\n try {\n const payload = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as TicketPayload\n if (\n !isVisitorUploadScope({ hostId: payload.h, purpose: payload.p, purposeId: payload.i }) ||\n !isVisitorUploadSegment(payload.u) ||\n !visitorUploadTypeOf(String(payload.t)) ||\n !Number.isSafeInteger(payload.s) ||\n typeof payload.n !== 'string' ||\n !Number.isSafeInteger(payload.e)\n ) {\n return null\n }\n return payload\n } catch {\n return null\n }\n}\n\n/*------------------------------------------\n * Mint\n *-----------------------------------------*/\n\nexport interface VisitorUploadTicket {\n ok: true\n /** Handed back to finalize. */\n ticket: string\n /** The signed form post: where, and the fields that go before the file. */\n upload: { url: string; fields: Record<string, string> }\n /** The file as it will be kept. */\n file: { id: string; name: string; contentType: string; size: number }\n}\n\n/**\n * A ticket and a signed upload for ONE file, after the caller's route has\n * decided the caller may upload for `scope`. Spends the rate limits; refused\n * while the platform's uploads are paused, and a member's file when the\n * workspace's storage band refuses it (never a visitor's). `maxBytes`\n * narrows the 25 MB ceiling, never widens it; `kinds` narrows the types\n * taken (a form field that asks for PDFs only), never widens them.\n */\nexport async function mintVisitorUploadTicket(\n deps: VisitorUploadDeps,\n input: {\n scope: VisitorUploadScope\n request: unknown\n caller: VisitorUploadCaller\n limits?: VisitorUploadLimits\n maxBytes?: number\n kinds?: readonly VisitorUploadKind[]\n },\n): Promise<VisitorUploadTicket | VisitorUploadRefusal> {\n const { scope } = input\n if (!isVisitorUploadScope(scope)) return refusal(400, 'scope', 'This upload is missing what it is for.')\n const checked = checkVisitorUploadRequest(input.request, { maxBytes: input.maxBytes, kinds: input.kinds })\n if ('error' in checked) return refusal(checked.code === 'size' ? 413 : 400, checked.code, checked.error)\n if (await deps.uploadsPaused()) {\n return refusal(423, 'paused', 'Uploads are paused for a moment. Try again a little later.')\n }\n // A member's file meets the storage band a library upload meets; a\n // visitor's is never refused for the business's storage (see STORAGE).\n if ('uid' in input.caller && deps.storageGate) {\n const full = await deps.storageGate({ hostId: scope.hostId, bytes: checked.upload.size })\n if (full) return refusal(full.status, 'storage', full.error)\n }\n const limits = input.limits ?? VISITOR_UPLOAD_LIMITS\n for (const [key, rate] of [\n [`visitor-upload:${scope.hostId}:${callerKey(input.caller)}`, limits.perCaller],\n [`visitor-upload-site:${scope.hostId}`, limits.perSite],\n ] as const) {\n const spent = await deps.consumeRateLimit(key, rate)\n if (!spent.allowed) {\n return refusal(429, 'rate', 'Too many files at once. Wait a few minutes and try again.', {\n retryAfterSeconds: Math.max(1, Math.ceil((spent.resetMs - deps.now()) / 1000)),\n })\n }\n }\n\n const { upload } = checked\n const id = deps.newId()\n const expiresAtMs = deps.now() + VISITOR_UPLOAD_TICKET_TTL_MS\n const answer = await deps\n .bucket()\n .file(visitorUploadPendingPath(scope, id))\n .generateSignedPostPolicyV4({\n expires: expiresAtMs,\n // Storage refuses a post of any other size, type or object: each\n // field below is also an exact-match condition of the policy.\n conditions: [['content-length-range', 1, upload.size]],\n fields: { 'Content-Type': upload.type.contentType },\n })\n const signed = answer[0]\n return {\n ok: true,\n ticket: mintTicket(deps.secret(), {\n h: scope.hostId,\n p: scope.purpose,\n i: scope.purposeId,\n u: id,\n t: upload.type.contentType,\n s: upload.size,\n n: upload.name,\n e: expiresAtMs,\n }),\n upload: { url: signed.url, fields: signed.fields },\n file: { id, name: upload.name, contentType: upload.type.contentType, size: upload.size },\n }\n}\n\n/*------------------------------------------\n * Finalize\n *-----------------------------------------*/\n\nconst first = <T,>(answer: [T] | T[]): T => answer[0] as T\n\n/**\n * The custom metadata key a kept file carries once its bytes are in its\n * site's storage counter. A file kept before files were counted has none, so\n * deleting it releases nothing it never added.\n */\nconst STORAGE_COUNTED = 'storageCounted'\n\n/** The custom metadata a kept file carries, which is how its record is read back. */\nfunction keptMetadata(name: string, uploadedAtMs: number): Record<string, string | null> {\n return {\n name,\n uploadedAtMs: String(uploadedAtMs),\n // Never a download token: nothing but the Admin SDK reads the object.\n firebaseStorageDownloadTokens: null,\n [STORAGE_COUNTED]: '1',\n }\n}\n\n/**\n * Adds a file just kept to its site's storage. Never the uploader's problem:\n * the file stays kept whatever the counter does, and if the counter could\n * not be moved the file's mark comes off, so deleting it later releases\n * nothing it never added.\n */\nasync function countKept(\n deps: Pick<VisitorUploadDeps, 'countStorage'>,\n hostId: string,\n size: number,\n kept: VisitorUploadObject,\n): Promise<void> {\n try {\n await deps.countStorage(hostId, { bytes: size, files: 1 })\n } catch (error) {\n console.error('a kept upload was not counted toward storage', { hostId, error })\n await kept.setMetadata({ metadata: { [STORAGE_COUNTED]: null } }).catch(() => undefined)\n }\n}\n\n/** A kept file's record from its object's metadata, or null when it is not one. */\nfunction recordFromMetadata(path: string, id: string, metadata: VisitorUploadObjectMetadata): VisitorUploadFile | null {\n const contentType = String(metadata.contentType ?? '')\n const size = Number(metadata.size)\n const name = String(metadata.metadata?.['name'] ?? '')\n if (!visitorUploadTypeOf(contentType) || !Number.isSafeInteger(size) || size <= 0 || !name) return null\n return {\n id,\n name,\n contentType,\n size,\n path,\n uploadedAtMs: Number(metadata.metadata?.['uploadedAtMs']) || 0,\n }\n}\n\n/**\n * Checks and keeps the file a ticket signed for. The ticket must be one this\n * signed, for this `scope`, not long lapsed. Idempotent: a retried finalize\n * of a file already kept answers its record.\n */\nexport async function finalizeVisitorUpload(\n deps: VisitorUploadDeps,\n input: { scope: VisitorUploadScope; ticket: unknown; caller: VisitorUploadCaller },\n): Promise<{ ok: true; file: VisitorUploadFile } | VisitorUploadRefusal> {\n const { scope } = input\n if (!isVisitorUploadScope(scope)) return refusal(400, 'scope', 'This upload is missing what it is for.')\n const spent = await deps.consumeRateLimit(\n `visitor-upload-finalize:${scope.hostId}:${callerKey(input.caller)}`,\n VISITOR_UPLOAD_FINALIZE_LIMIT,\n )\n if (!spent.allowed) {\n return refusal(429, 'rate', 'Too many files at once. Wait a few minutes and try again.', {\n retryAfterSeconds: Math.max(1, Math.ceil((spent.resetMs - deps.now()) / 1000)),\n })\n }\n const ticket = readTicket(deps.secret(), input.ticket)\n const lapsed = 'This upload took too long. Send the file again.'\n if (\n !ticket ||\n ticket.h !== scope.hostId ||\n ticket.p !== scope.purpose ||\n ticket.i !== scope.purposeId\n ) {\n return refusal(400, 'ticket', lapsed)\n }\n if (deps.now() > ticket.e + VISITOR_UPLOAD_FINALIZE_GRACE_MS) return refusal(410, 'ticket', lapsed)\n\n const bucket = deps.bucket()\n const finalPath = visitorUploadFinalPath(scope, ticket.u)\n const kept = bucket.file(finalPath)\n if (first(await kept.exists())) {\n const record = recordFromMetadata(finalPath, ticket.u, first(await kept.getMetadata()))\n if (record) return { ok: true, file: record }\n }\n\n const pending = bucket.file(visitorUploadPendingPath(scope, ticket.u))\n if (!first(await pending.exists())) {\n return refusal(409, 'missing', `We didn’t receive ${ticket.n}. Try sending it again.`)\n }\n const discard = async <T,>(answer: T): Promise<T> => {\n await pending.delete({ ignoreNotFound: true }).catch(() => undefined)\n return answer\n }\n const metadata = first(await pending.getMetadata())\n const size = Number(metadata.size)\n const contentType = String(metadata.contentType ?? '')\n if (contentType !== ticket.t) {\n return discard(refusal(415, 'type', `${ticket.n} arrived as a different kind of file. Send it again.`))\n }\n if (!Number.isSafeInteger(size) || size <= 0) return discard(refusal(400, 'empty', `${ticket.n} is empty.`))\n if (size > ticket.s || size > VISITOR_UPLOAD_MAX_BYTES) {\n return discard(refusal(413, 'size', `${ticket.n} is larger than it said it was. Send it again.`))\n }\n\n // The bytes against the type: a few KB from the front, or all of an SVG,\n // which is text and is stripped of script below. Unlike the console's\n // media route this fails CLOSED: a visitor's file that could not be looked\n // at is not kept.\n let bytes: Buffer\n try {\n bytes = isSvgUploadType(contentType)\n ? first(await pending.download())\n : first(await pending.download({ start: 0, end: Math.min(size, UPLOAD_INSPECTION_HEAD_BYTES) - 1 }))\n } catch {\n return discard(refusal(503, 'unchecked', `${ticket.n} could not be checked. Send it again.`))\n }\n const inspected = inspectUploadBytes({ bytes, contentType, fileName: ticket.n })\n if (inspected) return discard(refusal(415, 'inspection', inspected.message))\n\n const uploadedAtMs = deps.now()\n const disposition = contentDisposition(ticket.n, contentType)\n if (isSvgUploadType(contentType)) {\n const sanitized = sanitizeSvgBuffer(bytes)\n await kept.save(sanitized.buffer, {\n resumable: false,\n contentType,\n metadata: {\n cacheControl: 'private, no-store',\n contentDisposition: disposition,\n metadata: keptMetadata(ticket.n, uploadedAtMs),\n },\n })\n await pending.delete({ ignoreNotFound: true }).catch(() => undefined)\n await countKept(deps, scope.hostId, sanitized.buffer.length, kept)\n return {\n ok: true,\n file: { id: ticket.u, name: ticket.n, contentType, size: sanitized.buffer.length, path: finalPath, uploadedAtMs },\n }\n }\n await pending.move(finalPath)\n await kept.setMetadata({\n cacheControl: 'private, no-store',\n contentDisposition: disposition,\n metadata: keptMetadata(ticket.n, uploadedAtMs),\n })\n await countKept(deps, scope.hostId, size, kept)\n return { ok: true, file: { id: ticket.u, name: ticket.n, contentType, size, path: finalPath, uploadedAtMs } }\n}\n\n/*------------------------------------------\n * Afterwards\n *-----------------------------------------*/\n\n/** A kept file's record, by its id within `scope`; null when there is none. */\nexport async function readVisitorUpload(\n deps: Pick<VisitorUploadDeps, 'bucket'>,\n scope: VisitorUploadScope,\n id: string,\n): Promise<VisitorUploadFile | null> {\n if (!isVisitorUploadScope(scope) || !isVisitorUploadSegment(id)) return null\n const path = visitorUploadFinalPath(scope, id)\n const file = deps.bucket().file(path)\n if (!first(await file.exists())) return null\n return recordFromMetadata(path, id, first(await file.getMetadata()))\n}\n\nconst isNotFound = (error: unknown): boolean =>\n Number((error as { code?: unknown } | null)?.code) === 404\n\n/** Deletes one object; true only when this call is the one that removed it. */\nasync function deleteObject(object: Pick<VisitorUploadObject, 'delete'>): Promise<boolean> {\n try {\n await object.delete()\n return true\n } catch (error) {\n if (isNotFound(error)) return false\n throw error\n }\n}\n\n/**\n * Takes deleted files' bytes off their site's storage: the ones that were\n * counted, by the size each was kept at. Never throws, so a counter that\n * could not be moved never fails the delete it follows.\n */\nasync function releaseCounted(\n deps: Pick<VisitorUploadDeps, 'countStorage'>,\n hostId: string,\n deleted: ReadonlyArray<VisitorUploadObjectMetadata | null | undefined>,\n): Promise<void> {\n let bytes = 0\n let files = 0\n for (const metadata of deleted) {\n if (metadata?.metadata?.[STORAGE_COUNTED] !== '1') continue\n const size = Number(metadata.size)\n if (!Number.isSafeInteger(size) || size <= 0) continue\n bytes += size\n files += 1\n }\n if (!files) return\n try {\n await deps.countStorage(hostId, { bytes: -bytes, files: -files })\n } catch (error) {\n console.error('deleted uploads were not taken off storage', { hostId, bytes, files, error })\n }\n}\n\n/** Deletes one kept file and releases its bytes. Gone already is fine. */\nexport async function deleteVisitorUpload(\n deps: Pick<VisitorUploadDeps, 'bucket' | 'countStorage'>,\n path: string,\n): Promise<void> {\n if (!path.startsWith('hosts/') || !path.includes('/private/uploads/')) return\n const hostId = path.split('/')[1] ?? ''\n if (!isVisitorUploadSegment(hostId)) return\n const file = deps.bucket().file(path)\n let metadata: VisitorUploadObjectMetadata\n try {\n metadata = first(await file.getMetadata())\n } catch (error) {\n if (isNotFound(error)) return\n throw error\n }\n if (await deleteObject(file)) await releaseCounted(deps, hostId, [metadata])\n}\n\n/** Deletes every kept file of one purpose and record, and releases their bytes. */\nexport async function deleteVisitorUploads(\n deps: Pick<VisitorUploadDeps, 'bucket' | 'countStorage'>,\n scope: VisitorUploadScope,\n): Promise<void> {\n if (!isVisitorUploadScope(scope)) return\n const [listed = []] = await deps.bucket().getFiles({ prefix: visitorUploadFolder(scope) })\n const deleted = await Promise.all(\n listed.map(async (object) => ((await deleteObject(object)) ? object.metadata : null)),\n )\n await releaseCounted(deps, scope.hostId, deleted)\n}\n\n/** An ASCII stand-in for a header, and the real name encoded beside it. */\nfunction contentDisposition(name: string, contentType: string): string {\n const ascii = name.replace(/[^\\x20-\\x7e]/g, '_').replace(/[\"\\\\]/g, '_') || 'file'\n const kind = visitorUploadIsInline(contentType) ? 'inline' : 'attachment'\n return `${kind}; filename=\"${ascii}\"; filename*=UTF-8''${encodeURIComponent(name)}`\n}\n\n/** The headers a kept file is served with. */\nexport function visitorUploadResponseHeaders(file: Pick<VisitorUploadFile, 'name' | 'contentType'>): Record<string, string> {\n return {\n 'Content-Type': file.contentType,\n 'Content-Disposition': contentDisposition(file.name, file.contentType),\n 'X-Content-Type-Options': 'nosniff',\n // Whatever the bytes turn out to be, they run nothing and load nothing.\n 'Content-Security-Policy': \"default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox\",\n 'Cache-Control': 'private, no-store',\n 'X-Robots-Tag': 'noindex, nofollow',\n 'Referrer-Policy': 'no-referrer',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n }\n}\n\n/** The response a gated route streams a kept file into. */\nexport interface VisitorUploadResponse extends Writable {\n setHeader(name: string, value: string): void\n status(code: number): unknown\n}\n\n/**\n * Streams a kept file to a route's response, after the route has checked the\n * caller. The file is never held whole in memory.\n */\nexport async function sendVisitorUploadFile(\n deps: Pick<VisitorUploadDeps, 'bucket'>,\n res: VisitorUploadResponse,\n file: Pick<VisitorUploadFile, 'path' | 'name' | 'contentType'>,\n): Promise<void> {\n for (const [name, value] of Object.entries(visitorUploadResponseHeaders(file))) res.setHeader(name, value)\n res.status(200)\n await pipeline(deps.bucket().file(file.path).createReadStream(), res)\n}\n"],"names":["createHmac","randomBytes","timingSafeEqual","pipeline","inspectUploadBytes","UPLOAD_INSPECTION_HEAD_BYTES","isSvgUploadType","sanitizeSvgBuffer","checkVisitorUploadRequest","isVisitorUploadScope","isVisitorUploadSegment","visitorUploadFinalPath","visitorUploadFolder","visitorUploadIsInline","visitorUploadPendingPath","visitorUploadTypeOf","VISITOR_UPLOAD_COUNTER_BYTES","VISITOR_UPLOAD_COUNTER_FILES","VISITOR_UPLOAD_MAX_BYTES","VISITOR_UPLOAD_TICKET_TTL_MS","uploadStorageGate","firebaseAdmin","featureLockdownRefusal","consumeRateLimit","defaultVisitorUploadDeps","bucket","app","storage","process","env","undefined","key","options","uploadsPaused","feature","secret","Error","now","Date","newId","toString","countStorage","hostId","delta","increment","firestore","FieldValue","collection","doc","set","bytes","files","merge","storageGate","input","check","VISITOR_UPLOAD_LIMITS","perCaller","limit","windowMs","perSite","VISITOR_UPLOAD_FINALIZE_LIMIT","VISITOR_UPLOAD_FINALIZE_GRACE_MS","refusal","status","code","error","extra","ok","callerKey","caller","uid","ip","signTicket","payload","update","digest","mintTicket","encoded","Buffer","from","JSON","stringify","readTicket","ticket","length","separator","lastIndexOf","slice","presented","expected","parse","h","purpose","p","purposeId","i","u","String","t","Number","isSafeInteger","s","n","e","mintVisitorUploadTicket","deps","scope","checked","request","maxBytes","kinds","full","upload","size","limits","rate","spent","allowed","retryAfterSeconds","Math","max","ceil","resetMs","id","expiresAtMs","answer","file","generateSignedPostPolicyV4","expires","conditions","fields","type","contentType","signed","name","url","first","STORAGE_COUNTED","keptMetadata","uploadedAtMs","firebaseStorageDownloadTokens","countKept","kept","console","setMetadata","metadata","catch","recordFromMetadata","path","finalizeVisitorUpload","lapsed","finalPath","exists","record","getMetadata","pending","discard","delete","ignoreNotFound","download","start","end","min","inspected","fileName","message","disposition","contentDisposition","sanitized","save","buffer","resumable","cacheControl","move","readVisitorUpload","isNotFound","deleteObject","object","releaseCounted","deleted","deleteVisitorUpload","startsWith","includes","split","deleteVisitorUploads","listed","getFiles","prefix","Promise","all","map","ascii","replace","kind","encodeURIComponent","visitorUploadResponseHeaders","sendVisitorUploadFile","res","value","Object","entries","setHeader","createReadStream"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,WAAW,EAAEC,eAAe,QAAQ,cAAa;AACtE,SAASC,QAAQ,QAAQ,uBAAsB;AAE/C,SACEC,kBAAkB,EAClBC,4BAA4B,QACvB,2CAA0C;AACjD,SAASC,eAAe,EAAEC,iBAAiB,QAAQ,sCAAqC;AACxF,SACEC,yBAAyB,EACzBC,oBAAoB,EACpBC,sBAAsB,EACtBC,sBAAsB,EACtBC,mBAAmB,EACnBC,qBAAqB,EACrBC,wBAAwB,EACxBC,mBAAmB,EACnBC,4BAA4B,EAC5BC,4BAA4B,EAC5BC,wBAAwB,EACxBC,4BAA4B,QAIvB,wCAAuC;AAC9C,SACEC,iBAAiB,QAEZ,yDAAwD;AAC/D,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,sBAAsB,QAAQ,gBAAY;AACnD,SAASC,gBAAgB,QAAQ,wBAAoB;AAiJrD,OAAO,SAASC;IACd,OAAO;QACL,6EAA6E;QAC7E,4EAA4E;QAC5EC,QAAQ,IACNJ,cACGK,GAAG,GACHC,OAAO,GACPF,MAAM,CAACG,QAAQC,GAAG,CAAC,sCAAsC,IAAIC;QAClEP,kBAAkB,CAACQ,KAAKC,UAAYT,iBAAiBQ,KAAKC;QAC1DC,eAAe,UAAY,AAAC,MAAMX,uBAAuB;gBAAEY,SAAS;YAAU,OAAQ;QACtFC,QAAQ;YACN,MAAMA,SAASP,QAAQC,GAAG,CAAC,uBAAuB;YAClD,IAAI,CAACM,QAAQ,MAAM,IAAIC,MAAM;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