@aglyn/tenant-data-admin 1.0.0-beta.277 → 1.0.0-beta.283

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/account-emails.js +18 -4
  3. package/src/lib/server/account-emails.js.map +1 -1
  4. package/src/lib/server/bundle-links.d.ts +5 -0
  5. package/src/lib/server/bundle-links.js +4 -2
  6. package/src/lib/server/bundle-links.js.map +1 -1
  7. package/src/lib/server/erase.js +9 -0
  8. package/src/lib/server/erase.js.map +1 -1
  9. package/src/lib/server/media-strong-digest.js +33 -5
  10. package/src/lib/server/media-strong-digest.js.map +1 -1
  11. package/src/lib/server/organizations.js +20 -0
  12. package/src/lib/server/organizations.js.map +1 -1
  13. package/src/lib/server/owner-handoff-emails.d.ts +43 -0
  14. package/src/lib/server/owner-handoff-emails.js +134 -0
  15. package/src/lib/server/owner-handoff-emails.js.map +1 -0
  16. package/src/lib/server/personal-data-export.js +18 -4
  17. package/src/lib/server/personal-data-export.js.map +1 -1
  18. package/src/lib/server/render-monitor.d.ts +8 -4
  19. package/src/lib/server/render-monitor.js +12 -8
  20. package/src/lib/server/render-monitor.js.map +1 -1
  21. package/src/lib/server/site-care-inbound.d.ts +75 -4
  22. package/src/lib/server/site-care-inbound.js +236 -26
  23. package/src/lib/server/site-care-inbound.js.map +1 -1
  24. package/src/lib/server/site-care-reconcile.d.ts +36 -2
  25. package/src/lib/server/site-care-reconcile.js +219 -54
  26. package/src/lib/server/site-care-reconcile.js.map +1 -1
  27. package/src/lib/server/site-care-requests.d.ts +43 -1
  28. package/src/lib/server/site-care-requests.js +117 -6
  29. package/src/lib/server/site-care-requests.js.map +1 -1
  30. package/src/lib/server/upgrade-proposal.d.ts +6 -1
  31. package/src/lib/server/upgrade-proposal.js.map +1 -1
  32. package/src/lib/server/upload-cors-reconcile.d.ts +2 -2
  33. package/src/lib/server/upload-cors-reconcile.js +2 -2
  34. package/src/lib/server/upload-cors-reconcile.js.map +1 -1
