@aglyn/tenant-data-admin 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,6 +25,7 @@ import { FieldValue } from "firebase-admin/firestore";
25
25
  import firebaseAdmin from "./firebase-admin.js";
26
26
  import { deleteHostProjectionForAllMembers, syncHostProjectionForMembers } from "./host-memberships.js";
27
27
  import { syncOrgAuthProjections } from "./organizations.js";
28
+ import { sweepScopeSharingAfterSiteChange } from "./scope-sharing-sweep.js";
28
29
  import { SENDING_LABELS_COLLECTION } from "./host-sending-domain.js";
29
30
  import { SENDING_DOMAINS_COLLECTION } from "./sending-domains.js";
30
31
  import { TRACKING_HOSTS_COLLECTION } from "./tracking-hosts.js";
@@ -332,6 +333,21 @@ const consentHoldMessage = (hold)=>hold.reason === 'grouped' ? `The site is in t
332
333
  }, {
333
334
  merge: true
334
335
  });
336
+ // Documents shared with all sites except some name their sites, and this
337
+ // site just moved between the two lists they are worked out from. Both never
338
+ // throw, and come before anything below that could.
339
+ await sweepScopeSharingAfterSiteChange({
340
+ orgId: toOrgId,
341
+ reason: 'site-added',
342
+ hostId
343
+ });
344
+ if (fromOrgId) {
345
+ await sweepScopeSharingAfterSiteChange({
346
+ orgId: fromOrgId,
347
+ reason: 'site-removed',
348
+ hostId
349
+ });
350
+ }
335
351
  if (fromRef && fromOrgId) {
336
352
  // The old roster's per-site grants on this site, then its projections.
337
353
  const grants = await fromRef.collection('members').get();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/transfer-host.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 type ConsentGroupSiteHold,\n consentGroupSiteHold,\n} from '@aglyn/aglyn/app-utils/consent-groups'\nimport { holdsDedicatedSendingDomain } from '@aglyn/aglyn/app-utils/dedicated-sending-domain'\nimport type { HostTransferHold, HostTransferPlan } from '@aglyn/aglyn/app-utils/host-transfer'\nimport { checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { resolveHostEnabledPlugins } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport { listPluginOrgCollections } from '@aglyn/aglyn/plugin-manager/plugin-host-collections'\nimport { normalizeSendingDomain } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\nimport {\n deleteHostProjectionForAllMembers,\n syncHostProjectionForMembers,\n} from './host-memberships'\nimport { syncOrgAuthProjections } from './organizations'\nimport { SENDING_LABELS_COLLECTION } from './host-sending-domain'\nimport { SENDING_DOMAINS_COLLECTION } from './sending-domains'\nimport { TRACKING_HOSTS_COLLECTION } from './tracking-hosts'\n\n/*\n * MOVING A SITE TO ANOTHER ORGANIZATION (AGL-3381).\n *\n * A site's CONTENT lives under `hosts/{hostId}` and goes wherever the site\n * goes: pages, layouts, versions, forms and their submissions, its members,\n * collections, orders. What ties it to its organization is a handful of\n * pointers and projections, and those are what a transfer rewrites:\n *\n * hosts/{hostId} orgId, and memberRoles / memberPermissions\n * recomputed from the NEW roster (replaced whole,\n * so the old organization's people drop out)\n * hostIndex/{hostId} orgId — how routing resolves the owner\n * orgs/{from} hosts[hostId], and the site's paid seat pools\n * (registerAllocations, collaboratorAllocations)\n * released back to the old organization\n * orgs/{from}/members/* hostAccess[hostId], hostPermissions[hostId]\n * users/{uid}/hostMemberships/{hostId}\n * the old members' rows deleted, the new ones'\n * written\n * orgs/{to} hosts[hostId]\n *\n * The dedicated sending domain moves with it, because the reputation a\n * domain has earned is the site's: its record and its click-tracking host\n * move from `orgs/{from}` to `orgs/{to}`, and the label claim names the new\n * organization. It moves only to an organization whose plan may hold one.\n *\n * ## What stays with the old organization, and why\n *\n * Media `orgs/{from}/media`, stored under that organization's own\n * object prefix. Published pages reference it by address, so\n * the site keeps showing it; moving it would mean copying\n * objects and rewriting every page version that names them.\n * The plan counts it so staff can say so.\n * Records the site filed for its organization — CRM, datasets, lists —\n * are that organization's customer data.\n * Plugin documents a site OWNS on the organization (a declared\n * `siteField`, e.g. sends made as the site) stay as the old\n * organization's history: they name its lists, its\n * containers and the consent it relied on. A plugin that has\n * work still in flight on them (`holdsTransferWhile`) holds\n * the transfer until it lands or is cancelled.\n *\n * ## What refuses a transfer\n *\n * the site or either organization is missing, or it is already there;\n * the site is in a consent group, or a group change naming it is running\n * (its refusals are read by its siblings — it leaves the group first);\n * the destination is at its site limit, unless staff override it;\n * the site holds a dedicated sending domain the destination's plan\n * cannot hold (release it first);\n * a plugin reports work in flight on documents the site owns.\n */\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport type { HostTransferHold, HostTransferPlan } from '@aglyn/aglyn/app-utils/host-transfer'\n\nexport interface PlanHostTransferInput {\n hostId: string\n toOrgId: string\n /** Staff may place a site past the destination's site limit. */\n overrideSiteLimit?: boolean\n}\n\nconst count = async (query: FirebaseFirestore.Query): Promise<number> =>\n (await query.count().get()).data().count\n\nconst consentHoldMessage = (hold: ConsentGroupSiteHold): string =>\n hold.reason === 'grouped'\n ? `The site is in the consent group \"${hold.name}\". Remove it from the group first — its opt-outs are read by the other sites in it.`\n : 'A consent group change naming this site has not finished. Wait for it, then transfer.'\n\n/** How many sites an organization holds: its directory or its query, whichever is larger. */\nasync function sitesHeld(\n db: FirebaseFirestore.Firestore,\n orgId: string,\n org: Record<string, unknown>,\n): Promise<number> {\n const directory = org['hosts']\n const mapped =\n directory && typeof directory === 'object'\n ? Object.values(directory as Record<string, unknown>).filter(Boolean).length\n : 0\n const queried = await count(db.collection('hosts').where('orgId', '==', orgId))\n return Math.max(mapped, queried)\n}\n\n/**\n * The transfer, worked out and not performed. Read only: safe to call for a\n * confirmation dialog, and called again by {@link transferHost} so what runs\n * is what was decided a moment ago, not what was true when the dialog opened.\n */\nexport async function planHostTransfer(input: PlanHostTransferInput): Promise<HostTransferPlan> {\n const db = firestore()\n const hostId = String(input.hostId ?? '').trim()\n const toOrgId = String(input.toOrgId ?? '').trim()\n const holds: HostTransferHold[] = []\n const warnings: string[] = []\n const host = hostId ? await db.collection('hosts').doc(hostId).get() : null\n const hostData = (host?.exists ? host.data() : null) ?? null\n const fromOrgId = typeof hostData?.['orgId'] === 'string' ? (hostData['orgId'] as string) : null\n const [fromOrg, toOrg] = await Promise.all([\n fromOrgId ? db.collection('orgs').doc(fromOrgId).get() : Promise.resolve(null),\n toOrgId ? db.collection('orgs').doc(toOrgId).get() : Promise.resolve(null),\n ])\n const fromData = (fromOrg?.exists ? fromOrg.data() : null) ?? null\n const toData = (toOrg?.exists ? toOrg.data() : null) ?? null\n\n const plan: HostTransferPlan = {\n hostId,\n siteName: (hostData?.['displayName'] as string | undefined) ?? null,\n fromOrgId,\n fromOrgName: (fromData?.['name'] as string | undefined) ?? null,\n toOrgId,\n toOrgName: (toData?.['name'] as string | undefined) ?? null,\n holds,\n warnings,\n facts: {\n mediaStaying: 0,\n ownedDocumentsStaying: [],\n collaboratorsLosingAccess: 0,\n sendingDomain: null,\n pluginsLost: [],\n siteLimit: { used: 0, limit: 0, allowed: true },\n },\n }\n\n if (!hostData) {\n holds.push({ code: 'no-site', message: 'There is no such site.' })\n return plan\n }\n if (!toData) {\n holds.push({ code: 'no-destination', message: 'There is no such destination organization.' })\n return plan\n }\n if (fromOrgId === toOrgId) {\n holds.push({ code: 'same-organization', message: 'The site already belongs to that organization.' })\n return plan\n }\n\n // Consent: the site's refusals are its siblings' too.\n const consentHold = fromData ? consentGroupSiteHold(fromData, hostId) : null\n if (consentHold) holds.push({ code: 'consent-group', message: consentHoldMessage(consentHold) })\n\n // The destination's site limit, counted the way site creation counts it.\n const used = await sitesHeld(db, toOrgId, toData)\n const quota = checkQuota(toData as never, 'hostLimit', used)\n plan.facts.siteLimit = { used, limit: quota.limit, allowed: quota.allowed }\n if (!quota.allowed) {\n if (input.overrideSiteLimit) {\n warnings.push(\n `The destination is at its site limit (${used} of ${quota.limit}); the transfer places this site past it.`,\n )\n } else {\n holds.push({\n code: 'site-limit',\n message: `The destination holds ${used} of its ${quota.limit} sites. Raise its limit, or override it.`,\n })\n }\n }\n\n // The dedicated sending domain moves only to a plan that may hold one.\n const sendingDomain = normalizeSendingDomain(String(hostData['sendingDomain'] ?? '')) || null\n const sendingLabel = String(hostData['sendingLabel'] ?? '').trim()\n if (sendingLabel || sendingDomain) {\n plan.facts.sendingDomain = sendingDomain ?? sendingLabel\n if (!holdsDedicatedSendingDomain(toData as never)) {\n holds.push({\n code: 'sending-domain',\n message:\n `The site sends as ${plan.facts.sendingDomain}, and the destination's plan cannot hold a ` +\n 'dedicated sending domain. Release it from the site first, or raise the destination’s plan.',\n })\n } else {\n warnings.push(`The dedicated sending domain ${plan.facts.sendingDomain} moves with the site.`)\n }\n }\n\n if (fromOrgId) {\n // Plugin documents the site owns on the old organization, and any still\n // in flight — each plugin's own declaration says which field and which\n // states, so no collection is named here.\n for (const declared of listPluginOrgCollections()) {\n if (!declared.siteField) continue\n const owned = db\n .collection('orgs')\n .doc(fromOrgId)\n .collection(declared.name)\n .where(declared.siteField, '==', hostId)\n const held = await count(owned).catch(() => 0)\n if (held) plan.facts.ownedDocumentsStaying.push({ collection: declared.name, count: held })\n const hold = declared.holdsTransferWhile\n if (held && hold) {\n const moving = await count(owned.where(hold.field, 'in', hold.values)).catch(() => 0)\n if (moving) {\n holds.push({\n code: 'in-flight',\n message:\n `${moving} ${declared.label ?? declared.name} of this site ${moving === 1 ? 'is' : 'are'} ` +\n `still ${hold.values.join(' or ')}. Let ${moving === 1 ? 'it' : 'them'} finish or cancel ` +\n `${moving === 1 ? 'it' : 'them'} first.`,\n })\n }\n }\n }\n if (plan.facts.ownedDocumentsStaying.length) {\n warnings.push(\n 'Records the site made for its old organization (' +\n plan.facts.ownedDocumentsStaying.map((row) => `${row.count} ${row.collection}`).join(', ') +\n ') stay there as its history.',\n )\n }\n\n plan.facts.mediaStaying = await count(\n db\n .collection('orgs')\n .doc(fromOrgId)\n .collection('media')\n .where('visibleTo', 'array-contains', hostScopeToken(hostId)),\n ).catch(() => 0)\n if (plan.facts.mediaStaying) {\n warnings.push(\n `${plan.facts.mediaStaying} media file(s) stay in the old organization's library. The site keeps ` +\n 'showing them, but only the old organization can manage them — deleting them there removes them from this site.',\n )\n }\n\n // Collaborators: old members who reached this site only through a grant.\n const members = await db.collection('orgs').doc(fromOrgId).collection('members').get()\n plan.facts.collaboratorsLosingAccess = members.docs.filter(\n (member) =>\n member.get('allHosts') !== true &&\n member.get('role') !== 'owner' &&\n Boolean((member.get('hostAccess') ?? {})[hostId]),\n ).length\n if (plan.facts.collaboratorsLosingAccess) {\n warnings.push(\n `${plan.facts.collaboratorsLosingAccess} collaborator(s) of the old organization lose access to the site.`,\n )\n }\n\n const before = resolveHostEnabledPlugins(fromData as never, hostData as never)\n const after = new Set(resolveHostEnabledPlugins(toData as never, hostData as never))\n plan.facts.pluginsLost = before.filter((id) => !after.has(id))\n if (plan.facts.pluginsLost.length) {\n warnings.push(\n `The destination does not enable ${plan.facts.pluginsLost.join(', ')}; what they draw on the site stops rendering.`,\n )\n }\n }\n\n if (toData['suspendedAt']) {\n warnings.push('The destination organization is suspended, so the site goes offline with it.')\n }\n return plan\n}\n\n/** A transfer refused by its plan: nothing was written. */\nexport class HostTransferRefusedError extends Error {\n readonly plan: HostTransferPlan\n\n constructor(plan: HostTransferPlan) {\n super(plan.holds.map((hold) => hold.message).join(' '))\n this.name = 'HostTransferRefusedError'\n this.plan = plan\n }\n}\n\n/** Move one document from one path to another, deleting the original. */\nasync function moveDocument(\n from: FirebaseFirestore.DocumentReference,\n to: FirebaseFirestore.DocumentReference,\n): Promise<boolean> {\n const snapshot = await from.get()\n if (!snapshot.exists) return false\n await to.set(snapshot.data() ?? {})\n await from.delete()\n return true\n}\n\n/**\n * Move a site to another organization (AGL-3381). Re-plans first and refuses\n * — writing nothing — when the plan holds; see the header for what moves,\n * what stays, and why.\n *\n * The ownership flip is one transaction over the site and both organization\n * documents, re-reading the site's organization inside it, so two transfers\n * of one site cannot both land. The site's access list is rebuilt straight\n * after it, before anything else. Everything after the flip is a projection\n * of it, recomputed from the documents rather than carried from the plan, so\n * a failure part-way is finished by running the projections again\n * ({@link syncOrgAuthProjections} and the membership sync).\n *\n * A site that belongs to no organization — left behind by a failed create or\n * a hand edit — is given one the same way, with nothing to release.\n */\nexport async function transferHost(input: PlanHostTransferInput): Promise<HostTransferPlan> {\n const plan = await planHostTransfer(input)\n if (plan.holds.length) throw new HostTransferRefusedError(plan)\n const db = firestore()\n const { hostId, toOrgId, fromOrgId } = plan\n const hostRef = db.collection('hosts').doc(hostId)\n const fromRef = fromOrgId ? db.collection('orgs').doc(fromOrgId) : null\n const toRef = db.collection('orgs').doc(toOrgId)\n\n await db.runTransaction(async (tx) => {\n const current = await tx.get(hostRef)\n if ((current.get('orgId') ?? null) !== fromOrgId) {\n throw new HostTransferRefusedError({\n ...plan,\n holds: [{ code: 'same-organization', message: 'The site changed organization while this ran.' }],\n })\n }\n if (fromRef) {\n tx.set(\n fromRef,\n {\n hosts: { [hostId]: FieldValue.delete() },\n registerAllocations: { [hostId]: FieldValue.delete() },\n collaboratorAllocations: { [hostId]: FieldValue.delete() },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n }\n tx.set(\n toRef,\n { hosts: { [hostId]: true }, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n tx.update(hostRef, { orgId: toOrgId, updatedAt: FieldValue.serverTimestamp() })\n })\n\n // FIRST after the flip: the site's access list, rebuilt whole from the new\n // roster. Until this lands the old organization's people still hold the\n // keys the rules read, so nothing may run ahead of it.\n await syncOrgAuthProjections(toOrgId, hostId)\n // Routing names the new owner.\n await db.collection('hostIndex').doc(hostId).set({ orgId: toOrgId }, { merge: true })\n\n if (fromRef && fromOrgId) {\n // The old roster's per-site grants on this site, then its projections.\n const grants = await fromRef.collection('members').get()\n for (let at = 0; at < grants.docs.length; at += 400) {\n const batch = db.batch()\n for (const member of grants.docs.slice(at, at + 400)) {\n const access = member.get('hostAccess') ?? {}\n const permissions = member.get('hostPermissions') ?? {}\n if (!(hostId in access) && !(hostId in permissions)) continue\n batch.update(member.ref, {\n [`hostAccess.${hostId}`]: FieldValue.delete(),\n [`hostPermissions.${hostId}`]: FieldValue.delete(),\n })\n }\n await batch.commit()\n }\n await deleteHostProjectionForAllMembers(fromOrgId, hostId)\n await syncOrgAuthProjections(fromOrgId)\n }\n await syncHostProjectionForMembers(toOrgId, hostId)\n\n // The dedicated sending domain and its click-tracking host.\n const current = await hostRef.get()\n const domain = normalizeSendingDomain(String(current.get('sendingDomain') ?? '')) || null\n const label = String(current.get('sendingLabel') ?? '').trim()\n if (domain && fromRef) {\n for (const collection of [SENDING_DOMAINS_COLLECTION, TRACKING_HOSTS_COLLECTION]) {\n await moveDocument(\n fromRef.collection(collection).doc(domain),\n toRef.collection(collection).doc(domain),\n )\n }\n }\n if (label) {\n const claim = db.collection(SENDING_LABELS_COLLECTION).doc(label)\n if ((await claim.get()).exists) await claim.update({ orgId: toOrgId })\n }\n\n return plan\n}\n"],"names":["consentGroupSiteHold","holdsDedicatedSendingDomain","checkQuota","hostScopeToken","resolveHostEnabledPlugins","listPluginOrgCollections","normalizeSendingDomain","FieldValue","firebaseAdmin","deleteHostProjectionForAllMembers","syncHostProjectionForMembers","syncOrgAuthProjections","SENDING_LABELS_COLLECTION","SENDING_DOMAINS_COLLECTION","TRACKING_HOSTS_COLLECTION","firestore","app","count","query","get","data","consentHoldMessage","hold","reason","name","sitesHeld","db","orgId","org","directory","mapped","Object","values","filter","Boolean","length","queried","collection","where","Math","max","planHostTransfer","input","host","fromOrg","toOrg","hostData","hostId","String","trim","toOrgId","holds","warnings","doc","exists","fromOrgId","Promise","all","resolve","fromData","toData","plan","siteName","fromOrgName","toOrgName","facts","mediaStaying","ownedDocumentsStaying","collaboratorsLosingAccess","sendingDomain","pluginsLost","siteLimit","used","limit","allowed","push","code","message","consentHold","quota","overrideSiteLimit","sendingLabel","declared","siteField","owned","held","catch","holdsTransferWhile","moving","field","label","join","map","row","members","docs","member","before","after","Set","id","has","HostTransferRefusedError","Error","moveDocument","from","to","snapshot","set","delete","transferHost","current","hostRef","fromRef","toRef","runTransaction","tx","hosts","registerAllocations","collaboratorAllocations","updatedAt","serverTimestamp","merge","update","grants","at","batch","slice","access","permissions","ref","commit","domain","claim"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,oBAAoB,QACf,wCAAuC;AAC9C,SAASC,2BAA2B,QAAQ,kDAAiD;AAE7F,SAASC,UAAU,QAAQ,2CAA0C;AACrE,SAASC,cAAc,QAAQ,sCAAqC;AACpE,SAASC,yBAAyB,QAAQ,8CAA6C;AACvF,SAASC,wBAAwB,QAAQ,sDAAqD;AAC9F,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,OAAOC,mBAAmB,sBAAkB;AAC5C,SACEC,iCAAiC,EACjCC,4BAA4B,QACvB,wBAAoB;AAC3B,SAASC,sBAAsB,QAAQ,qBAAiB;AACxD,SAASC,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,0BAA0B,QAAQ,uBAAmB;AAC9D,SAASC,yBAAyB,QAAQ,sBAAkB;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmDC,GAED,MAAMC,YAAY,IAAMP,cAAcQ,GAAG,GAAGD,SAAS;AAWrD,MAAME,QAAQ,OAAOC,QACnB,AAAC,CAAA,MAAM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+E,MAAMV,MAAM,CAAC;YAAEhG,OAAOuB;QAAQ;IACtE;IAEA,OAAOW;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/transfer-host.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 type ConsentGroupSiteHold,\n consentGroupSiteHold,\n} from '@aglyn/aglyn/app-utils/consent-groups'\nimport { holdsDedicatedSendingDomain } from '@aglyn/aglyn/app-utils/dedicated-sending-domain'\nimport type { HostTransferHold, HostTransferPlan } from '@aglyn/aglyn/app-utils/host-transfer'\nimport { checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { resolveHostEnabledPlugins } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport { listPluginOrgCollections } from '@aglyn/aglyn/plugin-manager/plugin-host-collections'\nimport { normalizeSendingDomain } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\nimport {\n deleteHostProjectionForAllMembers,\n syncHostProjectionForMembers,\n} from './host-memberships'\nimport { syncOrgAuthProjections } from './organizations'\nimport { sweepScopeSharingAfterSiteChange } from './scope-sharing-sweep'\nimport { SENDING_LABELS_COLLECTION } from './host-sending-domain'\nimport { SENDING_DOMAINS_COLLECTION } from './sending-domains'\nimport { TRACKING_HOSTS_COLLECTION } from './tracking-hosts'\n\n/*\n * MOVING A SITE TO ANOTHER ORGANIZATION (AGL-3381).\n *\n * A site's CONTENT lives under `hosts/{hostId}` and goes wherever the site\n * goes: pages, layouts, versions, forms and their submissions, its members,\n * collections, orders. What ties it to its organization is a handful of\n * pointers and projections, and those are what a transfer rewrites:\n *\n * hosts/{hostId} orgId, and memberRoles / memberPermissions\n * recomputed from the NEW roster (replaced whole,\n * so the old organization's people drop out)\n * hostIndex/{hostId} orgId — how routing resolves the owner\n * orgs/{from} hosts[hostId], and the site's paid seat pools\n * (registerAllocations, collaboratorAllocations)\n * released back to the old organization\n * orgs/{from}/members/* hostAccess[hostId], hostPermissions[hostId]\n * users/{uid}/hostMemberships/{hostId}\n * the old members' rows deleted, the new ones'\n * written\n * orgs/{to} hosts[hostId]\n *\n * The dedicated sending domain moves with it, because the reputation a\n * domain has earned is the site's: its record and its click-tracking host\n * move from `orgs/{from}` to `orgs/{to}`, and the label claim names the new\n * organization. It moves only to an organization whose plan may hold one.\n *\n * ## What stays with the old organization, and why\n *\n * Media `orgs/{from}/media`, stored under that organization's own\n * object prefix. Published pages reference it by address, so\n * the site keeps showing it; moving it would mean copying\n * objects and rewriting every page version that names them.\n * The plan counts it so staff can say so.\n * Records the site filed for its organization — CRM, datasets, lists —\n * are that organization's customer data.\n * Plugin documents a site OWNS on the organization (a declared\n * `siteField`, e.g. sends made as the site) stay as the old\n * organization's history: they name its lists, its\n * containers and the consent it relied on. A plugin that has\n * work still in flight on them (`holdsTransferWhile`) holds\n * the transfer until it lands or is cancelled.\n *\n * ## What refuses a transfer\n *\n * the site or either organization is missing, or it is already there;\n * the site is in a consent group, or a group change naming it is running\n * (its refusals are read by its siblings — it leaves the group first);\n * the destination is at its site limit, unless staff override it;\n * the site holds a dedicated sending domain the destination's plan\n * cannot hold (release it first);\n * a plugin reports work in flight on documents the site owns.\n */\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport type { HostTransferHold, HostTransferPlan } from '@aglyn/aglyn/app-utils/host-transfer'\n\nexport interface PlanHostTransferInput {\n hostId: string\n toOrgId: string\n /** Staff may place a site past the destination's site limit. */\n overrideSiteLimit?: boolean\n}\n\nconst count = async (query: FirebaseFirestore.Query): Promise<number> =>\n (await query.count().get()).data().count\n\nconst consentHoldMessage = (hold: ConsentGroupSiteHold): string =>\n hold.reason === 'grouped'\n ? `The site is in the consent group \"${hold.name}\". Remove it from the group first — its opt-outs are read by the other sites in it.`\n : 'A consent group change naming this site has not finished. Wait for it, then transfer.'\n\n/** How many sites an organization holds: its directory or its query, whichever is larger. */\nasync function sitesHeld(\n db: FirebaseFirestore.Firestore,\n orgId: string,\n org: Record<string, unknown>,\n): Promise<number> {\n const directory = org['hosts']\n const mapped =\n directory && typeof directory === 'object'\n ? Object.values(directory as Record<string, unknown>).filter(Boolean).length\n : 0\n const queried = await count(db.collection('hosts').where('orgId', '==', orgId))\n return Math.max(mapped, queried)\n}\n\n/**\n * The transfer, worked out and not performed. Read only: safe to call for a\n * confirmation dialog, and called again by {@link transferHost} so what runs\n * is what was decided a moment ago, not what was true when the dialog opened.\n */\nexport async function planHostTransfer(input: PlanHostTransferInput): Promise<HostTransferPlan> {\n const db = firestore()\n const hostId = String(input.hostId ?? '').trim()\n const toOrgId = String(input.toOrgId ?? '').trim()\n const holds: HostTransferHold[] = []\n const warnings: string[] = []\n const host = hostId ? await db.collection('hosts').doc(hostId).get() : null\n const hostData = (host?.exists ? host.data() : null) ?? null\n const fromOrgId = typeof hostData?.['orgId'] === 'string' ? (hostData['orgId'] as string) : null\n const [fromOrg, toOrg] = await Promise.all([\n fromOrgId ? db.collection('orgs').doc(fromOrgId).get() : Promise.resolve(null),\n toOrgId ? db.collection('orgs').doc(toOrgId).get() : Promise.resolve(null),\n ])\n const fromData = (fromOrg?.exists ? fromOrg.data() : null) ?? null\n const toData = (toOrg?.exists ? toOrg.data() : null) ?? null\n\n const plan: HostTransferPlan = {\n hostId,\n siteName: (hostData?.['displayName'] as string | undefined) ?? null,\n fromOrgId,\n fromOrgName: (fromData?.['name'] as string | undefined) ?? null,\n toOrgId,\n toOrgName: (toData?.['name'] as string | undefined) ?? null,\n holds,\n warnings,\n facts: {\n mediaStaying: 0,\n ownedDocumentsStaying: [],\n collaboratorsLosingAccess: 0,\n sendingDomain: null,\n pluginsLost: [],\n siteLimit: { used: 0, limit: 0, allowed: true },\n },\n }\n\n if (!hostData) {\n holds.push({ code: 'no-site', message: 'There is no such site.' })\n return plan\n }\n if (!toData) {\n holds.push({ code: 'no-destination', message: 'There is no such destination organization.' })\n return plan\n }\n if (fromOrgId === toOrgId) {\n holds.push({ code: 'same-organization', message: 'The site already belongs to that organization.' })\n return plan\n }\n\n // Consent: the site's refusals are its siblings' too.\n const consentHold = fromData ? consentGroupSiteHold(fromData, hostId) : null\n if (consentHold) holds.push({ code: 'consent-group', message: consentHoldMessage(consentHold) })\n\n // The destination's site limit, counted the way site creation counts it.\n const used = await sitesHeld(db, toOrgId, toData)\n const quota = checkQuota(toData as never, 'hostLimit', used)\n plan.facts.siteLimit = { used, limit: quota.limit, allowed: quota.allowed }\n if (!quota.allowed) {\n if (input.overrideSiteLimit) {\n warnings.push(\n `The destination is at its site limit (${used} of ${quota.limit}); the transfer places this site past it.`,\n )\n } else {\n holds.push({\n code: 'site-limit',\n message: `The destination holds ${used} of its ${quota.limit} sites. Raise its limit, or override it.`,\n })\n }\n }\n\n // The dedicated sending domain moves only to a plan that may hold one.\n const sendingDomain = normalizeSendingDomain(String(hostData['sendingDomain'] ?? '')) || null\n const sendingLabel = String(hostData['sendingLabel'] ?? '').trim()\n if (sendingLabel || sendingDomain) {\n plan.facts.sendingDomain = sendingDomain ?? sendingLabel\n if (!holdsDedicatedSendingDomain(toData as never)) {\n holds.push({\n code: 'sending-domain',\n message:\n `The site sends as ${plan.facts.sendingDomain}, and the destination's plan cannot hold a ` +\n 'dedicated sending domain. Release it from the site first, or raise the destination’s plan.',\n })\n } else {\n warnings.push(`The dedicated sending domain ${plan.facts.sendingDomain} moves with the site.`)\n }\n }\n\n if (fromOrgId) {\n // Plugin documents the site owns on the old organization, and any still\n // in flight — each plugin's own declaration says which field and which\n // states, so no collection is named here.\n for (const declared of listPluginOrgCollections()) {\n if (!declared.siteField) continue\n const owned = db\n .collection('orgs')\n .doc(fromOrgId)\n .collection(declared.name)\n .where(declared.siteField, '==', hostId)\n const held = await count(owned).catch(() => 0)\n if (held) plan.facts.ownedDocumentsStaying.push({ collection: declared.name, count: held })\n const hold = declared.holdsTransferWhile\n if (held && hold) {\n const moving = await count(owned.where(hold.field, 'in', hold.values)).catch(() => 0)\n if (moving) {\n holds.push({\n code: 'in-flight',\n message:\n `${moving} ${declared.label ?? declared.name} of this site ${moving === 1 ? 'is' : 'are'} ` +\n `still ${hold.values.join(' or ')}. Let ${moving === 1 ? 'it' : 'them'} finish or cancel ` +\n `${moving === 1 ? 'it' : 'them'} first.`,\n })\n }\n }\n }\n if (plan.facts.ownedDocumentsStaying.length) {\n warnings.push(\n 'Records the site made for its old organization (' +\n plan.facts.ownedDocumentsStaying.map((row) => `${row.count} ${row.collection}`).join(', ') +\n ') stay there as its history.',\n )\n }\n\n plan.facts.mediaStaying = await count(\n db\n .collection('orgs')\n .doc(fromOrgId)\n .collection('media')\n .where('visibleTo', 'array-contains', hostScopeToken(hostId)),\n ).catch(() => 0)\n if (plan.facts.mediaStaying) {\n warnings.push(\n `${plan.facts.mediaStaying} media file(s) stay in the old organization's library. The site keeps ` +\n 'showing them, but only the old organization can manage them — deleting them there removes them from this site.',\n )\n }\n\n // Collaborators: old members who reached this site only through a grant.\n const members = await db.collection('orgs').doc(fromOrgId).collection('members').get()\n plan.facts.collaboratorsLosingAccess = members.docs.filter(\n (member) =>\n member.get('allHosts') !== true &&\n member.get('role') !== 'owner' &&\n Boolean((member.get('hostAccess') ?? {})[hostId]),\n ).length\n if (plan.facts.collaboratorsLosingAccess) {\n warnings.push(\n `${plan.facts.collaboratorsLosingAccess} collaborator(s) of the old organization lose access to the site.`,\n )\n }\n\n const before = resolveHostEnabledPlugins(fromData as never, hostData as never)\n const after = new Set(resolveHostEnabledPlugins(toData as never, hostData as never))\n plan.facts.pluginsLost = before.filter((id) => !after.has(id))\n if (plan.facts.pluginsLost.length) {\n warnings.push(\n `The destination does not enable ${plan.facts.pluginsLost.join(', ')}; what they draw on the site stops rendering.`,\n )\n }\n }\n\n if (toData['suspendedAt']) {\n warnings.push('The destination organization is suspended, so the site goes offline with it.')\n }\n return plan\n}\n\n/** A transfer refused by its plan: nothing was written. */\nexport class HostTransferRefusedError extends Error {\n readonly plan: HostTransferPlan\n\n constructor(plan: HostTransferPlan) {\n super(plan.holds.map((hold) => hold.message).join(' '))\n this.name = 'HostTransferRefusedError'\n this.plan = plan\n }\n}\n\n/** Move one document from one path to another, deleting the original. */\nasync function moveDocument(\n from: FirebaseFirestore.DocumentReference,\n to: FirebaseFirestore.DocumentReference,\n): Promise<boolean> {\n const snapshot = await from.get()\n if (!snapshot.exists) return false\n await to.set(snapshot.data() ?? {})\n await from.delete()\n return true\n}\n\n/**\n * Move a site to another organization (AGL-3381). Re-plans first and refuses\n * — writing nothing — when the plan holds; see the header for what moves,\n * what stays, and why.\n *\n * The ownership flip is one transaction over the site and both organization\n * documents, re-reading the site's organization inside it, so two transfers\n * of one site cannot both land. The site's access list is rebuilt straight\n * after it, before anything else. Everything after the flip is a projection\n * of it, recomputed from the documents rather than carried from the plan, so\n * a failure part-way is finished by running the projections again\n * ({@link syncOrgAuthProjections} and the membership sync).\n *\n * A site that belongs to no organization — left behind by a failed create or\n * a hand edit — is given one the same way, with nothing to release.\n */\nexport async function transferHost(input: PlanHostTransferInput): Promise<HostTransferPlan> {\n const plan = await planHostTransfer(input)\n if (plan.holds.length) throw new HostTransferRefusedError(plan)\n const db = firestore()\n const { hostId, toOrgId, fromOrgId } = plan\n const hostRef = db.collection('hosts').doc(hostId)\n const fromRef = fromOrgId ? db.collection('orgs').doc(fromOrgId) : null\n const toRef = db.collection('orgs').doc(toOrgId)\n\n await db.runTransaction(async (tx) => {\n const current = await tx.get(hostRef)\n if ((current.get('orgId') ?? null) !== fromOrgId) {\n throw new HostTransferRefusedError({\n ...plan,\n holds: [{ code: 'same-organization', message: 'The site changed organization while this ran.' }],\n })\n }\n if (fromRef) {\n tx.set(\n fromRef,\n {\n hosts: { [hostId]: FieldValue.delete() },\n registerAllocations: { [hostId]: FieldValue.delete() },\n collaboratorAllocations: { [hostId]: FieldValue.delete() },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n }\n tx.set(\n toRef,\n { hosts: { [hostId]: true }, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n tx.update(hostRef, { orgId: toOrgId, updatedAt: FieldValue.serverTimestamp() })\n })\n\n // FIRST after the flip: the site's access list, rebuilt whole from the new\n // roster. Until this lands the old organization's people still hold the\n // keys the rules read, so nothing may run ahead of it.\n await syncOrgAuthProjections(toOrgId, hostId)\n // Routing names the new owner.\n await db.collection('hostIndex').doc(hostId).set({ orgId: toOrgId }, { merge: true })\n\n // Documents shared with all sites except some name their sites, and this\n // site just moved between the two lists they are worked out from. Both never\n // throw, and come before anything below that could.\n await sweepScopeSharingAfterSiteChange({ orgId: toOrgId, reason: 'site-added', hostId })\n if (fromOrgId) {\n await sweepScopeSharingAfterSiteChange({ orgId: fromOrgId, reason: 'site-removed', hostId })\n }\n\n if (fromRef && fromOrgId) {\n // The old roster's per-site grants on this site, then its projections.\n const grants = await fromRef.collection('members').get()\n for (let at = 0; at < grants.docs.length; at += 400) {\n const batch = db.batch()\n for (const member of grants.docs.slice(at, at + 400)) {\n const access = member.get('hostAccess') ?? {}\n const permissions = member.get('hostPermissions') ?? {}\n if (!(hostId in access) && !(hostId in permissions)) continue\n batch.update(member.ref, {\n [`hostAccess.${hostId}`]: FieldValue.delete(),\n [`hostPermissions.${hostId}`]: FieldValue.delete(),\n })\n }\n await batch.commit()\n }\n await deleteHostProjectionForAllMembers(fromOrgId, hostId)\n await syncOrgAuthProjections(fromOrgId)\n }\n await syncHostProjectionForMembers(toOrgId, hostId)\n\n // The dedicated sending domain and its click-tracking host.\n const current = await hostRef.get()\n const domain = normalizeSendingDomain(String(current.get('sendingDomain') ?? '')) || null\n const label = String(current.get('sendingLabel') ?? '').trim()\n if (domain && fromRef) {\n for (const collection of [SENDING_DOMAINS_COLLECTION, TRACKING_HOSTS_COLLECTION]) {\n await moveDocument(\n fromRef.collection(collection).doc(domain),\n toRef.collection(collection).doc(domain),\n )\n }\n }\n if (label) {\n const claim = db.collection(SENDING_LABELS_COLLECTION).doc(label)\n if ((await claim.get()).exists) await claim.update({ orgId: toOrgId })\n }\n\n return plan\n}\n"],"names":["consentGroupSiteHold","holdsDedicatedSendingDomain","checkQuota","hostScopeToken","resolveHostEnabledPlugins","listPluginOrgCollections","normalizeSendingDomain","FieldValue","firebaseAdmin","deleteHostProjectionForAllMembers","syncHostProjectionForMembers","syncOrgAuthProjections","sweepScopeSharingAfterSiteChange","SENDING_LABELS_COLLECTION","SENDING_DOMAINS_COLLECTION","TRACKING_HOSTS_COLLECTION","firestore","app","count","query","get","data","consentHoldMessage","hold","reason","name","sitesHeld","db","orgId","org","directory","mapped","Object","values","filter","Boolean","length","queried","collection","where","Math","max","planHostTransfer","input","host","fromOrg","toOrg","hostData","hostId","String","trim","toOrgId","holds","warnings","doc","exists","fromOrgId","Promise","all","resolve","fromData","toData","plan","siteName","fromOrgName","toOrgName","facts","mediaStaying","ownedDocumentsStaying","collaboratorsLosingAccess","sendingDomain","pluginsLost","siteLimit","used","limit","allowed","push","code","message","consentHold","quota","overrideSiteLimit","sendingLabel","declared","siteField","owned","held","catch","holdsTransferWhile","moving","field","label","join","map","row","members","docs","member","before","after","Set","id","has","HostTransferRefusedError","Error","moveDocument","from","to","snapshot","set","delete","transferHost","current","hostRef","fromRef","toRef","runTransaction","tx","hosts","registerAllocations","collaboratorAllocations","updatedAt","serverTimestamp","merge","update","grants","at","batch","slice","access","permissions","ref","commit","domain","claim"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,oBAAoB,QACf,wCAAuC;AAC9C,SAASC,2BAA2B,QA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,EAAEnF,QAAQ,CAAC,EAAEzC,WAAWuG,MAAM;oBAC3C,CAAC,CAAC,gBAAgB,EAAE9D,QAAQ,CAAC,EAAEzC,WAAWuG,MAAM;gBAClD;YACF;YACA,MAAMiB,MAAMK,MAAM;QACpB;QACA,MAAM3H,kCAAkC+C,WAAWR;QACnD,MAAMrC,uBAAuB6C;IAC/B;IACA,MAAM9C,6BAA6ByC,SAASH;IAE5C,4DAA4D;IAC5D,MAAMgE,UAAU,MAAMC,QAAQ7F,GAAG;IACjC,MAAMiH,SAAS/H,uBAAuB2C,QAAO+D,eAAAA,QAAQ5F,GAAG,CAAC,4BAAZ4F,eAAgC,QAAQ;IACrF,MAAMrB,QAAQ1C,QAAO+D,gBAAAA,QAAQ5F,GAAG,CAAC,2BAAZ4F,gBAA+B,IAAI9D,IAAI;IAC5D,IAAImF,UAAUnB,SAAS;QACrB,KAAK,MAAM5E,cAAc;YAACxB;YAA4BC;SAA0B,CAAE;YAChF,MAAM0F,aACJS,QAAQ5E,UAAU,CAACA,YAAYgB,GAAG,CAAC+E,SACnClB,MAAM7E,UAAU,CAACA,YAAYgB,GAAG,CAAC+E;QAErC;IACF;IACA,IAAI1C,OAAO;QACT,MAAM2C,QAAQ3G,GAAGW,UAAU,CAACzB,2BAA2ByC,GAAG,CAACqC;QAC3D,IAAI,AAAC,CAAA,MAAM2C,MAAMlH,GAAG,EAAC,EAAGmC,MAAM,EAAE,MAAM+E,MAAMV,MAAM,CAAC;YAAEhG,OAAOuB;QAAQ;IACtE;IAEA,OAAOW;AACT"}
@@ -38,6 +38,10 @@ export interface VisitorUploadObject {
38
38
  }): Promise<[Buffer] | Buffer[]>;
39
39
  save(data: Buffer, options: Record<string, unknown>): Promise<unknown>;
40
40
  move(destination: string): Promise<unknown>;
41
+ copy(destination: string, options?: {
42
+ contentType?: string;
43
+ metadata?: Record<string, string | null>;
44
+ }): Promise<unknown>;
41
45
  setMetadata(metadata: Record<string, unknown>): Promise<unknown>;
42
46
  delete(options?: {
43
47
  ignoreNotFound?: boolean;
@@ -179,6 +183,30 @@ export declare function finalizeVisitorUpload(deps: VisitorUploadDeps, input: {
179
183
  ok: true;
180
184
  file: VisitorUploadFile;
181
185
  } | VisitorUploadRefusal>;
186
+ /**
187
+ * Keeps a COPY of an object already in this bucket as a kept file of `scope`:
188
+ * a member choosing a media library file for a quote's proof, say, after the
189
+ * caller's route has decided they may read it and may attach it.
190
+ *
191
+ * It is an upload in every way but who sends the bytes. The object's real name,
192
+ * type and size meet what a ticket meets ({@link mintVisitorUploadTicket}), the
193
+ * bytes are copied to the same pending path a browser posts to, and
194
+ * {@link finalizeVisitorUpload} inspects, sanitizes, keeps and counts them. The
195
+ * copy carries none of the source's metadata, and a finalize that refuses it
196
+ * deletes it. From then on the kept file owes the source nothing: changing or
197
+ * deleting the source does not touch it.
198
+ */
199
+ export declare function keepVisitorUploadCopy(deps: VisitorUploadDeps, input: {
200
+ scope: VisitorUploadScope;
201
+ source: {
202
+ path: string;
203
+ name: string;
204
+ };
205
+ caller: VisitorUploadCaller;
206
+ }): Promise<{
207
+ ok: true;
208
+ file: VisitorUploadFile;
209
+ } | VisitorUploadRefusal>;
182
210
  /** A kept file's record, by its id within `scope`; null when there is none. */
183
211
  export declare function readVisitorUpload(deps: Pick<VisitorUploadDeps, 'bucket'>, scope: VisitorUploadScope, id: string): Promise<VisitorUploadFile | null>;
184
212
  /** Deletes one kept file and releases its bytes. Gone already is fine. */
@@ -112,14 +112,12 @@ function mintTicket(secret, payload) {
112
112
  return null;
113
113
  }
114
114
  }
115
- /**
116
- * A ticket and a signed upload for ONE file, after the caller's route has
117
- * decided the caller may upload for `scope`. Spends the rate limits; refused
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.
122
- */ export async function mintVisitorUploadTicket(deps, input) {
115
+ /*------------------------------------------
116
+ * Mint
117
+ *-----------------------------------------*/ /**
118
+ * What every file meets before any bytes move: the request's type and size,
119
+ * the platform's uploads pause, a member's storage band, and the rate limits.
120
+ */ async function admitVisitorUpload(deps, input) {
123
121
  var _input_limits;
124
122
  const { scope } = input;
125
123
  if (!isVisitorUploadScope(scope)) return refusal(400, 'scope', 'This upload is missing what it is for.');
@@ -158,7 +156,22 @@ function mintTicket(secret, payload) {
158
156
  });
159
157
  }
160
158
  }
161
- const { upload } = checked;
159
+ return {
160
+ upload: checked.upload
161
+ };
162
+ }
163
+ /**
164
+ * A ticket and a signed upload for ONE file, after the caller's route has
165
+ * decided the caller may upload for `scope`. Spends the rate limits; refused
166
+ * while the platform's uploads are paused, and a member's file when the
167
+ * workspace's storage band refuses it (never a visitor's). `maxBytes`
168
+ * narrows the 25 MB ceiling, never widens it; `kinds` narrows the types
169
+ * taken (a form field that asks for PDFs only), never widens them.
170
+ */ export async function mintVisitorUploadTicket(deps, input) {
171
+ const { scope } = input;
172
+ const admitted = await admitVisitorUpload(deps, input);
173
+ if ('error' in admitted) return admitted;
174
+ const { upload } = admitted;
162
175
  const id = deps.newId();
163
176
  const expiresAtMs = deps.now() + VISITOR_UPLOAD_TICKET_TTL_MS;
164
177
  const answer = await deps.bucket().file(visitorUploadPendingPath(scope, id)).generateSignedPostPolicyV4({
@@ -374,6 +387,65 @@ function mintTicket(secret, payload) {
374
387
  }
375
388
  };
376
389
  }
390
+ /*------------------------------------------
391
+ * Keeping a copy of a file already in Storage
392
+ *-----------------------------------------*/ /**
393
+ * Keeps a COPY of an object already in this bucket as a kept file of `scope`:
394
+ * a member choosing a media library file for a quote's proof, say, after the
395
+ * caller's route has decided they may read it and may attach it.
396
+ *
397
+ * It is an upload in every way but who sends the bytes. The object's real name,
398
+ * type and size meet what a ticket meets ({@link mintVisitorUploadTicket}), the
399
+ * bytes are copied to the same pending path a browser posts to, and
400
+ * {@link finalizeVisitorUpload} inspects, sanitizes, keeps and counts them. The
401
+ * copy carries none of the source's metadata, and a finalize that refuses it
402
+ * deletes it. From then on the kept file owes the source nothing: changing or
403
+ * deleting the source does not touch it.
404
+ */ export async function keepVisitorUploadCopy(deps, input) {
405
+ var _metadata_contentType;
406
+ const { scope, source, caller } = input;
407
+ const bucket = deps.bucket();
408
+ const original = bucket.file(source.path);
409
+ let metadata;
410
+ try {
411
+ metadata = first(await original.getMetadata());
412
+ } catch (error) {
413
+ if (!isNotFound(error)) throw error;
414
+ return refusal(409, 'missing', `We couldn’t find ${source.name}. Choose it again.`);
415
+ }
416
+ const admitted = await admitVisitorUpload(deps, {
417
+ scope,
418
+ request: {
419
+ name: source.name,
420
+ contentType: String((_metadata_contentType = metadata.contentType) != null ? _metadata_contentType : ''),
421
+ size: Number(metadata.size)
422
+ },
423
+ caller
424
+ });
425
+ if ('error' in admitted) return admitted;
426
+ const { upload } = admitted;
427
+ const id = deps.newId();
428
+ await original.copy(visitorUploadPendingPath(scope, id), {
429
+ // Written out, so the copy takes none of the source's metadata: no download token.
430
+ contentType: upload.type.contentType,
431
+ metadata: {}
432
+ });
433
+ const ticket = mintTicket(deps.secret(), {
434
+ h: scope.hostId,
435
+ p: scope.purpose,
436
+ i: scope.purposeId,
437
+ u: id,
438
+ t: upload.type.contentType,
439
+ s: upload.size,
440
+ n: upload.name,
441
+ e: deps.now() + VISITOR_UPLOAD_TICKET_TTL_MS
442
+ });
443
+ return finalizeVisitorUpload(deps, {
444
+ scope,
445
+ ticket,
446
+ caller
447
+ });
448
+ }
377
449
  /*------------------------------------------
378
450
  * Afterwards
379
451
  *-----------------------------------------*/ /** A kept file's record, by its id within `scope`; null when there is none. */ export async function readVisitorUpload(deps, scope, id) {
@@ -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_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;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EF,WAAmB;IAC3D,MAAM2D,QAAQzD,KAAK0D,OAAO,CAAC,iBAAiB,KAAKA,OAAO,CAAC,UAAU,QAAQ;IAC3E,MAAMC,OAAOrL,sBAAsBwH,eAAe,WAAW;IAC7D,OAAO,GAAG6D,KAAK,YAAY,EAAEF,MAAM,oBAAoB,EAAEG,mBAAmB5D,OAAO;AACrF;AAEA,4CAA4C,GAC5C,OAAO,SAAS6D,6BAA6BrE,IAAqD;IAChG,OAAO;QACL,gBAAgBA,KAAKM,WAAW;QAChC,uBAAuBmC,mBAAmBzC,KAAKQ,IAAI,EAAER,KAAKM,WAAW;QACrE,0BAA0B;QAC1B,wEAAwE;QACxE,2BAA2B;QAC3B,iBAAiB;QACjB,gBAAgB;QAChB,mBAAmB;QACnB,gCAAgC;IAClC;AACF;AAQA;;;CAGC,GACD,OAAO,eAAegE,sBACpB3F,IAAuC,EACvC4F,GAA0B,EAC1BvE,IAA8D;IAE9D,KAAK,MAAM,CAACQ,MAAMgE,MAAM,IAAIC,OAAOC,OAAO,CAACL,6BAA6BrE,OAAQuE,IAAII,SAAS,CAACnE,MAAMgE;IACpGD,IAAItI,MAAM,CAAC;IACX,MAAM7D,SAASuG,KAAKjF,MAAM,GAAGsG,IAAI,CAACA,KAAKsB,IAAI,EAAEsD,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 CheckedVisitorUpload,\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 * {@link keepVisitorUploadCopy} does both for a file already in Storage: a\n * member's media library file chosen for a quote's proof, whose bytes go\n * through the same checks a browser's do.\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 copy(destination: string, options?: { contentType?: string; metadata?: Record<string, string | null> }): 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\n/**\n * What every file meets before any bytes move: the request's type and size,\n * the platform's uploads pause, a member's storage band, and the rate limits.\n */\nasync function admitVisitorUpload(\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<{ upload: CheckedVisitorUpload } | 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 return { upload: checked.upload }\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 const admitted = await admitVisitorUpload(deps, input)\n if ('error' in admitted) return admitted\n const { upload } = admitted\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 * Keeping a copy of a file already in Storage\n *-----------------------------------------*/\n\n/**\n * Keeps a COPY of an object already in this bucket as a kept file of `scope`:\n * a member choosing a media library file for a quote's proof, say, after the\n * caller's route has decided they may read it and may attach it.\n *\n * It is an upload in every way but who sends the bytes. The object's real name,\n * type and size meet what a ticket meets ({@link mintVisitorUploadTicket}), the\n * bytes are copied to the same pending path a browser posts to, and\n * {@link finalizeVisitorUpload} inspects, sanitizes, keeps and counts them. The\n * copy carries none of the source's metadata, and a finalize that refuses it\n * deletes it. From then on the kept file owes the source nothing: changing or\n * deleting the source does not touch it.\n */\nexport async function keepVisitorUploadCopy(\n deps: VisitorUploadDeps,\n input: {\n scope: VisitorUploadScope\n source: { path: string; name: string }\n caller: VisitorUploadCaller\n },\n): Promise<{ ok: true; file: VisitorUploadFile } | VisitorUploadRefusal> {\n const { scope, source, caller } = input\n const bucket = deps.bucket()\n const original = bucket.file(source.path)\n let metadata: VisitorUploadObjectMetadata\n try {\n metadata = first(await original.getMetadata())\n } catch (error) {\n if (!isNotFound(error)) throw error\n return refusal(409, 'missing', `We couldn’t find ${source.name}. Choose it again.`)\n }\n const admitted = await admitVisitorUpload(deps, {\n scope,\n request: { name: source.name, contentType: String(metadata.contentType ?? ''), size: Number(metadata.size) },\n caller,\n })\n if ('error' in admitted) return admitted\n const { upload } = admitted\n const id = deps.newId()\n await original.copy(visitorUploadPendingPath(scope, id), {\n // Written out, so the copy takes none of the source's metadata: no download token.\n contentType: upload.type.contentType,\n metadata: {},\n })\n const 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: deps.now() + VISITOR_UPLOAD_TICKET_TTL_MS,\n })\n return finalizeVisitorUpload(deps, { scope, ticket, caller })\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","admitVisitorUpload","deps","scope","checked","request","maxBytes","kinds","full","upload","size","limits","rate","spent","allowed","retryAfterSeconds","Math","max","ceil","resetMs","mintVisitorUploadTicket","admitted","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","keepVisitorUploadCopy","source","original","isNotFound","copy","readVisitorUpload","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,QAKvB,wCAAuC;AAC9C,SACEC,iBAAiB,QAEZ,yDAAwD;AAC/D,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,sBAAsB,QAAQ,gBAAY;AACnD,SAASC,gBAAgB,QAAQ,wBAAoB;AAsJrD,OAAO,SAASC;IACd,OAAO;QACL,6EAA6E;QAC7E,4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