@@ -47,6 +47,11 @@ export interface ProposeOrgUpgradeOptions {
47
47
  addons?: unknown;
48
48
  interval?: unknown;
49
49
  coupon?: unknown;
50
+ /**
51
+ * The Aglyn AI tier chosen with the AI add-on (AGL-4025); an `ai:<tier>`
52
+ * entry in `addons` names one too, and this wins when both do.
53
+ */
54
+ aiTier?: unknown;
50
55
  /** The staff member proposing. */
51
56
  actor: {
52
57
  uid: string;
@@ -78,7 +83,7 @@ export declare function proposeOrgUpgrade(options: ProposeOrgUpgradeOptions): Pr
78
83
  * can buy itself, a bounded note, and the bundle fitted to the plan
79
84
  * (AGL-3956). Nothing is read or written.
80
85
  */
81
- export declare function buildUpgradeProposal(options: Pick<ProposeOrgUpgradeOptions, 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'actor'> & {
86
+ export declare function buildUpgradeProposal(options: Pick<ProposeOrgUpgradeOptions, 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'aiTier' | 'actor'> & {
82
87
  now?: number;
83
88
  }): OrgUpgradeProposal;
84
89
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upgrade-proposal.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The platform team's ask that a workspace buy a plan, server side\n * (AGL-3466): staff propose and withdraw it, and a live subscription settles\n * it.\n *\n * The sequence it serves: staff build a workspace for a client, comp it to\n * the tier being sold with the `trial` reason, and hand it over. The client\n * evaluates on that tier with no upgrade asked of them. When the evaluation\n * is done, staff record a proposal here; the owner is emailed and the\n * workspace's billing managers see a card with the plan preselected. When\n * the subscription goes live, the proposal and the trial comp both clear,\n * so a comp granted to evaluate cannot revive free access if the customer\n * later cancels.\n */\n\nimport type {\n AglynOrgBilling,\n OrgPlan,\n OrgUpgradeProposal,\n} from '@aglyn/aglyn/server'\nimport { PLAN_LABELS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n normalizeUpgradeProposalNote,\n upgradeProposalDestination,\n upgradeProposalSummary,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\n// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { logOrgActivity } from './organizations'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** The override reason a sales-evaluation comp is granted under. */\nexport const TRIAL_PLAN_COMP_REASON = 'trial'\n\n/** A proposal refused before anything was written. */\nexport class UpgradeProposalError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'UpgradeProposalError'\n this.status = status\n }\n}\n\nexport interface ProposeOrgUpgradeOptions {\n orgId: string\n plan: unknown\n note?: unknown\n /**\n * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any\n * shape `parseBundleAddons` reads; fitted to the plan before storing.\n */\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /** The staff member proposing. */\n actor: { uid: string; email?: string | null }\n /** The console origin the email's link is built on. */\n origin: string\n}\n\nexport interface ProposeOrgUpgradeResult {\n proposal: OrgUpgradeProposal\n /** Whether the owner's email actually went out. */\n emailed: boolean\n}\n\n/**\n * Record a proposal on the org, audit it, and email the owner.\n *\n * The org write and its audit row commit together, the property every staff\n * write to an org document keeps (AGL-1784). The email is sent after the\n * commit and is best-effort: the card on the org home is the proposal, and\n * an email that failed must not undo it.\n *\n * Refused when the workspace already has a live subscription — the question\n * a proposal asks is already answered — and for any plan a customer cannot\n * buy themselves.\n */\nexport async function proposeOrgUpgrade(\n options: ProposeOrgUpgradeOptions,\n): Promise<ProposeOrgUpgradeResult> {\n const { orgId, actor, origin } = options\n const proposal = buildUpgradeProposal(options)\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const org = await db.runTransaction(async (tx) => {\n const data = await readUpgradeProposalTarget(tx, orgRef)\n stageUpgradeProposal(tx, db, { orgId, proposal, before: data, actorUid: actor.uid })\n return data\n })\n await recordUpgradeProposalActivity(orgId, actor, proposal)\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\n}\n\n/**\n * The proposal as it will be stored, or the refusal: a plan the workspace\n * can buy itself, a bounded note, and the bundle fitted to the plan\n * (AGL-3956). Nothing is read or written.\n */\nexport function buildUpgradeProposal(\n options: Pick<ProposeOrgUpgradeOptions, 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'actor'> & {\n now?: number\n },\n): OrgUpgradeProposal {\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new UpgradeProposalError(\n 'Choose a paid plan the workspace can buy itself',\n )\n }\n const plan: OrgPlan = options.plan\n const note = normalizeUpgradeProposalNote(options.note)\n return {\n plan,\n proposedBy: options.actor.uid,\n proposedAt: options.now ?? Date.now(),\n ...(note ? { note } : {}),\n ...normalizeUpgradeProposalBundle(plan, options),\n }\n}\n\n/**\n * Read the org a proposal is for, inside the caller's transaction, refusing\n * an unknown workspace and one whose subscription is already live — the\n * question a proposal asks is then already answered.\n */\nexport async function readUpgradeProposalTarget(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Partial<AglynOrgBilling>> {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const billing = await tx.get(\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID),\n )\n const status =\n (billing.get('subscription') as { status?: unknown } | undefined)?.status ??\n data.billingStatus\n if (isLiveSubscriptionStatus(status)) {\n throw new UpgradeProposalError(\n 'This workspace already has a live subscription, so there is nothing to propose',\n 409,\n )\n }\n return data\n}\n\n/**\n * Write the proposal and its audit row into the caller's transaction, so\n * they commit with whatever else the caller writes (AGL-1784) — the owner\n * invitation, for a hand-off that proposes in the same act (AGL-3956).\n */\nexport function stageUpgradeProposal(\n tx: FirebaseFirestore.Transaction,\n db: FirebaseFirestore.Firestore,\n options: {\n orgId: string\n proposal: OrgUpgradeProposal\n before: Partial<AglynOrgBilling>\n actorUid: string\n },\n): void {\n const { orgId, proposal, before, actorUid } = options\n tx.set(\n db.collection('orgs').doc(orgId),\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: before.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n}\n\n/** \"Proposed the Starter plan\", naming the bundle when there is one. */\nexport function proposalActivityLine(proposal: OrgUpgradeProposal): string {\n const label = planName(proposal.plan)\n const summary = upgradeProposalSummary(proposal)\n return summary === label\n ? `Proposed the ${label} plan`\n : `Proposed the ${label} plan (${summary})`\n}\n\n/** The workspace's feed line for a proposal, after it commits. */\nexport async function recordUpgradeProposalActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n proposal: OrgUpgradeProposal,\n): Promise<void> {\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n proposalActivityLine(proposal),\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n}\n\n/** Remove a standing proposal, audited. Answers whether one stood. */\nexport async function withdrawOrgUpgrade(options: {\n orgId: string\n actor: { uid: string; email?: string | null }\n}): Promise<boolean> {\n const { orgId, actor } = options\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const withdrawn = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const stored = snapshot.get('upgradeProposal') as OrgUpgradeProposal | undefined\n if (!stored) return null\n tx.set(\n orgRef,\n { upgradeProposal: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.withdraw',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: stored },\n after: { upgradeProposal: null },\n at: FieldValue.serverTimestamp(),\n })\n return stored\n })\n if (!withdrawn) return false\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Withdrew the ${planName(withdrawn.plan)} plan proposal`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n return true\n}\n\n/**\n * What a live subscription settles (AGL-3466), cleared in one transaction\n * with an audit row that says why:\n *\n * - the standing `upgradeProposal`, whose question the purchase answered;\n * - a stored plan comp granted for a sales TRIAL. A comp waits dormant under\n * a live subscription and applies again if it ends (`resolvePlanComp`), so\n * a trial comp left in place would hand a customer who cancels the tier for\n * free. Comps granted for any other reason are left alone: those are\n * decisions staff made for reasons a purchase does not answer.\n *\n * Called by the Stripe webhook once its mirror has recorded a live status.\n * Idempotent: a redelivery finds nothing to clear and writes nothing.\n */\nexport async function settleSubscriptionStart(\n orgId: string,\n context: { status: string; subscriptionId?: string | null },\n): Promise<{ proposalCleared: boolean; trialCompRemoved: boolean }> {\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const outcome = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) return null\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const proposal = data.upgradeProposal ?? null\n const entitlements = (data.entitlements ?? null) as Record<string, unknown> | null\n const comp = entitlements?.['planComp'] as\n | { plan?: string; reason?: string }\n | undefined\n const trialComp = comp?.reason === TRIAL_PLAN_COMP_REASON ? comp : null\n if (!proposal && !trialComp) return null\n // The map goes with its last key, so the staff list's override count\n // never reads an empty `entitlements` as one.\n const onlyComp =\n !!entitlements && Object.keys(entitlements).every((key) => key === 'planComp')\n tx.set(\n orgRef,\n {\n ...(proposal ? { upgradeProposal: FieldValue.delete() } : {}),\n ...(trialComp\n ? onlyComp\n ? { entitlements: FieldValue.delete() }\n : { entitlements: { planComp: FieldValue.delete() } }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: 'system',\n action: 'org.subscriptionStarted.settle',\n target: `orgs/${orgId}`,\n reason: {\n code: 'subscription_live',\n note:\n `The subscription went live (${context.status})` +\n (context.subscriptionId ? `, ${context.subscriptionId}` : '') +\n ', which settles the upgrade proposal and ends the sales-trial comp.',\n },\n before: { upgradeProposal: proposal, planComp: comp ?? null },\n after: {\n upgradeProposal: null,\n // A comp granted for any other reason stays exactly as it was.\n planComp: trialComp ? null : (comp ?? null),\n },\n at: FieldValue.serverTimestamp(),\n })\n return { proposal, trialComp }\n })\n if (!outcome) return { proposalCleared: false, trialCompRemoved: false }\n // Nobody is present at a Stripe flip, and the row says so rather than\n // naming whoever last touched billing.\n if (outcome.proposal) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.proposal.plan)} plan proposal closed — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n if (outcome.trialComp) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.trialComp.plan)} sales-trial comp ended — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n return {\n proposalCleared: !!outcome.proposal,\n trialCompRemoved: !!outcome.trialComp,\n }\n}\n\n/** Mail the owner the proposal, in the workspace's brand. Never throws. */\nasync function emailUpgradeProposal(options: {\n orgId: string\n org: Partial<AglynOrgBilling>\n proposal: OrgUpgradeProposal\n origin: string\n}): Promise<boolean> {\n const { orgId, org, proposal, origin } = options\n try {\n if (!isEmailConfigured()) return false\n const ownerUid = (org as { ownerUid?: unknown }).ownerUid\n if (typeof ownerUid !== 'string' || !ownerUid) return false\n const owner = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(ownerUid)\n .get()\n const to = owner.get('email')\n if (typeof to !== 'string' || !to) return false\n const brand = systemEmailBrand(org as Record<string, unknown>)\n const orgName = brand.orgName || 'your workspace'\n const slug = typeof org.slug === 'string' ? org.slug : ''\n const billingUrl = slug\n ? `${origin}${upgradeProposalDestination(slug, proposal)}`\n : origin\n const label = planName(proposal.plan)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n const summary = upgradeProposalSummary(proposal, { brand: productName })\n const content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\n 'proposal.summary': summary === label ? '' : summary,\n billingUrl,\n },\n brand,\n {\n subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,\n text:\n `Your ${productName} team proposed moving ${orgName} to the ${label} ` +\n (summary === label ? 'plan. ' : `plan (${summary}). `) +\n 'When you are ready, start the subscription from Billing, ' +\n `where the plan is already selected:\\n\\n${billingUrl}` +\n (proposal.note ? `\\n\\n${proposal.note}` : ''),\n },\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'org-upgrade-proposal',\n })\n if (result.sent) await meterOrgEmail(orgId)\n return result.sent\n } catch (error) {\n console.error('[upgrade-proposal] owner email failed', error)\n return false\n }\n}\n\nfunction planName(plan: unknown): string {\n return typeof plan === 'string' && plan in PLAN_LABELS\n ? PLAN_LABELS[plan as OrgPlan]\n : String(plan ?? 'proposed')\n}\n"],"names":["PLAN_LABELS","PLATFORM_BRAND_NAME","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","normalizeUpgradeProposalNote","upgradeProposalDestination","upgradeProposalSummary","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","isEmailConfigured","sendEmail","FieldValue","setAdminAudit","meterOrgEmail","firebaseAdmin","logOrgActivity","renderSystemEmailContent","systemEmailBrand","firestore","app","TRIAL_PLAN_COMP_REASON","UpgradeProposalError","Error","message","status","name","proposeOrgUpgrade","options","orgId","actor","origin","proposal","buildUpgradeProposal","db","orgRef","collection","doc","org","runTransaction","tx","data","readUpgradeProposalTarget","stageUpgradeProposal","before","actorUid","uid","recordUpgradeProposalActivity","emailed","emailUpgradeProposal","plan","note","proposedBy","proposedAt","now","Date","billing","snapshot","get","exists","billingStatus","set","upgradeProposal","updatedAt","serverTimestamp","merge","action","target","after","at","proposalActivityLine","label","planName","summary","email","type","id","staffActorId","withdrawOrgUpgrade","withdrawn","stored","delete","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","productName","content","subject","text","result","html","fromName","sent","error","console","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAOD,SAASA,WAAW,QAAQ,2CAA0C;AACtE,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,qBAAqB,EACrBC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,sBAAsB,QACjB,0CAAyC;AAChD,wE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IAC7B,OAAO,OAAOA,SAAS,YAAYA,QAAQlD,cACvCA,WAAW,CAACkD,KAAgB,GAC5BkE,OAAOlE,eAAAA,OAAQ;AACrB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upgrade-proposal.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The platform team's ask that a workspace buy a plan, server side\n * (AGL-3466): staff propose and withdraw it, and a live subscription settles\n * it.\n *\n * The sequence it serves: staff build a workspace for a client, comp it to\n * the tier being sold with the `trial` reason, and hand it over. The client\n * evaluates on that tier with no upgrade asked of them. When the evaluation\n * is done, staff record a proposal here; the owner is emailed and the\n * workspace's billing managers see a card with the plan preselected. When\n * the subscription goes live, the proposal and the trial comp both clear,\n * so a comp granted to evaluate cannot revive free access if the customer\n * later cancels.\n */\n\nimport type {\n AglynOrgBilling,\n OrgPlan,\n OrgUpgradeProposal,\n} from '@aglyn/aglyn/server'\nimport { PLAN_LABELS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n normalizeUpgradeProposalNote,\n upgradeProposalDestination,\n upgradeProposalSummary,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\n// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { logOrgActivity } from './organizations'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** The override reason a sales-evaluation comp is granted under. */\nexport const TRIAL_PLAN_COMP_REASON = 'trial'\n\n/** A proposal refused before anything was written. */\nexport class UpgradeProposalError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'UpgradeProposalError'\n this.status = status\n }\n}\n\nexport interface ProposeOrgUpgradeOptions {\n orgId: string\n plan: unknown\n note?: unknown\n /**\n * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any\n * shape `parseBundleAddons` reads; fitted to the plan before storing.\n */\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /**\n * The Aglyn AI tier chosen with the AI add-on (AGL-4025); an `ai:<tier>`\n * entry in `addons` names one too, and this wins when both do.\n */\n aiTier?: unknown\n /** The staff member proposing. */\n actor: { uid: string; email?: string | null }\n /** The console origin the email's link is built on. */\n origin: string\n}\n\nexport interface ProposeOrgUpgradeResult {\n proposal: OrgUpgradeProposal\n /** Whether the owner's email actually went out. */\n emailed: boolean\n}\n\n/**\n * Record a proposal on the org, audit it, and email the owner.\n *\n * The org write and its audit row commit together, the property every staff\n * write to an org document keeps (AGL-1784). The email is sent after the\n * commit and is best-effort: the card on the org home is the proposal, and\n * an email that failed must not undo it.\n *\n * Refused when the workspace already has a live subscription — the question\n * a proposal asks is already answered — and for any plan a customer cannot\n * buy themselves.\n */\nexport async function proposeOrgUpgrade(\n options: ProposeOrgUpgradeOptions,\n): Promise<ProposeOrgUpgradeResult> {\n const { orgId, actor, origin } = options\n const proposal = buildUpgradeProposal(options)\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const org = await db.runTransaction(async (tx) => {\n const data = await readUpgradeProposalTarget(tx, orgRef)\n stageUpgradeProposal(tx, db, { orgId, proposal, before: data, actorUid: actor.uid })\n return data\n })\n await recordUpgradeProposalActivity(orgId, actor, proposal)\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\n}\n\n/**\n * The proposal as it will be stored, or the refusal: a plan the workspace\n * can buy itself, a bounded note, and the bundle fitted to the plan\n * (AGL-3956). Nothing is read or written.\n */\nexport function buildUpgradeProposal(\n options: Pick<\n ProposeOrgUpgradeOptions,\n 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'aiTier' | 'actor'\n > & {\n now?: number\n },\n): OrgUpgradeProposal {\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new UpgradeProposalError(\n 'Choose a paid plan the workspace can buy itself',\n )\n }\n const plan: OrgPlan = options.plan\n const note = normalizeUpgradeProposalNote(options.note)\n return {\n plan,\n proposedBy: options.actor.uid,\n proposedAt: options.now ?? Date.now(),\n ...(note ? { note } : {}),\n ...normalizeUpgradeProposalBundle(plan, options),\n }\n}\n\n/**\n * Read the org a proposal is for, inside the caller's transaction, refusing\n * an unknown workspace and one whose subscription is already live — the\n * question a proposal asks is then already answered.\n */\nexport async function readUpgradeProposalTarget(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Partial<AglynOrgBilling>> {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const billing = await tx.get(\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID),\n )\n const status =\n (billing.get('subscription') as { status?: unknown } | undefined)?.status ??\n data.billingStatus\n if (isLiveSubscriptionStatus(status)) {\n throw new UpgradeProposalError(\n 'This workspace already has a live subscription, so there is nothing to propose',\n 409,\n )\n }\n return data\n}\n\n/**\n * Write the proposal and its audit row into the caller's transaction, so\n * they commit with whatever else the caller writes (AGL-1784) — the owner\n * invitation, for a hand-off that proposes in the same act (AGL-3956).\n */\nexport function stageUpgradeProposal(\n tx: FirebaseFirestore.Transaction,\n db: FirebaseFirestore.Firestore,\n options: {\n orgId: string\n proposal: OrgUpgradeProposal\n before: Partial<AglynOrgBilling>\n actorUid: string\n },\n): void {\n const { orgId, proposal, before, actorUid } = options\n tx.set(\n db.collection('orgs').doc(orgId),\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: before.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n}\n\n/** \"Proposed the Starter plan\", naming the bundle when there is one. */\nexport function proposalActivityLine(proposal: OrgUpgradeProposal): string {\n const label = planName(proposal.plan)\n const summary = upgradeProposalSummary(proposal)\n return summary === label\n ? `Proposed the ${label} plan`\n : `Proposed the ${label} plan (${summary})`\n}\n\n/** The workspace's feed line for a proposal, after it commits. */\nexport async function recordUpgradeProposalActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n proposal: OrgUpgradeProposal,\n): Promise<void> {\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n proposalActivityLine(proposal),\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n}\n\n/** Remove a standing proposal, audited. Answers whether one stood. */\nexport async function withdrawOrgUpgrade(options: {\n orgId: string\n actor: { uid: string; email?: string | null }\n}): Promise<boolean> {\n const { orgId, actor } = options\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const withdrawn = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const stored = snapshot.get('upgradeProposal') as OrgUpgradeProposal | undefined\n if (!stored) return null\n tx.set(\n orgRef,\n { upgradeProposal: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.withdraw',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: stored },\n after: { upgradeProposal: null },\n at: FieldValue.serverTimestamp(),\n })\n return stored\n })\n if (!withdrawn) return false\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Withdrew the ${planName(withdrawn.plan)} plan proposal`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n return true\n}\n\n/**\n * What a live subscription settles (AGL-3466), cleared in one transaction\n * with an audit row that says why:\n *\n * - the standing `upgradeProposal`, whose question the purchase answered;\n * - a stored plan comp granted for a sales TRIAL. A comp waits dormant under\n * a live subscription and applies again if it ends (`resolvePlanComp`), so\n * a trial comp left in place would hand a customer who cancels the tier for\n * free. Comps granted for any other reason are left alone: those are\n * decisions staff made for reasons a purchase does not answer.\n *\n * Called by the Stripe webhook once its mirror has recorded a live status.\n * Idempotent: a redelivery finds nothing to clear and writes nothing.\n */\nexport async function settleSubscriptionStart(\n orgId: string,\n context: { status: string; subscriptionId?: string | null },\n): Promise<{ proposalCleared: boolean; trialCompRemoved: boolean }> {\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const outcome = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) return null\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const proposal = data.upgradeProposal ?? null\n const entitlements = (data.entitlements ?? null) as Record<string, unknown> | null\n const comp = entitlements?.['planComp'] as\n | { plan?: string; reason?: string }\n | undefined\n const trialComp = comp?.reason === TRIAL_PLAN_COMP_REASON ? comp : null\n if (!proposal && !trialComp) return null\n // The map goes with its last key, so the staff list's override count\n // never reads an empty `entitlements` as one.\n const onlyComp =\n !!entitlements && Object.keys(entitlements).every((key) => key === 'planComp')\n tx.set(\n orgRef,\n {\n ...(proposal ? { upgradeProposal: FieldValue.delete() } : {}),\n ...(trialComp\n ? onlyComp\n ? { entitlements: FieldValue.delete() }\n : { entitlements: { planComp: FieldValue.delete() } }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: 'system',\n action: 'org.subscriptionStarted.settle',\n target: `orgs/${orgId}`,\n reason: {\n code: 'subscription_live',\n note:\n `The subscription went live (${context.status})` +\n (context.subscriptionId ? `, ${context.subscriptionId}` : '') +\n ', which settles the upgrade proposal and ends the sales-trial comp.',\n },\n before: { upgradeProposal: proposal, planComp: comp ?? null },\n after: {\n upgradeProposal: null,\n // A comp granted for any other reason stays exactly as it was.\n planComp: trialComp ? null : (comp ?? null),\n },\n at: FieldValue.serverTimestamp(),\n })\n return { proposal, trialComp }\n })\n if (!outcome) return { proposalCleared: false, trialCompRemoved: false }\n // Nobody is present at a Stripe flip, and the row says so rather than\n // naming whoever last touched billing.\n if (outcome.proposal) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.proposal.plan)} plan proposal closed — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n if (outcome.trialComp) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.trialComp.plan)} sales-trial comp ended — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n return {\n proposalCleared: !!outcome.proposal,\n trialCompRemoved: !!outcome.trialComp,\n }\n}\n\n/** Mail the owner the proposal, in the workspace's brand. Never throws. */\nasync function emailUpgradeProposal(options: {\n orgId: string\n org: Partial<AglynOrgBilling>\n proposal: OrgUpgradeProposal\n origin: string\n}): Promise<boolean> {\n const { orgId, org, proposal, origin } = options\n try {\n if (!isEmailConfigured()) return false\n const ownerUid = (org as { ownerUid?: unknown }).ownerUid\n if (typeof ownerUid !== 'string' || !ownerUid) return false\n const owner = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(ownerUid)\n .get()\n const to = owner.get('email')\n if (typeof to !== 'string' || !to) return false\n const brand = systemEmailBrand(org as Record<string, unknown>)\n const orgName = brand.orgName || 'your workspace'\n const slug = typeof org.slug === 'string' ? org.slug : ''\n const billingUrl = slug\n ? `${origin}${upgradeProposalDestination(slug, proposal)}`\n : origin\n const label = planName(proposal.plan)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n const summary = upgradeProposalSummary(proposal, { brand: productName })\n const content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\n 'proposal.summary': summary === label ? '' : summary,\n billingUrl,\n },\n brand,\n {\n subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,\n text:\n `Your ${productName} team proposed moving ${orgName} to the ${label} ` +\n (summary === label ? 'plan. ' : `plan (${summary}). `) +\n 'When you are ready, start the subscription from Billing, ' +\n `where the plan is already selected:\\n\\n${billingUrl}` +\n (proposal.note ? `\\n\\n${proposal.note}` : ''),\n },\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'org-upgrade-proposal',\n })\n if (result.sent) await meterOrgEmail(orgId)\n return result.sent\n } catch (error) {\n console.error('[upgrade-proposal] owner email failed', error)\n return false\n }\n}\n\nfunction planName(plan: unknown): string {\n return typeof plan === 'string' && plan in PLAN_LABELS\n ? PLAN_LABELS[plan as OrgPlan]\n : String(plan ?? 'proposed')\n}\n"],"names":["PLAN_LABELS","PLATFORM_BRAND_NAME","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","normalizeUpgradeProposalNote","upgradeProposalDestination","upgradeProposalSummary","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","isEmailConfigured","sendEmail","FieldValue","setAdminAudit","meterOrgEmail","firebaseAdmin","logOrgActivity","renderSystemEmailContent","systemEmailBrand","firestore","app","TRIAL_PLAN_COMP_REASON","UpgradeProposalError","Error","message","status","name","proposeOrgUpgrade","options","orgId","actor","origin","proposal","buildUpgradeProposal","db","orgRef","collection","doc","org","runTransaction","tx","data","readUpgradeProposalTarget","stageUpgradeProposal","before","actorUid","uid","recordUpgradeProposalActivity","emailed","emailUpgradeProposal","plan","note","proposedBy","proposedAt","now","Date","billing","snapshot","get","exists","billingStatus","set","upgradeProposal","updatedAt","serverTimestamp","merge","action","target","after","at","proposalActivityLine","label","planName","summary","email","type","id","staffActorId","withdrawOrgUpgrade","withdrawn","stored","delete","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","productName","content","subject","text","result","html","fromName","sent","error","console","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAOD,SAASA,WAAW,QAAQ,2CAA0C;AACtE,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,qBAAqB,EACrBC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,sBAAsB,QACjB,0CAAyC;AAChD,wEAAwE;AACxE,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,yBAAyB,QACpB,yCAAwC;AAC/C,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,yBAAqB;AACnD,SAASC,aAAa,QAAQ,sBAAkB;AAChD,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,cAAc,QAAQ,qBAAiB;AAChD,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,2BAAuB;AAE9B,MAAMC,YAAY,IAAMJ,cAAcK,GAAG,GAAGD,SAAS;AAErD,kEAAkE,GAClE,OAAO,MAAME,yBAAyB,QAAO;AAE7C,oDAAoD,GACpD,OAAO,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gC,SAAS;YAC7EM,MACE,CAAC,KAAK,EAAEH,YAAY,sBAAsB,EAAEH,QAAQ,QAAQ,EAAEhC,MAAM,CAAC,CAAC,GACrEE,CAAAA,YAAYF,QAAQ,WAAW,CAAC,MAAM,EAAEE,QAAQ,GAAG,CAAC,AAAD,IACpD,8DACA,CAAC,uCAAuC,EAAEgC,YAAY,GACrDzE,CAAAA,SAASmB,IAAI,GAAG,CAAC,IAAI,EAAEnB,SAASmB,IAAI,EAAE,GAAG,EAAC;QAC/C;QAEF,MAAM2D,SAAS,MAAMnG,UAAU;YAC7B0F;YACAO,SAASD,QAAQC,OAAO;YACxBC,MAAMF,QAAQE,IAAI;WACdF,QAAQI,IAAI,GAAG;YAAEA,MAAMJ,QAAQI,IAAI;QAAC,IAAI,CAAC,GACzCT,MAAMU,QAAQ,GAAG;YAAEA,UAAUV,MAAMU,QAAQ;QAAC,IAAI,CAAC;YACrD7B,SAAS;;QAEX,IAAI2B,OAAOG,IAAI,EAAE,MAAMnG,cAAce;QACrC,OAAOiF,OAAOG,IAAI;IACpB,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,yCAAyCA;QACvD,OAAO;IACT;AACF;AAEA,SAAS1C,SAAStB,IAAa;IAC7B,OAAO,OAAOA,SAAS,YAAYA,QAAQlD,cACvCA,WAAW,CAACkD,KAAgB,GAC5BkE,OAAOlE,eAAAA,OAAQ;AACrB"}
@@ -31,8 +31,8 @@
31
31
  * console project's seventeen attached names, exactly one —
32
32
  * `https://app.aglyn.com` — was permitted, while five names that serve the
33
33
  * console at 200 (`zgover.aglyn.com`, `test-org.aglyn.com`,
34
- * `aglyn-org.aglyn.com`, `sale-test.aglyn.com`, `zachary1748.aglyn.com`) were
35
- * refused. AGL-1452 recorded workspace subdomains as latent because none were
34
+ * `aglyn-org.aglyn.com`, `sale-test.aglyn.com` and one personal workspace's
35
+ * host) were refused. AGL-1452 recorded workspace subdomains as latent because none were
36
36
  * attached at the time; they are attached now.
37
37
  *
38
38
  * ## Serving names only
@@ -30,8 +30,8 @@
30
30
  * console project's seventeen attached names, exactly one —
31
31
  * `https://app.aglyn.com` — was permitted, while five names that serve the
32
32
  * console at 200 (`zgover.aglyn.com`, `test-org.aglyn.com`,
33
- * `aglyn-org.aglyn.com`, `sale-test.aglyn.com`, `zachary1748.aglyn.com`) were
34
- * refused. AGL-1452 recorded workspace subdomains as latent because none were
33
+ * `aglyn-org.aglyn.com`, `sale-test.aglyn.com` and one personal workspace's
34
+ * host) were refused. AGL-1452 recorded workspace subdomains as latent because none were
35
35
  * attached at the time; they are attached now.
36
36
  *
37
37
  * ## Serving names only
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upload-cors-reconcile.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Keep the media bucket's upload CORS in step with the names the console is\n * SERVED on (AGL-1452).\n *\n * ## Why this is automation rather than a checklist line\n *\n * GCS matches the CORS `origin` list as an exact string — no subtree form —\n * so every serving console name needs its own entry, and a missing one fails\n * only on files large enough to take the signed direct-to-GCS path, behind a\n * generic \"try again\" snackbar. Nothing about the symptom points at bucket\n * configuration, and nothing at attach time pointed at it either.\n *\n * That was already costing us, not merely threatening to. Driving real\n * preflights against `gs://aglyn-main.appspot.com` on 2026-08-20: of the\n * console project's seventeen attached names, exactly one —\n * `https://app.aglyn.com` — was permitted, while five names that serve the\n * console at 200 (`zgover.aglyn.com`, `test-org.aglyn.com`,\n * `aglyn-org.aglyn.com`, `sale-test.aglyn.com`, `zachary1748.aglyn.com`) were\n * refused. AGL-1452 recorded workspace subdomains as latent because none were\n * attached at the time; they are attached now.\n *\n * ## Serving names only\n *\n * A name attached as a REDIRECT never becomes a browser origin — the browser\n * is already at the redirect target before it uploads — so it needs no entry.\n * Measured: `console.aglyn.com` 308s and `app.aglyn.io` 307s to\n * `app.aglyn.com`, and neither is in the CORS list, and neither is broken.\n * `attachProjectDomain` therefore calls this only for a name it attached\n * WITHOUT a redirect.\n *\n * ## When it cannot\n *\n * The runtime service account may not hold `storage.buckets.update`. That is\n * a real and likely outcome, and the one thing this must not do about it is\n * be quiet: the verdict carries `permitted: false` and the exact ordered\n * read-modify-write command, so the failure is legible at attach time instead\n * of arriving days later as a broken upload. It never throws and never blocks\n * an attach — a domain must not fail to attach over a storage API.\n */\n\nimport {\n mergeUploadOrigins,\n permitsUploadOrigin,\n revokeUploadOrigins,\n uploadCorsRemedy,\n uploadOriginFor,\n type CorsRule,\n} from '@aglyn/aglyn/server'\n\n/**\n * The one origin a release must never take away.\n *\n * Configured rather than provisioned, so it will never appear in a detach —\n * but the guard is here rather than at the call site because the cost of\n * getting it wrong is every customer's large uploads at once, and a guard that\n * lives at the call site is a guard the next call site does not have.\n */\nfunction platformOrigin(): string | null {\n return uploadOriginFor(\n process.env['NEXT_PUBLIC_CONSOLE_URL'] ?? 'app.aglyn.com',\n )\n}\n\nexport interface UploadCorsVerdict {\n /** The origin a browser at this name will send. */\n origin: string\n /** Can a signed `PUT` from that origin complete, now that we are done? */\n permitted: boolean\n /** Origins this run added to the bucket. Empty when it was already covered. */\n added: string[]\n /** What a human must run, when we could not. Null when there is nothing owed. */\n remedy: string | null\n /** Which step failed, for a caller that wants to branch. */\n detail: string | null\n}\n\n/**\n * The bucket, behind a seam.\n *\n * Injectable so the merge and the failure paths are exercised without a\n * network — the reason AGL-1408 shipped broken is that the only leg nobody\n * could test cheaply was the only leg that mattered.\n */\nexport interface BucketCorsIO {\n bucket: string\n /** Null when the configuration could not be read at all. */\n read(): Promise<{ rules: CorsRule[]; metageneration: string } | null>\n /**\n * Write the merged configuration back, conditional on the metageneration\n * that was read — two attaches racing would otherwise clobber each other.\n */\n write(rules: CorsRule[], metageneration: string): Promise<void>\n}\n\n/** The live bucket, or null when this deployment has no media bucket configured. */\nexport function liveBucketCorsIO(): BucketCorsIO | null {\n const bucket = String(\n process.env['NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET'] ?? '',\n ).trim()\n if (!bucket) return null\n // Imported lazily, not at module scope. `firebase-admin.ts` builds a\n // Firebase app on load, and this module is imported by `workspace-domains`,\n // which had no Firebase dependency at all and must keep none — a domain\n // attach is an HTTP call to Vercel and nothing more.\n const handle = async () => {\n const { firebaseAdmin } = await import('./firebase-admin')\n return firebaseAdmin.app().storage().bucket(bucket)\n }\n return {\n bucket,\n read: async () => {\n const [metadata] = await (await handle()).getMetadata()\n return {\n rules: (metadata?.cors ?? []) as CorsRule[],\n metageneration: String(metadata?.metageneration ?? ''),\n }\n },\n write: async (rules, metageneration) => {\n await (await handle()).setMetadata(\n { cors: rules },\n metageneration ? { ifMetagenerationMatch: metageneration } : {},\n )\n },\n }\n}\n\nexport async function reconcileUploadCors(\n host: string,\n io: BucketCorsIO | null = liveBucketCorsIO(),\n): Promise<UploadCorsVerdict | null> {\n const origin = uploadOriginFor(host)\n if (!origin || !io) return null\n\n const refused = (detail: string): UploadCorsVerdict => ({\n origin,\n permitted: false,\n added: [],\n remedy: uploadCorsRemedy(io.bucket, [origin]),\n detail,\n })\n\n let current: { rules: CorsRule[]; metageneration: string } | null\n try {\n current = await io.read()\n } catch (error) {\n console.error('[upload-cors] could not read bucket CORS', io.bucket, error)\n return refused('read-failed')\n }\n if (!current) return refused('read-failed')\n\n if (permitsUploadOrigin(current.rules, origin)) {\n return { origin, permitted: true, added: [], remedy: null, detail: null }\n }\n\n let merged: { rules: CorsRule[]; added: string[] }\n try {\n merged = mergeUploadOrigins(current.rules, [origin])\n } catch (error) {\n // `mergeUploadOrigins` throws only on a wildcard, which `uploadOriginFor`\n // has already ruled out — so reaching here means the invariant moved.\n console.error('[upload-cors] refused to build a policy', origin, error)\n return refused('merge-refused')\n }\n\n try {\n await io.write(merged.rules, current.metageneration)\n } catch (error) {\n console.error(\n '[upload-cors] could not write bucket CORS — large uploads from',\n origin,\n 'will fail until a human runs the command in the verdict',\n error,\n )\n return refused('write-failed')\n }\n\n return {\n origin,\n permitted: true,\n added: merged.added,\n remedy: null,\n detail: null,\n }\n}\n\n/** What a detach did, or could not do, about the origin it left behind. */\nexport interface UploadCorsRelease {\n /** The origin the detached name used to send. */\n origin: string\n /** Is that origin gone from the bucket now? */\n revoked: boolean\n /** Why not, for a caller that wants to branch. Null when it is gone. */\n detail: string | null\n}\n\n/**\n * Take an origin back off the bucket when its name stops serving the console\n * (AGL-1452).\n *\n * The mirror of `reconcileUploadCors`, and the half that was missing: attaching\n * added an origin and detaching left it. That is a standing permission for a\n * host we no longer serve — and for a white-label customer domain, a host that\n * somebody else still controls, on a bucket where the signed URL IS the\n * authorization.\n *\n * Same three properties as the attach side. It never throws, never blocks a\n * detach, and reports what it could not do rather than going quiet: a domain\n * must not fail to detach because a storage API was slow, and the operator who\n * detached a customer must be able to see that the permission outlived them.\n *\n * Refuses the platform origin structurally, not by convention.\n */\nexport async function releaseUploadCors(\n host: string,\n io: BucketCorsIO | null = liveBucketCorsIO(),\n): Promise<UploadCorsRelease | null> {\n const origin = uploadOriginFor(host)\n if (!origin || !io) return null\n if (origin === platformOrigin()) {\n return { origin, revoked: false, detail: 'platform-origin' }\n }\n\n let current: { rules: CorsRule[]; metageneration: string } | null\n try {\n current = await io.read()\n } catch (error) {\n console.error('[upload-cors] could not read bucket CORS', io.bucket, error)\n return { origin, revoked: false, detail: 'read-failed' }\n }\n if (!current) return { origin, revoked: false, detail: 'read-failed' }\n\n // Already gone is the success case, not a no-op to report as a failure: a\n // detach that runs twice must not read as a permission that would not go.\n if (!permitsUploadOrigin(current.rules, origin)) {\n return { origin, revoked: true, detail: null }\n }\n\n const { rules, removed } = revokeUploadOrigins(current.rules, [origin], {\n keep: [platformOrigin() ?? ''].filter(Boolean),\n })\n if (removed.length === 0) {\n return { origin, revoked: false, detail: 'refused' }\n }\n\n try {\n await io.write(rules, current.metageneration)\n } catch (error) {\n console.error(\n '[upload-cors] could not revoke bucket CORS —',\n origin,\n 'keeps a standing permission to complete signed uploads; run',\n 'npm run check:upload-cors -- --prune',\n error,\n )\n return { origin, revoked: false, detail: 'write-failed' }\n }\n return { origin, revoked: true, detail: null }\n}\n"],"names":["mergeUploadOrigins","permitsUploadOrigin","revokeUploadOrigins","uploadCorsRemedy","uploadOriginFor","platformOrigin","process","env","liveBucketCorsIO","bucket","String","trim","handle","firebaseAdmin","app","storage","read","metadata","getMetadata","rules","cors","metageneration","write","setMetadata","ifMetagenerationMatch","reconcileUploadCors","host","io","origin","refused","detail","permitted","added","remedy","current","error","console","merged","releaseUploadCors","revoked","removed","keep","filter","Boolean","length"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCC,GAED,SACEA,kBAAkB,EAClBC,mBAAmB,EACnBC,mBAAmB,EACnBC,gBAAgB,EAChBC,eAAe,QAEV,sBAAqB;AAE5B;;;;;;;CAOC,GACD,SAASC;QAELC;IADF,OAAOF,iBACLE,uCAAAA,QAAQC,GAAG,CAAC,0BAA0B,YAAtCD,uCAA0C;AAE9C;AAiCA,kFAAkF,GAClF,OAAO,SAASE;QAEZF;IADF,MAAMG,SAASC,QACbJ,mDAAAA,QAAQC,GAAG,CAAC,sCAAsC,YAAlDD,mDAAsD,IACtDK,IAAI;IACN,IAAI,CAACF,QAAQ,OAAO;IACpB,qEAAqE;IACrE,4EAA4E;IAC5E,wEAAwE;IACxE,qDAAqD;IACrD,MAAMG,SAAS;QACb,MAAM,EAAEC,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC;QACvC,OAAOA,cAAcC,GAAG,GAAGC,OAAO,GAAGN,M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;YAAQW,SAAS;YAAOT,QAAQ;QAAU;IACrD;IAEA,IAAI;QACF,MAAMH,GAAGL,KAAK,CAACH,OAAOe,QAAQb,cAAc;IAC9C,EAAE,OAAOc,OAAO;QACdC,QAAQD,KAAK,CACX,gDACAP,QACA,+DACA,wCACAO;QAEF,OAAO;YAAEP;YAAQW,SAAS;YAAOT,QAAQ;QAAe;IAC1D;IACA,OAAO;QAAEF;QAAQW,SAAS;QAAMT,QAAQ;IAAK;AAC/C"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upload-cors-reconcile.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Keep the media bucket's upload CORS in step with the names the console is\n * SERVED on (AGL-1452).\n *\n * ## Why this is automation rather than a checklist line\n *\n * GCS matches the CORS `origin` list as an exact string — no subtree form —\n * so every serving console name needs its own entry, and a missing one fails\n * only on files large enough to take the signed direct-to-GCS path, behind a\n * generic \"try again\" snackbar. Nothing about the symptom points at bucket\n * configuration, and nothing at attach time pointed at it either.\n *\n * That was already costing us, not merely threatening to. Driving real\n * preflights against `gs://aglyn-main.appspot.com` on 2026-08-20: of the\n * console project's seventeen attached names, exactly one —\n * `https://app.aglyn.com` — was permitted, while five names that serve the\n * console at 200 (`zgover.aglyn.com`, `test-org.aglyn.com`,\n * `aglyn-org.aglyn.com`, `sale-test.aglyn.com` and one personal workspace's\n * host) were refused. AGL-1452 recorded workspace subdomains as latent because none were\n * attached at the time; they are attached now.\n *\n * ## Serving names only\n *\n * A name attached as a REDIRECT never becomes a browser origin — the browser\n * is already at the redirect target before it uploads — so it needs no entry.\n * Measured: `console.aglyn.com` 308s and `app.aglyn.io` 307s to\n * `app.aglyn.com`, and neither is in the CORS list, and neither is broken.\n * `attachProjectDomain` therefore calls this only for a name it attached\n * WITHOUT a redirect.\n *\n * ## When it cannot\n *\n * The runtime service account may not hold `storage.buckets.update`. That is\n * a real and likely outcome, and the one thing this must not do about it is\n * be quiet: the verdict carries `permitted: false` and the exact ordered\n * read-modify-write command, so the failure is legible at attach time instead\n * of arriving days later as a broken upload. It never throws and never blocks\n * an attach — a domain must not fail to attach over a storage API.\n */\n\nimport {\n mergeUploadOrigins,\n permitsUploadOrigin,\n revokeUploadOrigins,\n uploadCorsRemedy,\n uploadOriginFor,\n type CorsRule,\n} from '@aglyn/aglyn/server'\n\n/**\n * The one origin a release must never take away.\n *\n * Configured rather than provisioned, so it will never appear in a detach —\n * but the guard is here rather than at the call site because the cost of\n * getting it wrong is every customer's large uploads at once, and a guard that\n * lives at the call site is a guard the next call site does not have.\n */\nfunction platformOrigin(): string | null {\n return uploadOriginFor(\n process.env['NEXT_PUBLIC_CONSOLE_URL'] ?? 'app.aglyn.com',\n )\n}\n\nexport interface UploadCorsVerdict {\n /** The origin a browser at this name will send. */\n origin: string\n /** Can a signed `PUT` from that origin complete, now that we are done? */\n permitted: boolean\n /** Origins this run added to the bucket. Empty when it was already covered. */\n added: string[]\n /** What a human must run, when we could not. Null when there is nothing owed. */\n remedy: string | null\n /** Which step failed, for a caller that wants to branch. */\n detail: string | null\n}\n\n/**\n * The bucket, behind a seam.\n *\n * Injectable so the merge and the failure paths are exercised without a\n * network — the reason AGL-1408 shipped broken is that the only leg nobody\n * could test cheaply was the only leg that mattered.\n */\nexport interface BucketCorsIO {\n bucket: string\n /** Null when the configuration could not be read at all. */\n read(): Promise<{ rules: CorsRule[]; metageneration: string } | null>\n /**\n * Write the merged configuration back, conditional on the metageneration\n * that was read — two attaches racing would otherwise clobber each other.\n */\n write(rules: CorsRule[], metageneration: string): Promise<void>\n}\n\n/** The live bucket, or null when this deployment has no media bucket configured. */\nexport function liveBucketCorsIO(): BucketCorsIO | null {\n const bucket = String(\n process.env['NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET'] ?? '',\n ).trim()\n if (!bucket) return null\n // Imported lazily, not at module scope. `firebase-admin.ts` builds a\n // Firebase app on load, and this module is imported by `workspace-domains`,\n // which had no Firebase dependency at all and must keep none — a domain\n // attach is an HTTP call to Vercel and nothing more.\n const handle = async () => {\n const { firebaseAdmin } = await import('./firebase-admin')\n return firebaseAdmin.app().storage().bucket(bucket)\n }\n return {\n bucket,\n read: async () => {\n const [metadata] = await (await handle()).getMetadata()\n return {\n rules: (metadata?.cors ?? []) as CorsRule[],\n metageneration: String(metadata?.metageneration ?? ''),\n }\n },\n write: async (rules, metageneration) => {\n await (await handle()).setMetadata(\n { cors: rules },\n metageneration ? { ifMetagenerationMatch: metageneration } : {},\n )\n },\n }\n}\n\nexport async function reconcileUploadCors(\n host: string,\n io: BucketCorsIO | null = liveBucketCorsIO(),\n): Promise<UploadCorsVerdict | null> {\n const origin = uploadOriginFor(host)\n if (!origin || !io) return null\n\n const refused = (detail: string): UploadCorsVerdict => ({\n origin,\n permitted: false,\n added: [],\n remedy: uploadCorsRemedy(io.bucket, [origin]),\n detail,\n })\n\n let current: { rules: CorsRule[]; metageneration: string } | null\n try {\n current = await io.read()\n } catch (error) {\n console.error('[upload-cors] could not read bucket CORS', io.bucket, error)\n return refused('read-failed')\n }\n if (!current) return refused('read-failed')\n\n if (permitsUploadOrigin(current.rules, origin)) {\n return { origin, permitted: true, added: [], remedy: null, detail: null }\n }\n\n let merged: { rules: CorsRule[]; added: string[] }\n try {\n merged = mergeUploadOrigins(current.rules, [origin])\n } catch (error) {\n // `mergeUploadOrigins` throws only on a wildcard, which `uploadOriginFor`\n // has already ruled out — so reaching here means the invariant moved.\n console.error('[upload-cors] refused to build a policy', origin, error)\n return refused('merge-refused')\n }\n\n try {\n await io.write(merged.rules, current.metageneration)\n } catch (error) {\n console.error(\n '[upload-cors] could not write bucket CORS — large uploads from',\n origin,\n 'will fail until a human runs the command in the verdict',\n error,\n )\n return refused('write-failed')\n }\n\n return {\n origin,\n permitted: true,\n added: merged.added,\n remedy: null,\n detail: null,\n }\n}\n\n/** What a detach did, or could not do, about the origin it left behind. */\nexport interface UploadCorsRelease {\n /** The origin the detached name used to send. */\n origin: string\n /** Is that origin gone from the bucket now? */\n revoked: boolean\n /** Why not, for a caller that wants to branch. Null when it is gone. */\n detail: string | null\n}\n\n/**\n * Take an origin back off the bucket when its name stops serving the console\n * (AGL-1452).\n *\n * The mirror of `reconcileUploadCors`, and the half that was missing: attaching\n * added an origin and detaching left it. That is a standing permission for a\n * host we no longer serve — and for a white-label customer domain, a host that\n * somebody else still controls, on a bucket where the signed URL IS the\n * authorization.\n *\n * Same three properties as the attach side. It never throws, never blocks a\n * detach, and reports what it could not do rather than going quiet: a domain\n * must not fail to detach because a storage API was slow, and the operator who\n * detached a customer must be able to see that the permission outlived them.\n *\n * Refuses the platform origin structurally, not by convention.\n */\nexport async function releaseUploadCors(\n host: string,\n io: BucketCorsIO | null = liveBucketCorsIO(),\n): Promise<UploadCorsRelease | null> {\n const origin = uploadOriginFor(host)\n if (!origin || !io) return null\n if (origin === platformOrigin()) {\n return { origin, revoked: false, detail: 'platform-origin' }\n }\n\n let current: { rules: CorsRule[]; metageneration: string } | null\n try {\n current = await io.read()\n } catch (error) {\n console.error('[upload-cors] could not read bucket CORS', io.bucket, error)\n return { origin, revoked: false, detail: 'read-failed' }\n }\n if (!current) return { origin, revoked: false, detail: 'read-failed' }\n\n // Already gone is the success case, not a no-op to report as a failure: a\n // detach that runs twice must not read as a permission that would not go.\n if (!permitsUploadOrigin(current.rules, origin)) {\n return { origin, revoked: true, detail: null }\n }\n\n const { rules, removed } = revokeUploadOrigins(current.rules, [origin], {\n keep: [platformOrigin() ?? ''].filter(Boolean),\n })\n if (removed.length === 0) {\n return { origin, revoked: false, detail: 'refused' }\n }\n\n try {\n await io.write(rules, current.metageneration)\n } catch (error) {\n console.error(\n '[upload-cors] could not revoke bucket CORS —',\n origin,\n 'keeps a standing permission to complete signed uploads; run',\n 'npm run check:upload-cors -- --prune',\n error,\n )\n return { origin, revoked: false, detail: 'write-failed' }\n }\n return { origin, revoked: true, detail: null }\n}\n"],"names":["mergeUploadOrigins","permitsUploadOrigin","revokeUploadOrigins","uploadCorsRemedy","uploadOriginFor","platformOrigin","process","env","liveBucketCorsIO","bucket","String","trim","handle","firebaseAdmin","app","storage","read","metadata","getMetadata","rules","cors","metageneration","write","setMetadata","ifMetagenerationMatch","reconcileUploadCors","host","io","origin","refused","detail","permitted","added","remedy","current","error","console","merged","releaseUploadCors","revoked","removed","keep","filter","Boolean","length"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCC,GAED,SACEA,kBAAkB,EAClBC,mBAAmB,EACnBC,mBAAmB,EACnBC,gBAAgB,EAChBC,eAAe,QAEV,sBAAqB;AAE5B;;;;;;;CAOC,GACD,SAASC;QAELC;IADF,OAAOF,iBACLE,uCAAAA,QAAQC,GAAG,CAAC,0BAA0B,YAAtCD,uCAA0C;AAE9C;AAiCA,kFAAkF,GAClF,OAAO,SAASE;QAEZF;IADF,MAAMG,SAASC,QACbJ,mDAAAA,QAAQC,GAAG,CAAC,sCAAsC,YAAlDD,mDAAsD,IACtDK,IAAI;IACN,IAAI,CAACF,QAAQ,OAAO;IACpB,qEAAqE;IACrE,4EAA4E;IAC5E,wEAAwE;IACxE,qDAAqD;IACrD,MAAMG,SAAS;QACb,MAAM,EAAEC,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC;QACvC,OAAOA,cAAcC,GAAG,GAAGC,OAAO,GAAGN,MAAM,CAACA;IAC9C;IACA,OAAO;QACLA;QACAO,MAAM;;YACJ,MAAM,CAACC,SAAS,GAAG,MAAM,AAAC,CAAA,MAAML,QAAO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