@aglyn/tenant-data-admin 1.19.0 → 1.20.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.
- package/package.json +7 -7
- package/src/lib/server/host-visitor-records.d.ts +8 -1
- package/src/lib/server/host-visitor-records.js +16 -5
- package/src/lib/server/host-visitor-records.js.map +1 -1
- package/src/lib/server/media-tombstone.d.ts +0 -15
- package/src/lib/server/media-tombstone.js +34 -2
- package/src/lib/server/media-tombstone.js.map +1 -1
- package/src/lib/server/plugin-runs-on.d.ts +62 -0
- package/src/lib/server/plugin-runs-on.js +142 -0
- package/src/lib/server/plugin-runs-on.js.map +1 -0
- package/src/lib/server/realm-plugins.d.ts +5 -1
- package/src/lib/server/realm-plugins.js +45 -1
- package/src/lib/server/realm-plugins.js.map +1 -1
- package/src/lib/server/scope-sharing-sweep.js +23 -1
- package/src/lib/server/scope-sharing-sweep.js.map +1 -1
- package/src/lib/server/transfer-host.js +16 -2
- package/src/lib/server/transfer-host.js.map +1 -1
- package/src/lib/server/upsert-contact.js +2 -19
- package/src/lib/server/upsert-contact.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/tenant-data-admin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.20.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,12 +25,12 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-util-email": "1.
|
|
30
|
-
"@aglyn/shared-util-fbserver": "1.
|
|
31
|
-
"@aglyn/shared-util-first-touch": "1.
|
|
32
|
-
"@aglyn/shared-util-http": "1.
|
|
33
|
-
"@aglyn/shared-util-tools": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.20.0",
|
|
29
|
+
"@aglyn/shared-util-email": "1.20.0",
|
|
30
|
+
"@aglyn/shared-util-fbserver": "1.20.0",
|
|
31
|
+
"@aglyn/shared-util-first-touch": "1.20.0",
|
|
32
|
+
"@aglyn/shared-util-http": "1.20.0",
|
|
33
|
+
"@aglyn/shared-util-tools": "1.20.0",
|
|
34
34
|
"@msgpack/msgpack": "^3.1.3",
|
|
35
35
|
"@swc/helpers": "0.5.23",
|
|
36
36
|
"sharp": "^0.35.5",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
*/
|
|
26
26
|
import { type VisitorRecordKind } from '@aglyn/aglyn/server';
|
|
27
27
|
import { type PluginConversionTouch } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit';
|
|
28
|
-
import type { ConsentGroup, ScopeToken } from '@aglyn/aglyn/server';
|
|
28
|
+
import type { ConsentGroup, CrmScopeFields, ScopeToken } from '@aglyn/aglyn/server';
|
|
29
29
|
/**
|
|
30
30
|
* A lead's one home: `orgs/{orgId}/leads/{personKey}` (AGL-3275).
|
|
31
31
|
*
|
|
@@ -104,6 +104,13 @@ export declare function leadReadTokensForHost(hostId: string, group?: ConsentGro
|
|
|
104
104
|
* `upsert-contact` does.
|
|
105
105
|
*/
|
|
106
106
|
export declare function leadScopeForHost(hostId: string, org?: Record<string, unknown> | null): Promise<ScopeToken[]>;
|
|
107
|
+
/**
|
|
108
|
+
* {@link leadScopeForHost} with the marker a NEW lead carries under the CRM
|
|
109
|
+
* default "All sites except…" (AGL-4047), which lets a site added later join
|
|
110
|
+
* it (`crmScopeFields`). An existing lead never takes it from a capture:
|
|
111
|
+
* widening a record that exists is the "Apply to existing records" run's.
|
|
112
|
+
*/
|
|
113
|
+
export declare function leadScopeFieldsForHost(hostId: string, org?: Record<string, unknown> | null): Promise<CrmScopeFields>;
|
|
107
114
|
/**
|
|
108
115
|
* The lead for an address, wherever it currently lives.
|
|
109
116
|
*
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
|
|
2
3
|
/**
|
|
3
4
|
* @license
|
|
4
5
|
* Copyright 2026 Aglyn LLC
|
|
@@ -29,7 +30,7 @@ import { notifyHostManagers } from "./notifications.js";
|
|
|
29
30
|
import { scheduleCapturedEmailCheck } from "./capture-email-check.js";
|
|
30
31
|
import firebaseAdmin from "./firebase-admin.js";
|
|
31
32
|
import { consentGroupForSite, getOrgForHost, orgDataCollectionForHost, scopedToHost } from "./organizations.js";
|
|
32
|
-
import { composeContactName, crmLeadListFields, crmReadTokens,
|
|
33
|
+
import { composeContactName, crmLeadListFields, crmReadTokens, crmScopeFields } from "@aglyn/aglyn/server";
|
|
33
34
|
// The module path rather than the barrel, as `upsert-contact.ts` does: a spec
|
|
34
35
|
// that substitutes the barrel keeps the real rule for which group a grant is.
|
|
35
36
|
import { consentGroupForGrant } from "@aglyn/aglyn/app-utils/consent-groups";
|
|
@@ -114,6 +115,14 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
114
115
|
* existing lead union these in rather than replacing, exactly as
|
|
115
116
|
* `upsert-contact` does.
|
|
116
117
|
*/ export async function leadScopeForHost(hostId, org) {
|
|
118
|
+
return (await leadScopeFieldsForHost(hostId, org)).visibleTo;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* {@link leadScopeForHost} with the marker a NEW lead carries under the CRM
|
|
122
|
+
* default "All sites except…" (AGL-4047), which lets a site added later join
|
|
123
|
+
* it (`crmScopeFields`). An existing lead never takes it from a capture:
|
|
124
|
+
* widening a record that exists is the "Apply to existing records" run's.
|
|
125
|
+
*/ export async function leadScopeFieldsForHost(hostId, org) {
|
|
117
126
|
var _ref;
|
|
118
127
|
var _this;
|
|
119
128
|
// The org document decides: a capture with none in hand reads it, rather
|
|
@@ -121,7 +130,7 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
121
130
|
// site. An org that cannot be read stamps the site — never everyone.
|
|
122
131
|
const resolved = (_ref = org != null ? org : (_this = await getOrgForHost(hostId).catch(()=>null)) == null ? void 0 : _this.org) != null ? _ref : null;
|
|
123
132
|
const group = await consentGroupForSite(hostId, resolved);
|
|
124
|
-
return
|
|
133
|
+
return crmScopeFields(resolved, group);
|
|
125
134
|
}
|
|
126
135
|
/**
|
|
127
136
|
* The lead for an address, wherever it currently lives.
|
|
@@ -340,7 +349,9 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
340
349
|
* a contended transaction re-runs that body, and neither of these can
|
|
341
350
|
* change between attempts, so resolving them inside would pay for the org
|
|
342
351
|
* read again on every retry.
|
|
343
|
-
*/ const
|
|
352
|
+
*/ const _ref1 = await leadScopeFieldsForHost(hostId), { visibleTo: scope } = _ref1, marker = _object_without_properties_loose(_ref1, [
|
|
353
|
+
"visibleTo"
|
|
354
|
+
]);
|
|
344
355
|
const group = await consentGroupForSite(hostId);
|
|
345
356
|
const now = Date.now();
|
|
346
357
|
const seen = _extends({
|
|
@@ -519,10 +530,10 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
519
530
|
* the contact door has always used for this field, now that a lead
|
|
520
531
|
* has the same question to answer.
|
|
521
532
|
*/ [CAPTURED_BY_HOST_FIELD]: FieldValue.arrayUnion(hostId)
|
|
522
|
-
}, existing.exists ? {} : {
|
|
533
|
+
}, existing.exists ? {} : _extends({
|
|
523
534
|
firstSeenAtMs: now,
|
|
524
535
|
createdAt: FieldValue.serverTimestamp()
|
|
525
|
-
}, lead.marketingConsent ? marketingConsentFieldsForGroup(consentGroupForGrant(group, lead.disclosedConsentGroup), consentAtMs) : {}), {
|
|
536
|
+
}, marker), lead.marketingConsent ? marketingConsentFieldsForGroup(consentGroupForGrant(group, lead.disclosedConsentGroup), consentAtMs) : {}), {
|
|
526
537
|
merge: true
|
|
527
538
|
});
|
|
528
539
|
return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-visitor-records.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 durable half of the visitor-record ceilings (AGL-1529) — the lead\n * writer that enforces `LEADS_MAX_PER_HOST`, and the bookkeeping that makes a\n * trip of EITHER ceiling something a site's owner can see.\n *\n * The policy is pure and lives in `@aglyn/aglyn/server`\n * (`visitor-record-ceiling.ts`); this is the part that needs Firestore. Same\n * split as `visitorWriteRateLimitRefusal`, and for the same reason.\n */\n\nimport {\n CAPTURED_BY_HOST_FIELD,\n checkVisitorRecordCeiling,\n containerMembershipField,\n LEADS_MAX_PER_HOST,\n marketingConsentFieldsForGroup,\n normalizeContainerIds,\n personKey,\n readMarketingBasis,\n utcMonthKey,\n VISITOR_RECORD_NOTICE_SENT_FIELD,\n visitorRecordAcceptFillsCeiling,\n visitorRecordCeilingAnnounced,\n visitorRecordRefusedCounterId,\n type VisitorRecordKind,\n} from '@aglyn/aglyn/server'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n creditConversion,\n type PluginConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { notifyHostManagers } from './notifications'\nimport { scheduleCapturedEmailCheck } from './capture-email-check'\nimport firebaseAdmin from './firebase-admin'\nimport {\n consentGroupForSite,\n getOrgForHost,\n orgDataCollectionForHost,\n resolveOrgIdForHost,\n scopedToHost,\n} from './organizations'\nimport {\n composeContactName,\n crmLeadListFields,\n crmReadTokens,\n crmScopeTokens,\n} from '@aglyn/aglyn/server'\nimport type { ConsentGroup, ScopeToken } from '@aglyn/aglyn/server'\n// The module path rather than the barrel, as `upsert-contact.ts` does: a spec\n// that substitutes the barrel keeps the real rule for which group a grant is.\nimport { consentGroupForGrant } from '@aglyn/aglyn/app-utils/consent-groups'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/**\n * A lead's one home: `orgs/{orgId}/leads/{personKey}` (AGL-3275).\n *\n * ## Why leads moved\n *\n * A lead used to live at `hosts/{hostId}/leads/{personKey}` while the\n * contact for the same human lived on the org with a `visibleTo` array. The\n * path was doing the job `visibleTo` does, and doing it worse:\n *\n * - An AGENCY was isolated by the path. It is isolated by `visibleTo` too,\n * with no configuration — `consentGroupScope` on a group of one is\n * `['host:{id}']`.\n * - A MULTI-BRAND org could not be served at all. `personKey` is derived\n * from the address, so the same person captured on two sibling brands\n * produced two documents with byte-identical ids under different parents.\n * One person was two records by construction, which is the thing AGL-3232\n * had just finished eliminating for contacts.\n * - The two answers could disagree. A person's contact was visible to every\n * brand in the consent group they actually consented to — the disclosure\n * names those brands — while their lead was visible to whichever brand's\n * form they happened to land on. The lead was scoped more narrowly than\n * what the person was told, which is the safe direction to be wrong in and\n * still the wrong answer.\n *\n * So a lead is stamped with `crmScopeTokens` and read with `crmReadTokens`,\n * the same pair the contacts surface uses. Nothing here is a new mechanism;\n * this is leads arriving at the one the rest of the CRM already had.\n *\n * ## The fallback is READ-ONLY, and temporary\n *\n * This repo has run this migration once already — AGL-237 moved datasets,\n * contacts and media to the org, AGL-1040 backfilled, AGL-1050 deleted the\n * fallback — and `orgDataCollectionForHost` carries what it learned:\n *\n * \"a second storage path that can still be WRITTEN is a second boundary to\n * enforce forever, which undoes the premise of scoped sharing: one home\n * per resource plus an explicit scope.\"\n *\n * So the host path is never written here. It is read, once, to carry a\n * not-yet-migrated lead onto the org as a side effect of the next write that\n * touches it ({@link leadForWrite}) — which shrinks what AGL-3276's backfill\n * has left to fold, and means no read can be answered by a stale host row\n * after a write has moved on. AGL-3277 deletes the fallback and the rules\n * block behind it once that backfill reports nothing left to plan.\n */\n\n\n/**\n * The org collection a lead is written to. Always the org — see the\n * read-only note above.\n */\nexport async function orgLeadsForHost(\n hostId: string,\n): Promise<FirebaseFirestore.CollectionReference> {\n return orgDataCollectionForHost(hostId, 'leads')\n}\n\n/**\n * The leads one site may LIST, narrowed by `visibleTo`.\n *\n * The Admin SDK does not evaluate rules, so an unnarrowed read here would\n * serve one agency client's leads on another's site — the same reason\n * `scopedToHost` exists for every other org-owned collection.\n */\nexport async function orgLeadsQueryForHost(hostId: string): Promise<{\n ref: FirebaseFirestore.CollectionReference\n query: FirebaseFirestore.Query\n}> {\n const ref = await orgLeadsForHost(hostId)\n return { ref, query: scopedToHost(ref, hostId) }\n}\n\n/**\n * The tokens a reader holding this group may ask `array-contains-any` for.\n * Capped at 30 by `crmReadTokens`, as the contacts list is.\n */\nexport async function leadReadTokensForHost(\n hostId: string,\n group?: ConsentGroup,\n): Promise<ScopeToken[]> {\n return crmReadTokens(group ?? (await consentGroupForSite(hostId)))\n}\n\n/**\n * The `visibleTo` a capture on this site stamps: `['org']` where the org's\n * CRM default (`crmDefaultScopeOf`) is `'org'` — its default — and the consent\n * group's sites where the org keeps its sites apart.\n *\n * Widened by the capture, never by the lookup — a site that has never\n * captured this person gains nothing by finding them, which is what keeps an\n * agency's clients apart on a record they share. Callers UPDATING an\n * existing lead union these in rather than replacing, exactly as\n * `upsert-contact` does.\n */\nexport async function leadScopeForHost(\n hostId: string,\n org?: Record<string, unknown> | null,\n): Promise<ScopeToken[]> {\n // The org document decides: a capture with none in hand reads it, rather\n // than stamping the site alone for an org whose records belong to every\n // site. An org that cannot be read stamps the site — never everyone.\n const resolved =\n org ?? ((await getOrgForHost(hostId).catch(() => null))?.org as Record<string, unknown> | undefined) ?? null\n const group = await consentGroupForSite(hostId, resolved)\n return crmScopeTokens(resolved, group)\n}\n\n/**\n * The lead for an address, wherever it currently lives.\n *\n * ## The lookup is UNSCOPED, and has to be\n *\n * One human who touched two sibling brands is one person. Narrowing this to\n * what the capturing site may already see would let a second submission on a\n * sibling brand mint a SECOND record for the same address — the duplication\n * this migration exists to end, reintroduced one layer up. Recognizing\n * somebody and being allowed to read their row are different acts:\n * this finds the person, {@link leadScopeForHost} decides who may see them.\n *\n * `upsert-contact` states the same rule at its own dedupe lookup, and for the\n * same reason. A caller that wants only what a site may SEE wants\n * {@link orgLeadsQueryForHost}.\n *\n * @returns the org row; else the not-yet-migrated host row; else `null`.\n */\nexport async function readLeadForHost(\n hostId: string,\n key: string,\n): Promise<FirebaseFirestore.DocumentSnapshot | null> {\n const orgRow = await (await orgLeadsForHost(hostId)).doc(key).get()\n return orgRow.exists ? orgRow : null\n}\n\n/**\n * The ref a write should target.\n *\n * This carried a not-yet-backfilled host row onto the org first, and reported\n * whether it had (`carried`). AGL-3276 emptied the host path and AGL-3277\n * removed it, so there is nothing left to carry: the org row is the only row.\n * `carried` stays on the shape, always `false`, because several callers\n * destructure it and a lie is cheaper to read than a signature change that\n * says nothing.\n */\nexport async function leadForWrite(\n hostId: string,\n key: string,\n): Promise<{\n ref: FirebaseFirestore.DocumentReference\n existed: boolean\n carried: boolean\n}> {\n const ref = (await orgLeadsForHost(hostId)).doc(key)\n return { ref, existed: (await ref.get()).exists, carried: false }\n}\n\n\n/**\n * Make a tripped ceiling OBSERVABLE rather than a silent drop — the * standing rule that a control which is not visible in the console does not\n * count as shipped.\n *\n * Two audiences, one call, in exactly `recordAbuseCeilingTrip`'s shape\n * (`libs/plugins/forms/src/lib/server/form-submit.ts`, AGL-1655):\n *\n * - A durable per-month refusal count at\n * `hosts/{id}/counters/{siteMembers|leads}Refused`. Counters are excluded\n * from every client write in `cloud/firebase-firestore.rules` (AGL-1367),\n * so the record cannot be edited away by the site it describes, and host\n * admins can already READ it — which is what lets the inbox console page\n * render it with no rules change.\n * - One notification to the site's managers per CROSSING (AGL-3442): on the\n * first refusal after the site reaches the ceiling, and not again while it\n * stays there. A notification per refused bot request would be the flood\n * again, delivered, and one a month would repeat an alarm about a state a\n * site can sit in for months. {@link rearmVisitorRecordCeilingNotice}\n * re-arms it once the site is seen below the ceiling, so reaching it again\n * is announced again.\n *\n * The counter is month-keyed even though the CEILING is a total, because the\n * two facts are different: the ceiling is \"how many records exist\" and this is\n * \"how many were turned away recently\". The inbox reports the second; the\n * notice announces the first, which is why it follows the crossing and not\n * the month.\n *\n * Best-effort throughout: bookkeeping that failed must never turn a contained\n * refusal into a 500, because a 500 is an invitation to retry.\n */\nexport async function recordVisitorRecordCeilingTrip(options: {\n hostRef: FirebaseFirestore.DocumentReference\n hostId: string\n kind: VisitorRecordKind\n ceiling: number\n monthKey?: string\n}): Promise<void> {\n const { hostRef, hostId, kind, ceiling } = options\n const monthKey = options.monthKey ?? utcMonthKey()\n try {\n const refusedRef = hostRef\n .collection('counters')\n .doc(visitorRecordRefusedCounterId(kind))\n const refusedSnapshot = await refusedRef.get()\n // Announced already for this crossing, by this writer or by the\n // month-scoped one before it — see `visitorRecordCeilingAnnounced`.\n const announced = visitorRecordCeilingAnnounced(refusedSnapshot.data())\n const now = Date.now()\n await refusedRef.set(\n {\n [monthKey]: FieldValue.increment(1),\n // Explicit values only — Firestore rejects `undefined`.\n ceiling,\n lastRefusedAtMs: now,\n // Marked in the same write as the refusal, so the next refusal reads\n // the crossing as announced without a write of its own.\n ...(announced ? {} : { [VISITOR_RECORD_NOTICE_SENT_FIELD]: now }),\n },\n { merge: true },\n )\n if (!announced) {\n const leads = kind === 'leads'\n /*\n * What is refused, said exactly (AGL-3432). A lead door — a form\n * routed to leads, a booking — stores its own record BEFORE it files\n * the lead, so at the ceiling the visitor's submission or booking is\n * still kept and only the new lead is not. A member sign-up is refused\n * whole: no account is created. `{site}` is the site's name, filled by\n * `notifyHostManagers` from the host doc it already reads.\n */\n await notifyHostManagers(hostId, {\n type: 'system.visitorRecordsPaused',\n title: leads\n ? 'Lead capture paused on {site} — platform limit reached'\n : 'Sign-ups paused on {site} — platform limit reached',\n body: leads\n ? `{site} holds ${ceiling.toLocaleString()} leads, the platform ` +\n 'safety limit, so new people are no longer added as leads. What ' +\n 'they send, such as a form submission or a booking, is still ' +\n 'saved; only the new lead is not. This limit is not part of your ' +\n 'plan — every plan includes unlimited leads — and nothing is ' +\n 'charged. Remove some leads, or contact support if this is real ' +\n 'traffic.'\n : `{site} has ${ceiling.toLocaleString()} member accounts, the ` +\n 'platform safety limit, so new sign-ups are refused and no ' +\n 'account is created. This limit is not part of your plan — every ' +\n 'plan includes unlimited member accounts — and nothing is ' +\n 'charged. Remove some members, or contact support if this is ' +\n 'real traffic.',\n link: `/${hostId}/inbox`,\n })\n }\n } catch (error) {\n console.error('visitor record ceiling bookkeeping failed', error)\n }\n}\n\n/**\n * Re-arm the ceiling notice when an accepted record shows the site was below\n * the ceiling (AGL-3442).\n *\n * Called by every writer that judges a new record against the ceiling, with\n * the count it judged. It does nothing unless the record it just accepted took\n * the site's LAST free slot: a site that dropped below the ceiling can reach\n * it again only through that accept, so it is where the re-arm is observed,\n * and every other accept pays nothing for it. That accept reads the refusal\n * counter, and clears the notice marker only when the previous crossing was\n * announced, so a site that never reached the ceiling gains no document.\n *\n * Best-effort and never throws, for the reason the trip's bookkeeping is: the\n * record is already stored, and a failure here only costs a notice.\n */\nexport async function rearmVisitorRecordCeilingNotice(options: {\n hostRef: FirebaseFirestore.DocumentReference\n kind: VisitorRecordKind\n /** The live count the accept was judged against, before its own record. */\n used: number\n ceiling: number\n}): Promise<void> {\n const { hostRef, kind, used, ceiling } = options\n if (!visitorRecordAcceptFillsCeiling(used, ceiling)) return\n try {\n const refusedRef = hostRef\n .collection('counters')\n .doc(visitorRecordRefusedCounterId(kind))\n const refusedSnapshot = await refusedRef.get()\n if (!visitorRecordCeilingAnnounced(refusedSnapshot.data())) return\n await refusedRef.set(\n { [VISITOR_RECORD_NOTICE_SENT_FIELD]: null },\n { merge: true },\n )\n } catch (error) {\n console.error('visitor record ceiling re-arm failed', error)\n }\n}\n\n/** What a caller wants stored on the lead. `createdAt` is stamped here. */\nexport interface HostLeadInput {\n email: string\n /** The name the person typed, when they typed one (AGL-2303). */\n name?: string\n /** `signup`, `booking`, `form:{formId}` — the surface that produced it. */\n source: string\n /**\n * Explicit marketing opt-in, with a consent timestamp — the same shape\n * `upsertHostContact` already carries (AGL-301). Omitted or `false` writes\n * nothing: a lead is a side effect of an action the visitor DID take\n * (sign up, book), which is not by itself consent to be emailed\n * marketing, so this is only set when the caller captured an explicit\n * checkbox.\n */\n marketingConsent?: boolean\n /**\n * The `consentGroupDisclosureKey` the capture surface rendered beside that\n * checkbox (AGL-3320). The grant pools across the site's consent group only\n * when it is the group's current key, and is this site's alone otherwise —\n * the same rule `upsertHostContact` applies.\n */\n disclosedConsentGroup?: string | null\n /**\n * The campaigns the capture SURFACE is filed under (AGL-3458) — a form's\n * `campaignIds`, read by the door off the verified form document. Never the\n * campaign touch, which is where the visitor came from: this is which\n * campaigns the merchant put the form in, and it is true of everybody who\n * fills that form in.\n *\n * Unioned into the lead's own `campaignIds` — the field the enroll route\n * and the bulk bar write — so a campaign the lead joined by hand or by a\n * sequence is kept, and the Leads list's Campaign filter\n * (`scopedCampaignIds`) is restamped from the union in the same write.\n */\n campaignIds?: readonly string[]\n /**\n * A phone the capture learned (AGL-3493), E.164 as the door normalized\n * it. Written only when the lead holds none: a number a rep typed on the\n * lead, or an earlier capture brought, is not replaced by this one.\n */\n phoneFill?: string\n}\n\n/**\n * Record one lead at `hosts/{hostId}/leads/{personKey}`, bounded by\n * `LEADS_MAX_PER_HOST` (AGL-1529).\n *\n * ## One person is one document\n *\n * `docs/specs/reusable-forms.md` §4b. This used to be `tx.create(ref.doc())`\n * — an auto-id per capture event — so one returning customer who signed up\n * and booked twice was three \"leads\". The Members & leads tab presented a\n * list of events as a list of people, and the only thing holding two rows for\n * one person together was string equality on the address at render time.\n *\n * The events are not lost, they are just no longer the record: `sources`\n * carries every surface that produced a capture, `submissionCount` counts\n * them, and `firstSeenAtMs`/`lastSeenAtMs` bracket them. The submissions, the\n * bookings and the member document are still there and still one row each.\n *\n * The id is {@link personKey} — `sha256(normalizeContactEmail(email))`, the\n * SAME derivation a list membership's `memberKey` uses, imported rather than\n * restated. Two specs named this function and the rule both stated is that\n * whichever ships second imports the first's helper: a second copy is how\n * `emailSuppressionKey` and `suppressionId` came to disagree.\n *\n * ## Why every lead writer goes through here\n *\n * There are three lead writes in the repo — the sign-up handler and the two\n * bookings paths — and all three were `hostRef.collection('leads').add(…)`\n * with a `.catch()` on the end. A cap enforced at two of three call sites is\n * not a cap, and the fourth writer somebody adds next month would not have\n * one either. One function is the only shape that survives that.\n *\n * ## The count is evaluated INSIDE the transaction that writes\n *\n * A create-time quota can be laundered by WHEN it is evaluated, not by the\n * counting rule (AGL-2231/2265/2266). Read-then-decide-then-`add()` lets N\n * concurrent visitors each read the same pre-count, each find room, and each\n * land — and nothing re-counts afterwards, so the extra rows are permanent.\n * `Transaction.get(AggregateQuery)` serialises the count against a concurrent\n * create into the same collection: the loser retries, re-reads the higher\n * count, and is refused. The count is of LIVE documents, so triaging leads in\n * the inbox frees the slots.\n *\n * ## Refusing a lead never fails the visitor's action\n *\n * A lead is a SIDE EFFECT — of a sign-up, or of a booking. The visitor did\n * not ask for it and cannot see it, so refusing one must not refuse the thing\n * they did ask for. This returns a boolean and never throws; the trip is\n * recorded and the caller carries on. That is the honest split, and it is why\n * `SITE_MEMBERS_MAX_PER_HOST` (which governs an action a visitor DID take) is\n * enforced with a 429 in the sign-up handler and this is not.\n */\nexport async function addHostLeadOutcome(options: {\n hostRef: FirebaseFirestore.DocumentReference\n hostId: string\n lead: HostLeadInput\n /**\n * The ceiling to compare against. Defaults to `LEADS_MAX_PER_HOST` and is\n * passed by NOTHING in production — it exists so the suite can re-drive the\n * same count against a ceiling one higher and require the write to succeed.\n * A refusal that survives its own ceiling being raised was never that\n * ceiling's refusal, and there is exactly ONE comparison below, so knifing\n * it cannot be absorbed by a fallback branch.\n */\n ceiling?: number\n /**\n * Where this person arrived from, already resolved by the door through the\n * plugin that credits outcomes (`plugin-conversion-credit`), and opaque\n * here.\n *\n * Resolved rather than raw, and passed rather than looked up, because one\n * visitor action reaches several writers: a form submission that creates a\n * submission, a contact AND a lead must pay for the touch lookup once. A\n * door that hands none — every order path, every import — attributes\n * nothing, which is how a lead that no campaign caused stays uncredited.\n */\n touch?: PluginConversionTouch | null\n}): Promise<HostLeadOutcome> {\n const { hostRef, hostId, lead } = options\n const maxPerHost = options.ceiling ?? LEADS_MAX_PER_HOST\n try {\n const leadsRef = await orgLeadsForHost(hostId)\n const firestore = hostRef.firestore\n /*\n * `null` for anything that is not a usable address — a lead captured\n * against a malformed one keeps an auto-id and stays its own row. Keying\n * several unusable addresses under one guessed id would merge two\n * different people, which is worse than two rows for one.\n */\n const key = personKey(lead.email)\n /*\n * A lead the org has not taken over yet is carried across BEFORE the\n * transaction opens (AGL-3275). It has to happen outside: the carry is\n * itself a read-then-write, and a transaction that also counted the\n * collection would be reading a row it was about to create. Two doors\n * carrying the same person in the same second both write the legacy\n * fields under `merge`, so the race is a no-op rather than a conflict.\n */\n const leadRef = key\n ? (await leadForWrite(hostId, key)).ref\n : leadsRef.doc()\n /*\n * The scope this capture stamps, and the group whose terms its consent is\n * recorded under. Both resolved HERE rather than in the transaction body:\n * a contended transaction re-runs that body, and neither of these can\n * change between attempts, so resolving them inside would pay for the org\n * read again on every retry.\n */\n const scope = await leadScopeForHost(hostId)\n const group = await consentGroupForSite(hostId)\n const now = Date.now()\n const seen = {\n // `arrayUnion`, so a person who books twice has `['booking']` and one\n // who signed up and then submitted a form has both. Bounded by the\n // number of surfaces, not by the number of captures.\n sources: FieldValue.arrayUnion(lead.source),\n lastSeenAtMs: now,\n submissionCount: FieldValue.increment(1),\n ...(lead.name ? { name: lead.name } : {}),\n }\n let created = false\n let sourceAdded = false\n let predicted = false\n // The count a new person was judged against, for the notice re-arm.\n let usedBeforeCreate: number | null = null\n const refused = await firestore.runTransaction(async (tx) => {\n // Reset per attempt: a contended transaction re-runs its body, and a\n // flag left standing from an aborted attempt would credit a campaign\n // with a person who turned out to exist already.\n created = false\n sourceAdded = false\n usedBeforeCreate = null\n // ALL READS BEFORE THE WRITE, which Firestore requires.\n const existing = await tx.get(leadRef)\n // Whether the lead already reads \"Would bounce\", for the check below.\n predicted = (existing.data() ?? {})['emailStatus'] === 'undeliverable'\n /*\n * ⛔ THE CEILING GATES A NEW PERSON, NEVER AN EXISTING ONE.\n *\n * A returning visitor's capture is an UPDATE — it does not grow the\n * collection, so refusing it buys no capacity and costs the customer\n * the source and the timestamp they would have learned. That is the\n * enforcement-at-use shape the capacity rule exists to forbid: a limit\n * must refuse the addition, never a person already recorded or the\n * data attached to them.\n *\n * It also means the count is only paid on a genuinely new person,\n * which is the case that can move it.\n */\n if (!existing.exists) {\n /*\n * COUNTED OVER WHAT THIS SITE MAY SEE, not over the org (AGL-3275).\n *\n * The collection is org-wide now, and `LEADS_MAX_PER_HOST` is a\n * per-SITE ceiling. An unfiltered count would charge every brand in\n * an agency's account for every other brand's leads, and the first\n * client to fill its allowance would refuse captures on sites that\n * had taken none. `scopedToHost` is the same narrowing every other\n * org-owned read uses, so a single-site org counts exactly what it\n * counted before this moved.\n *\n * A lead shared by two brands in one consent group is counted by\n * both, which is the honest answer: each of them holds it.\n */\n const used = (\n await tx.get(scopedToHost(leadsRef, hostId).count())\n ).data().count\n if (checkVisitorRecordCeiling(used, maxPerHost).exceeded) return true\n usedBeforeCreate = used\n }\n /*\n * Consent is carried forward and never cleared.\n *\n * A basis is written only when this capture carried an explicit\n * opt-in, so a later booking by someone who did not tick the box\n * leaves an earlier grant standing — absent-or-granted, the shape\n * every other writer uses. The TIMESTAMP is carried over rather than\n * restamped, for the reason given at the read below.\n */\n /*\n * The EARLIEST grant is the one that happened, so a later capture\n * carrying the same checkbox keeps the original date rather than\n * restamping when this person opted in. Read back through the shared\n * reader so \"already consented\" means the same thing here as it does\n * at send time.\n */\n /*\n * THE SITE'S REAL GROUP, because the silo that justified a group of one\n * is gone (AGL-3275).\n *\n * This read `soloConsentGroup(hostId)` for as long as a lead lived at\n * `hosts/{hostId}/leads`, and the reason was the path: private by\n * construction, so pooling a lead's basis would have recorded a\n * disclosure that reached nothing, while the contact written by the\n * same capture door was org-shared and pooled.\n *\n * A lead is now org-shared on exactly the terms the contact is, so the\n * premise is false and keeping the group of one would leave a\n * multi-brand org holding a lead its sibling brand can SEE but may not\n * MAIL — a narrower basis than the one `consentGroupDisclosure` named\n * beside the checkbox this person ticked. Pooling here records what\n * they were actually told, and only that: the grant reaches the group\n * when the capture surface sent back the group's current disclosure\n * key (AGL-3320), and this site alone otherwise. An undeclared group is\n * still a group of one, so an agency is unchanged and configures\n * nothing.\n *\n * Resolved above the transaction — see `group`'s declaration.\n */\n const prior = readMarketingBasis(existing.data() ?? null, group)\n const consentAtMs =\n prior.basis === 'granted' && prior.basisAtMs !== null\n ? prior.basisAtMs\n : now\n created = !existing.exists\n /*\n * Whether this capture puts its surface on the person for the FIRST\n * time: a new lead, or one first met through another door. A form\n * counts its leads by this (AGL-3330) — the people it filed, which is\n * what a recount of `sources` finds — so a returning visitor's second\n * submission moves no form's lead count.\n */\n const storedSources = (existing.data() ?? {})['sources']\n sourceAdded =\n created || !(Array.isArray(storedSources) && storedSources.includes(lead.source))\n /*\n * THE FIELDS THE LEADS LIST QUERIES (AGL-3321), from the lead as it\n * will stand: what the transaction read, the address and name this\n * capture brings and the scope it widens. A new lead is written\n * `status: 'new'`, so the Open view's `status in [new, working]`\n * finds a lead nobody has touched — an absent field matches no query.\n */\n const stored = existing.data() ?? {}\n const phoneFill =\n lead.phoneFill && !String(stored['phone'] ?? '').trim()\n ? { phone: lead.phoneFill }\n : {}\n const storedScope = Array.isArray(stored['visibleTo']) ? (stored['visibleTo'] as unknown[]) : []\n /*\n * THE CAMPAIGNS, unioned (AGL-3458). Computed from what the transaction\n * read rather than written as an `arrayUnion`, so the Campaign filter's\n * scoped keys below are derived from the same list the write stores,\n * and the union is held to the membership cap every reader applies.\n * Written only when the capture names one, so a door with no campaign\n * never rewrites the field a person or a sequence filled.\n */\n // The field a lead holds its campaigns in, at the top of its document.\n const campaignsField = lead.campaignIds?.length ? containerMembershipField('campaign') : null\n const campaigns = campaignsField\n ? normalizeContainerIds([\n ...normalizeContainerIds(stored[campaignsField]),\n ...(lead.campaignIds ?? []),\n ])\n : null\n /*\n * A lead that keeps a first or last name keeps the name they make\n * (AGL-3513): a capture's typed name does not replace it.\n */\n const composedName = composeContactName(stored['firstName'], stored['lastName'])\n const name = composedName || lead.name\n const listFields = crmLeadListFields({\n ...stored,\n email: lead.email,\n ...(name ? { name } : {}),\n visibleTo: [...new Set([...storedScope, ...scope])],\n ...(campaignsField && campaigns ? { [campaignsField]: campaigns } : {}),\n })\n tx.set(\n leadRef,\n {\n email: lead.email,\n ...seen,\n ...(composedName ? { name: composedName } : {}),\n ...phoneFill,\n ...listFields,\n ...(campaignsField && campaigns ? { [campaignsField]: campaigns } : {}),\n /*\n * WIDENED BY THE CAPTURE, NEVER BY THE LOOKUP (AGL-3275).\n *\n * `arrayUnion` rather than a replace, exactly as `upsert-contact`\n * stamps a contact: this site just collected this person, so it may\n * see the row. A site that merely FOUND them — the unscoped dedupe\n * lookup in `readLeadForHost` — gains nothing, which is what keeps\n * an agency's clients apart on a record they share.\n */\n visibleTo: FieldValue.arrayUnion(...scope),\n /*\n * EVERY SITE THAT CAPTURED THIS PERSON, not just the first\n * (AGL-3275).\n *\n * This was written once, on create, and that was sound while the\n * collection sat under one host and could hold only that host's\n * name. On the org the row is shared, so a sibling brand capturing\n * a person the first brand already holds has to be recorded here or\n * the \"Known by\" answer silently omits it — the same `arrayUnion`\n * the contact door has always used for this field, now that a lead\n * has the same question to answer.\n */\n [CAPTURED_BY_HOST_FIELD]: FieldValue.arrayUnion(hostId),\n ...(existing.exists\n ? {}\n : {\n firstSeenAtMs: now,\n createdAt: FieldValue.serverTimestamp(),\n }),\n /*\n * The basis is recorded under the GROUP, keyed by its host, because\n * {@link readMarketingBasis} is one function over four silos and a\n * silo whose basis lived somewhere else would need the reader to\n * know which collection it was handed. A reader that has to be told\n * the shape is a reader that can be told the wrong one.\n */\n ...(lead.marketingConsent\n ? marketingConsentFieldsForGroup(\n consentGroupForGrant(group, lead.disclosedConsentGroup),\n consentAtMs,\n )\n : {}),\n },\n { merge: true },\n )\n return false\n })\n if (refused) {\n await recordVisitorRecordCeilingTrip({\n hostRef,\n hostId,\n kind: 'leads',\n ceiling: maxPerHost,\n })\n return NOT_STORED\n }\n if (created && usedBeforeCreate !== null) {\n await rearmVisitorRecordCeilingNotice({\n hostRef,\n kind: 'leads',\n used: usedBeforeCreate,\n ceiling: maxPerHost,\n })\n }\n /*\n * ATTRIBUTED ON CREATION ONLY.\n *\n * A returning visitor's capture is an update — the campaign did not\n * produce a lead, it produced another visit by a person the site already\n * held — and crediting it would let whichever campaign ran most recently\n * re-earn every lead on the list. `created` is set inside the transaction\n * that decides it, so the attribution and the write agree about whether\n * this person is new.\n *\n * Awaited rather than fired off: `addHostLead` already returns only after\n * its own write, and a caller that `void`s it (every one of them) is\n * unaffected. Never throws, so a failure here cannot cost the lead.\n */\n /*\n * THE ADDRESS'S DOMAIN, checked after the response (AGL-3328): a lead\n * whose domain takes no mail reads \"Would bounce\". Queued, never\n * awaited — the write above is the capture, and this costs it nothing.\n */\n scheduleCapturedEmailCheck({\n orgId: leadsRef.parent?.id ?? null,\n hostId,\n email: lead.email,\n predicted,\n })\n if (created && options.touch) {\n await creditConversion({\n hostId,\n kind: 'lead',\n refId: leadRef.id,\n touch: options.touch,\n convertedAtMs: now,\n })\n }\n return { stored: true, created, sourceAdded }\n } catch (error) {\n // Same posture the three original call sites had (`.catch(() => undefined)`\n // / `.catch(console.error)`): a lead that failed to store must not fail\n // the sign-up or the booking that produced it.\n console.error('lead write failed', error)\n return NOT_STORED\n }\n}\n\n/** What {@link addHostLeadOutcome} did with one capture. */\nexport interface HostLeadOutcome {\n /** Whether the lead was written — false when refused or failed. */\n stored: boolean\n /** Whether it was a new person. */\n created: boolean\n /** Whether this capture's `source` was new on the lead — see the write. */\n sourceAdded: boolean\n}\n\nconst NOT_STORED: HostLeadOutcome = { stored: false, created: false, sourceAdded: false }\n\n/**\n * {@link addHostLeadOutcome}, answering only whether the lead was stored —\n * the question every door but a form's asks.\n */\nexport async function addHostLead(\n options: Parameters<typeof addHostLeadOutcome>[0],\n): Promise<boolean> {\n return (await addHostLeadOutcome(options)).stored\n}\n"],"names":["CAPTURED_BY_HOST_FIELD","checkVisitorRecordCeiling","containerMembershipField","LEADS_MAX_PER_HOST","marketingConsentFieldsForGroup","normalizeContainerIds","personKey","readMarketingBasis","utcMonthKey","VISITOR_RECORD_NOTICE_SENT_FIELD","visitorRecordAcceptFillsCeiling","visitorRecordCeilingAnnounced","visitorRecordRefusedCounterId","FieldValue","creditConversion","notifyHostManagers","scheduleCapturedEmailCheck","firebaseAdmin","consentGroupForSite","getOrgForHost","orgDataCollectionForHost","scopedToHost","composeContactName","crmLeadListFields","crmReadTokens","crmScopeTokens","consentGroupForGrant","firestore","app","orgLeadsForHost","hostId","orgLeadsQueryForHost","ref","query","leadReadTokensForHost","group","leadScopeForHost","org","resolved","catch","readLeadForHost","key","orgRow","doc","get","exists","leadForWrite","existed","carried","recordVisitorRecordCeilingTrip","options","hostRef","kind","ceiling","monthKey","refusedRef","collection","refusedSnapshot","announced","data","now","Date","set","increment","lastRefusedAtMs","merge","leads","type","title","body","toLocaleString","link","error","console","rearmVisitorRecordCeilingNotice","used","addHostLeadOutcome","lead","maxPerHost","leadsRef","email","leadRef","scope","seen","sources","arrayUnion","source","lastSeenAtMs","submissionCount","name","created","sourceAdded","predicted","usedBeforeCreate","refused","runTransaction","tx","existing","stored","count","exceeded","prior","consentAtMs","basis","basisAtMs","storedSources","Array","isArray","includes","phoneFill","String","trim","phone","storedScope","campaignsField","campaignIds","length","campaigns","composedName","listFields","visibleTo","Set","firstSeenAtMs","createdAt","serverTimestamp","marketingConsent","disclosedConsentGroup","NOT_STORED","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;QACT;QACA,IAAI6B,SAAS;YACX,MAAM7C,+BAA+B;gBACnCE;gBACArB;gBACAsB,MAAM;gBACNC,SAASyB;YACX;YACA,OAAOiD;QACT;QACA,IAAIrC,WAAWG,qBAAqB,MAAM;YACxC,MAAMnB,gCAAgC;gBACpCvB;gBACAC,MAAM;gBACNuB,MAAMkB;gBACNxC,SAASyB;YACX;QACF;QACA;;;;;;;;;;;;;KAaC,GACD;;;;KAIC,GACD9D,2BAA2B;YACzBgH,KAAK,WAAEjD,mBAAAA,SAASkD,MAAM,qBAAflD,iBAAiBmD,EAAE,mBAAI;YAC9BpG;YACAkD,OAAOH,KAAKG,KAAK;YACjBY;QACF;QACA,IAAIF,WAAWxC,QAAQiF,KAAK,EAAE;YAC5B,MAAMrH,iBAAiB;gBACrBgB;gBACAsB,MAAM;gBACNgF,OAAOnD,QAAQiD,EAAE;gBACjBC,OAAOjF,QAAQiF,KAAK;gBACpBE,eAAezE;YACjB;QACF;QACA,OAAO;YAAEsC,QAAQ;YAAMR;YAASC;QAAY;IAC9C,EAAE,OAAOnB,OAAO;QACd,4EAA4E;QAC5E,wEAAwE;QACxE,+CAA+C;QAC/CC,QAAQD,KAAK,CAAC,qBAAqBA;QACnC,OAAOuD;IACT;AACF;AAYA,MAAMA,aAA8B;IAAE7B,QAAQ;IAAOR,SAAS;IAAOC,aAAa;AAAM;AAExF;;;CAGC,GACD,OAAO,eAAe2C,YACpBpF,OAAiD;IAEjD,OAAO,AAAC,CAAA,MAAM0B,mBAAmB1B,QAAO,EAAGgD,MAAM;AACnD"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-visitor-records.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 durable half of the visitor-record ceilings (AGL-1529) — the lead\n * writer that enforces `LEADS_MAX_PER_HOST`, and the bookkeeping that makes a\n * trip of EITHER ceiling something a site's owner can see.\n *\n * The policy is pure and lives in `@aglyn/aglyn/server`\n * (`visitor-record-ceiling.ts`); this is the part that needs Firestore. Same\n * split as `visitorWriteRateLimitRefusal`, and for the same reason.\n */\n\nimport {\n CAPTURED_BY_HOST_FIELD,\n checkVisitorRecordCeiling,\n containerMembershipField,\n LEADS_MAX_PER_HOST,\n marketingConsentFieldsForGroup,\n normalizeContainerIds,\n personKey,\n readMarketingBasis,\n utcMonthKey,\n VISITOR_RECORD_NOTICE_SENT_FIELD,\n visitorRecordAcceptFillsCeiling,\n visitorRecordCeilingAnnounced,\n visitorRecordRefusedCounterId,\n type VisitorRecordKind,\n} from '@aglyn/aglyn/server'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n creditConversion,\n type PluginConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { notifyHostManagers } from './notifications'\nimport { scheduleCapturedEmailCheck } from './capture-email-check'\nimport firebaseAdmin from './firebase-admin'\nimport {\n consentGroupForSite,\n getOrgForHost,\n orgDataCollectionForHost,\n resolveOrgIdForHost,\n scopedToHost,\n} from './organizations'\nimport {\n composeContactName,\n crmLeadListFields,\n crmReadTokens,\n crmScopeFields,\n} from '@aglyn/aglyn/server'\nimport type { ConsentGroup, CrmScopeFields, ScopeToken } from '@aglyn/aglyn/server'\n// The module path rather than the barrel, as `upsert-contact.ts` does: a spec\n// that substitutes the barrel keeps the real rule for which group a grant is.\nimport { consentGroupForGrant } from '@aglyn/aglyn/app-utils/consent-groups'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/**\n * A lead's one home: `orgs/{orgId}/leads/{personKey}` (AGL-3275).\n *\n * ## Why leads moved\n *\n * A lead used to live at `hosts/{hostId}/leads/{personKey}` while the\n * contact for the same human lived on the org with a `visibleTo` array. The\n * path was doing the job `visibleTo` does, and doing it worse:\n *\n * - An AGENCY was isolated by the path. It is isolated by `visibleTo` too,\n * with no configuration — `consentGroupScope` on a group of one is\n * `['host:{id}']`.\n * - A MULTI-BRAND org could not be served at all. `personKey` is derived\n * from the address, so the same person captured on two sibling brands\n * produced two documents with byte-identical ids under different parents.\n * One person was two records by construction, which is the thing AGL-3232\n * had just finished eliminating for contacts.\n * - The two answers could disagree. A person's contact was visible to every\n * brand in the consent group they actually consented to — the disclosure\n * names those brands — while their lead was visible to whichever brand's\n * form they happened to land on. The lead was scoped more narrowly than\n * what the person was told, which is the safe direction to be wrong in and\n * still the wrong answer.\n *\n * So a lead is stamped with `crmScopeTokens` and read with `crmReadTokens`,\n * the same pair the contacts surface uses. Nothing here is a new mechanism;\n * this is leads arriving at the one the rest of the CRM already had.\n *\n * ## The fallback is READ-ONLY, and temporary\n *\n * This repo has run this migration once already — AGL-237 moved datasets,\n * contacts and media to the org, AGL-1040 backfilled, AGL-1050 deleted the\n * fallback — and `orgDataCollectionForHost` carries what it learned:\n *\n * \"a second storage path that can still be WRITTEN is a second boundary to\n * enforce forever, which undoes the premise of scoped sharing: one home\n * per resource plus an explicit scope.\"\n *\n * So the host path is never written here. It is read, once, to carry a\n * not-yet-migrated lead onto the org as a side effect of the next write that\n * touches it ({@link leadForWrite}) — which shrinks what AGL-3276's backfill\n * has left to fold, and means no read can be answered by a stale host row\n * after a write has moved on. AGL-3277 deletes the fallback and the rules\n * block behind it once that backfill reports nothing left to plan.\n */\n\n\n/**\n * The org collection a lead is written to. Always the org — see the\n * read-only note above.\n */\nexport async function orgLeadsForHost(\n hostId: string,\n): Promise<FirebaseFirestore.CollectionReference> {\n return orgDataCollectionForHost(hostId, 'leads')\n}\n\n/**\n * The leads one site may LIST, narrowed by `visibleTo`.\n *\n * The Admin SDK does not evaluate rules, so an unnarrowed read here would\n * serve one agency client's leads on another's site — the same reason\n * `scopedToHost` exists for every other org-owned collection.\n */\nexport async function orgLeadsQueryForHost(hostId: string): Promise<{\n ref: FirebaseFirestore.CollectionReference\n query: FirebaseFirestore.Query\n}> {\n const ref = await orgLeadsForHost(hostId)\n return { ref, query: scopedToHost(ref, hostId) }\n}\n\n/**\n * The tokens a reader holding this group may ask `array-contains-any` for.\n * Capped at 30 by `crmReadTokens`, as the contacts list is.\n */\nexport async function leadReadTokensForHost(\n hostId: string,\n group?: ConsentGroup,\n): Promise<ScopeToken[]> {\n return crmReadTokens(group ?? (await consentGroupForSite(hostId)))\n}\n\n/**\n * The `visibleTo` a capture on this site stamps: `['org']` where the org's\n * CRM default (`crmDefaultScopeOf`) is `'org'` — its default — and the consent\n * group's sites where the org keeps its sites apart.\n *\n * Widened by the capture, never by the lookup — a site that has never\n * captured this person gains nothing by finding them, which is what keeps an\n * agency's clients apart on a record they share. Callers UPDATING an\n * existing lead union these in rather than replacing, exactly as\n * `upsert-contact` does.\n */\nexport async function leadScopeForHost(\n hostId: string,\n org?: Record<string, unknown> | null,\n): Promise<ScopeToken[]> {\n return (await leadScopeFieldsForHost(hostId, org)).visibleTo\n}\n\n/**\n * {@link leadScopeForHost} with the marker a NEW lead carries under the CRM\n * default \"All sites except…\" (AGL-4047), which lets a site added later join\n * it (`crmScopeFields`). An existing lead never takes it from a capture:\n * widening a record that exists is the \"Apply to existing records\" run's.\n */\nexport async function leadScopeFieldsForHost(\n hostId: string,\n org?: Record<string, unknown> | null,\n): Promise<CrmScopeFields> {\n // The org document decides: a capture with none in hand reads it, rather\n // than stamping the site alone for an org whose records belong to every\n // site. An org that cannot be read stamps the site — never everyone.\n const resolved =\n org ?? ((await getOrgForHost(hostId).catch(() => null))?.org as Record<string, unknown> | undefined) ?? null\n const group = await consentGroupForSite(hostId, resolved)\n return crmScopeFields(resolved, group)\n}\n\n/**\n * The lead for an address, wherever it currently lives.\n *\n * ## The lookup is UNSCOPED, and has to be\n *\n * One human who touched two sibling brands is one person. Narrowing this to\n * what the capturing site may already see would let a second submission on a\n * sibling brand mint a SECOND record for the same address — the duplication\n * this migration exists to end, reintroduced one layer up. Recognizing\n * somebody and being allowed to read their row are different acts:\n * this finds the person, {@link leadScopeForHost} decides who may see them.\n *\n * `upsert-contact` states the same rule at its own dedupe lookup, and for the\n * same reason. A caller that wants only what a site may SEE wants\n * {@link orgLeadsQueryForHost}.\n *\n * @returns the org row; else the not-yet-migrated host row; else `null`.\n */\nexport async function readLeadForHost(\n hostId: string,\n key: string,\n): Promise<FirebaseFirestore.DocumentSnapshot | null> {\n const orgRow = await (await orgLeadsForHost(hostId)).doc(key).get()\n return orgRow.exists ? orgRow : null\n}\n\n/**\n * The ref a write should target.\n *\n * This carried a not-yet-backfilled host row onto the org first, and reported\n * whether it had (`carried`). AGL-3276 emptied the host path and AGL-3277\n * removed it, so there is nothing left to carry: the org row is the only row.\n * `carried` stays on the shape, always `false`, because several callers\n * destructure it and a lie is cheaper to read than a signature change that\n * says nothing.\n */\nexport async function leadForWrite(\n hostId: string,\n key: string,\n): Promise<{\n ref: FirebaseFirestore.DocumentReference\n existed: boolean\n carried: boolean\n}> {\n const ref = (await orgLeadsForHost(hostId)).doc(key)\n return { ref, existed: (await ref.get()).exists, carried: false }\n}\n\n\n/**\n * Make a tripped ceiling OBSERVABLE rather than a silent drop — the * standing rule that a control which is not visible in the console does not\n * count as shipped.\n *\n * Two audiences, one call, in exactly `recordAbuseCeilingTrip`'s shape\n * (`libs/plugins/forms/src/lib/server/form-submit.ts`, AGL-1655):\n *\n * - A durable per-month refusal count at\n * `hosts/{id}/counters/{siteMembers|leads}Refused`. Counters are excluded\n * from every client write in `cloud/firebase-firestore.rules` (AGL-1367),\n * so the record cannot be edited away by the site it describes, and host\n * admins can already READ it — which is what lets the inbox console page\n * render it with no rules change.\n * - One notification to the site's managers per CROSSING (AGL-3442): on the\n * first refusal after the site reaches the ceiling, and not again while it\n * stays there. A notification per refused bot request would be the flood\n * again, delivered, and one a month would repeat an alarm about a state a\n * site can sit in for months. {@link rearmVisitorRecordCeilingNotice}\n * re-arms it once the site is seen below the ceiling, so reaching it again\n * is announced again.\n *\n * The counter is month-keyed even though the CEILING is a total, because the\n * two facts are different: the ceiling is \"how many records exist\" and this is\n * \"how many were turned away recently\". The inbox reports the second; the\n * notice announces the first, which is why it follows the crossing and not\n * the month.\n *\n * Best-effort throughout: bookkeeping that failed must never turn a contained\n * refusal into a 500, because a 500 is an invitation to retry.\n */\nexport async function recordVisitorRecordCeilingTrip(options: {\n hostRef: FirebaseFirestore.DocumentReference\n hostId: string\n kind: VisitorRecordKind\n ceiling: number\n monthKey?: string\n}): Promise<void> {\n const { hostRef, hostId, kind, ceiling } = options\n const monthKey = options.monthKey ?? utcMonthKey()\n try {\n const refusedRef = hostRef\n .collection('counters')\n .doc(visitorRecordRefusedCounterId(kind))\n const refusedSnapshot = await refusedRef.get()\n // Announced already for this crossing, by this writer or by the\n // month-scoped one before it — see `visitorRecordCeilingAnnounced`.\n const announced = visitorRecordCeilingAnnounced(refusedSnapshot.data())\n const now = Date.now()\n await refusedRef.set(\n {\n [monthKey]: FieldValue.increment(1),\n // Explicit values only — Firestore rejects `undefined`.\n ceiling,\n lastRefusedAtMs: now,\n // Marked in the same write as the refusal, so the next refusal reads\n // the crossing as announced without a write of its own.\n ...(announced ? {} : { [VISITOR_RECORD_NOTICE_SENT_FIELD]: now }),\n },\n { merge: true },\n )\n if (!announced) {\n const leads = kind === 'leads'\n /*\n * What is refused, said exactly (AGL-3432). A lead door — a form\n * routed to leads, a booking — stores its own record BEFORE it files\n * the lead, so at the ceiling the visitor's submission or booking is\n * still kept and only the new lead is not. A member sign-up is refused\n * whole: no account is created. `{site}` is the site's name, filled by\n * `notifyHostManagers` from the host doc it already reads.\n */\n await notifyHostManagers(hostId, {\n type: 'system.visitorRecordsPaused',\n title: leads\n ? 'Lead capture paused on {site} — platform limit reached'\n : 'Sign-ups paused on {site} — platform limit reached',\n body: leads\n ? `{site} holds ${ceiling.toLocaleString()} leads, the platform ` +\n 'safety limit, so new people are no longer added as leads. What ' +\n 'they send, such as a form submission or a booking, is still ' +\n 'saved; only the new lead is not. This limit is not part of your ' +\n 'plan — every plan includes unlimited leads — and nothing is ' +\n 'charged. Remove some leads, or contact support if this is real ' +\n 'traffic.'\n : `{site} has ${ceiling.toLocaleString()} member accounts, the ` +\n 'platform safety limit, so new sign-ups are refused and no ' +\n 'account is created. This limit is not part of your plan — every ' +\n 'plan includes unlimited member accounts — and nothing is ' +\n 'charged. Remove some members, or contact support if this is ' +\n 'real traffic.',\n link: `/${hostId}/inbox`,\n })\n }\n } catch (error) {\n console.error('visitor record ceiling bookkeeping failed', error)\n }\n}\n\n/**\n * Re-arm the ceiling notice when an accepted record shows the site was below\n * the ceiling (AGL-3442).\n *\n * Called by every writer that judges a new record against the ceiling, with\n * the count it judged. It does nothing unless the record it just accepted took\n * the site's LAST free slot: a site that dropped below the ceiling can reach\n * it again only through that accept, so it is where the re-arm is observed,\n * and every other accept pays nothing for it. That accept reads the refusal\n * counter, and clears the notice marker only when the previous crossing was\n * announced, so a site that never reached the ceiling gains no document.\n *\n * Best-effort and never throws, for the reason the trip's bookkeeping is: the\n * record is already stored, and a failure here only costs a notice.\n */\nexport async function rearmVisitorRecordCeilingNotice(options: {\n hostRef: FirebaseFirestore.DocumentReference\n kind: VisitorRecordKind\n /** The live count the accept was judged against, before its own record. */\n used: number\n ceiling: number\n}): Promise<void> {\n const { hostRef, kind, used, ceiling } = options\n if (!visitorRecordAcceptFillsCeiling(used, ceiling)) return\n try {\n const refusedRef = hostRef\n .collection('counters')\n .doc(visitorRecordRefusedCounterId(kind))\n const refusedSnapshot = await refusedRef.get()\n if (!visitorRecordCeilingAnnounced(refusedSnapshot.data())) return\n await refusedRef.set(\n { [VISITOR_RECORD_NOTICE_SENT_FIELD]: null },\n { merge: true },\n )\n } catch (error) {\n console.error('visitor record ceiling re-arm failed', error)\n }\n}\n\n/** What a caller wants stored on the lead. `createdAt` is stamped here. */\nexport interface HostLeadInput {\n email: string\n /** The name the person typed, when they typed one (AGL-2303). */\n name?: string\n /** `signup`, `booking`, `form:{formId}` — the surface that produced it. */\n source: string\n /**\n * Explicit marketing opt-in, with a consent timestamp — the same shape\n * `upsertHostContact` already carries (AGL-301). Omitted or `false` writes\n * nothing: a lead is a side effect of an action the visitor DID take\n * (sign up, book), which is not by itself consent to be emailed\n * marketing, so this is only set when the caller captured an explicit\n * checkbox.\n */\n marketingConsent?: boolean\n /**\n * The `consentGroupDisclosureKey` the capture surface rendered beside that\n * checkbox (AGL-3320). The grant pools across the site's consent group only\n * when it is the group's current key, and is this site's alone otherwise —\n * the same rule `upsertHostContact` applies.\n */\n disclosedConsentGroup?: string | null\n /**\n * The campaigns the capture SURFACE is filed under (AGL-3458) — a form's\n * `campaignIds`, read by the door off the verified form document. Never the\n * campaign touch, which is where the visitor came from: this is which\n * campaigns the merchant put the form in, and it is true of everybody who\n * fills that form in.\n *\n * Unioned into the lead's own `campaignIds` — the field the enroll route\n * and the bulk bar write — so a campaign the lead joined by hand or by a\n * sequence is kept, and the Leads list's Campaign filter\n * (`scopedCampaignIds`) is restamped from the union in the same write.\n */\n campaignIds?: readonly string[]\n /**\n * A phone the capture learned (AGL-3493), E.164 as the door normalized\n * it. Written only when the lead holds none: a number a rep typed on the\n * lead, or an earlier capture brought, is not replaced by this one.\n */\n phoneFill?: string\n}\n\n/**\n * Record one lead at `hosts/{hostId}/leads/{personKey}`, bounded by\n * `LEADS_MAX_PER_HOST` (AGL-1529).\n *\n * ## One person is one document\n *\n * `docs/specs/reusable-forms.md` §4b. This used to be `tx.create(ref.doc())`\n * — an auto-id per capture event — so one returning customer who signed up\n * and booked twice was three \"leads\". The Members & leads tab presented a\n * list of events as a list of people, and the only thing holding two rows for\n * one person together was string equality on the address at render time.\n *\n * The events are not lost, they are just no longer the record: `sources`\n * carries every surface that produced a capture, `submissionCount` counts\n * them, and `firstSeenAtMs`/`lastSeenAtMs` bracket them. The submissions, the\n * bookings and the member document are still there and still one row each.\n *\n * The id is {@link personKey} — `sha256(normalizeContactEmail(email))`, the\n * SAME derivation a list membership's `memberKey` uses, imported rather than\n * restated. Two specs named this function and the rule both stated is that\n * whichever ships second imports the first's helper: a second copy is how\n * `emailSuppressionKey` and `suppressionId` came to disagree.\n *\n * ## Why every lead writer goes through here\n *\n * There are three lead writes in the repo — the sign-up handler and the two\n * bookings paths — and all three were `hostRef.collection('leads').add(…)`\n * with a `.catch()` on the end. A cap enforced at two of three call sites is\n * not a cap, and the fourth writer somebody adds next month would not have\n * one either. One function is the only shape that survives that.\n *\n * ## The count is evaluated INSIDE the transaction that writes\n *\n * A create-time quota can be laundered by WHEN it is evaluated, not by the\n * counting rule (AGL-2231/2265/2266). Read-then-decide-then-`add()` lets N\n * concurrent visitors each read the same pre-count, each find room, and each\n * land — and nothing re-counts afterwards, so the extra rows are permanent.\n * `Transaction.get(AggregateQuery)` serialises the count against a concurrent\n * create into the same collection: the loser retries, re-reads the higher\n * count, and is refused. The count is of LIVE documents, so triaging leads in\n * the inbox frees the slots.\n *\n * ## Refusing a lead never fails the visitor's action\n *\n * A lead is a SIDE EFFECT — of a sign-up, or of a booking. The visitor did\n * not ask for it and cannot see it, so refusing one must not refuse the thing\n * they did ask for. This returns a boolean and never throws; the trip is\n * recorded and the caller carries on. That is the honest split, and it is why\n * `SITE_MEMBERS_MAX_PER_HOST` (which governs an action a visitor DID take) is\n * enforced with a 429 in the sign-up handler and this is not.\n */\nexport async function addHostLeadOutcome(options: {\n hostRef: FirebaseFirestore.DocumentReference\n hostId: string\n lead: HostLeadInput\n /**\n * The ceiling to compare against. Defaults to `LEADS_MAX_PER_HOST` and is\n * passed by NOTHING in production — it exists so the suite can re-drive the\n * same count against a ceiling one higher and require the write to succeed.\n * A refusal that survives its own ceiling being raised was never that\n * ceiling's refusal, and there is exactly ONE comparison below, so knifing\n * it cannot be absorbed by a fallback branch.\n */\n ceiling?: number\n /**\n * Where this person arrived from, already resolved by the door through the\n * plugin that credits outcomes (`plugin-conversion-credit`), and opaque\n * here.\n *\n * Resolved rather than raw, and passed rather than looked up, because one\n * visitor action reaches several writers: a form submission that creates a\n * submission, a contact AND a lead must pay for the touch lookup once. A\n * door that hands none — every order path, every import — attributes\n * nothing, which is how a lead that no campaign caused stays uncredited.\n */\n touch?: PluginConversionTouch | null\n}): Promise<HostLeadOutcome> {\n const { hostRef, hostId, lead } = options\n const maxPerHost = options.ceiling ?? LEADS_MAX_PER_HOST\n try {\n const leadsRef = await orgLeadsForHost(hostId)\n const firestore = hostRef.firestore\n /*\n * `null` for anything that is not a usable address — a lead captured\n * against a malformed one keeps an auto-id and stays its own row. Keying\n * several unusable addresses under one guessed id would merge two\n * different people, which is worse than two rows for one.\n */\n const key = personKey(lead.email)\n /*\n * A lead the org has not taken over yet is carried across BEFORE the\n * transaction opens (AGL-3275). It has to happen outside: the carry is\n * itself a read-then-write, and a transaction that also counted the\n * collection would be reading a row it was about to create. Two doors\n * carrying the same person in the same second both write the legacy\n * fields under `merge`, so the race is a no-op rather than a conflict.\n */\n const leadRef = key\n ? (await leadForWrite(hostId, key)).ref\n : leadsRef.doc()\n /*\n * The scope this capture stamps, and the group whose terms its consent is\n * recorded under. Both resolved HERE rather than in the transaction body:\n * a contended transaction re-runs that body, and neither of these can\n * change between attempts, so resolving them inside would pay for the org\n * read again on every retry.\n */\n const { visibleTo: scope, ...marker } = await leadScopeFieldsForHost(hostId)\n const group = await consentGroupForSite(hostId)\n const now = Date.now()\n const seen = {\n // `arrayUnion`, so a person who books twice has `['booking']` and one\n // who signed up and then submitted a form has both. Bounded by the\n // number of surfaces, not by the number of captures.\n sources: FieldValue.arrayUnion(lead.source),\n lastSeenAtMs: now,\n submissionCount: FieldValue.increment(1),\n ...(lead.name ? { name: lead.name } : {}),\n }\n let created = false\n let sourceAdded = false\n let predicted = false\n // The count a new person was judged against, for the notice re-arm.\n let usedBeforeCreate: number | null = null\n const refused = await firestore.runTransaction(async (tx) => {\n // Reset per attempt: a contended transaction re-runs its body, and a\n // flag left standing from an aborted attempt would credit a campaign\n // with a person who turned out to exist already.\n created = false\n sourceAdded = false\n usedBeforeCreate = null\n // ALL READS BEFORE THE WRITE, which Firestore requires.\n const existing = await tx.get(leadRef)\n // Whether the lead already reads \"Would bounce\", for the check below.\n predicted = (existing.data() ?? {})['emailStatus'] === 'undeliverable'\n /*\n * ⛔ THE CEILING GATES A NEW PERSON, NEVER AN EXISTING ONE.\n *\n * A returning visitor's capture is an UPDATE — it does not grow the\n * collection, so refusing it buys no capacity and costs the customer\n * the source and the timestamp they would have learned. That is the\n * enforcement-at-use shape the capacity rule exists to forbid: a limit\n * must refuse the addition, never a person already recorded or the\n * data attached to them.\n *\n * It also means the count is only paid on a genuinely new person,\n * which is the case that can move it.\n */\n if (!existing.exists) {\n /*\n * COUNTED OVER WHAT THIS SITE MAY SEE, not over the org (AGL-3275).\n *\n * The collection is org-wide now, and `LEADS_MAX_PER_HOST` is a\n * per-SITE ceiling. An unfiltered count would charge every brand in\n * an agency's account for every other brand's leads, and the first\n * client to fill its allowance would refuse captures on sites that\n * had taken none. `scopedToHost` is the same narrowing every other\n * org-owned read uses, so a single-site org counts exactly what it\n * counted before this moved.\n *\n * A lead shared by two brands in one consent group is counted by\n * both, which is the honest answer: each of them holds it.\n */\n const used = (\n await tx.get(scopedToHost(leadsRef, hostId).count())\n ).data().count\n if (checkVisitorRecordCeiling(used, maxPerHost).exceeded) return true\n usedBeforeCreate = used\n }\n /*\n * Consent is carried forward and never cleared.\n *\n * A basis is written only when this capture carried an explicit\n * opt-in, so a later booking by someone who did not tick the box\n * leaves an earlier grant standing — absent-or-granted, the shape\n * every other writer uses. The TIMESTAMP is carried over rather than\n * restamped, for the reason given at the read below.\n */\n /*\n * The EARLIEST grant is the one that happened, so a later capture\n * carrying the same checkbox keeps the original date rather than\n * restamping when this person opted in. Read back through the shared\n * reader so \"already consented\" means the same thing here as it does\n * at send time.\n */\n /*\n * THE SITE'S REAL GROUP, because the silo that justified a group of one\n * is gone (AGL-3275).\n *\n * This read `soloConsentGroup(hostId)` for as long as a lead lived at\n * `hosts/{hostId}/leads`, and the reason was the path: private by\n * construction, so pooling a lead's basis would have recorded a\n * disclosure that reached nothing, while the contact written by the\n * same capture door was org-shared and pooled.\n *\n * A lead is now org-shared on exactly the terms the contact is, so the\n * premise is false and keeping the group of one would leave a\n * multi-brand org holding a lead its sibling brand can SEE but may not\n * MAIL — a narrower basis than the one `consentGroupDisclosure` named\n * beside the checkbox this person ticked. Pooling here records what\n * they were actually told, and only that: the grant reaches the group\n * when the capture surface sent back the group's current disclosure\n * key (AGL-3320), and this site alone otherwise. An undeclared group is\n * still a group of one, so an agency is unchanged and configures\n * nothing.\n *\n * Resolved above the transaction — see `group`'s declaration.\n */\n const prior = readMarketingBasis(existing.data() ?? null, group)\n const consentAtMs =\n prior.basis === 'granted' && prior.basisAtMs !== null\n ? prior.basisAtMs\n : now\n created = !existing.exists\n /*\n * Whether this capture puts its surface on the person for the FIRST\n * time: a new lead, or one first met through another door. A form\n * counts its leads by this (AGL-3330) — the people it filed, which is\n * what a recount of `sources` finds — so a returning visitor's second\n * submission moves no form's lead count.\n */\n const storedSources = (existing.data() ?? {})['sources']\n sourceAdded =\n created || !(Array.isArray(storedSources) && storedSources.includes(lead.source))\n /*\n * THE FIELDS THE LEADS LIST QUERIES (AGL-3321), from the lead as it\n * will stand: what the transaction read, the address and name this\n * capture brings and the scope it widens. A new lead is written\n * `status: 'new'`, so the Open view's `status in [new, working]`\n * finds a lead nobody has touched — an absent field matches no query.\n */\n const stored = existing.data() ?? {}\n const phoneFill =\n lead.phoneFill && !String(stored['phone'] ?? '').trim()\n ? { phone: lead.phoneFill }\n : {}\n const storedScope = Array.isArray(stored['visibleTo']) ? (stored['visibleTo'] as unknown[]) : []\n /*\n * THE CAMPAIGNS, unioned (AGL-3458). Computed from what the transaction\n * read rather than written as an `arrayUnion`, so the Campaign filter's\n * scoped keys below are derived from the same list the write stores,\n * and the union is held to the membership cap every reader applies.\n * Written only when the capture names one, so a door with no campaign\n * never rewrites the field a person or a sequence filled.\n */\n // The field a lead holds its campaigns in, at the top of its document.\n const campaignsField = lead.campaignIds?.length ? containerMembershipField('campaign') : null\n const campaigns = campaignsField\n ? normalizeContainerIds([\n ...normalizeContainerIds(stored[campaignsField]),\n ...(lead.campaignIds ?? []),\n ])\n : null\n /*\n * A lead that keeps a first or last name keeps the name they make\n * (AGL-3513): a capture's typed name does not replace it.\n */\n const composedName = composeContactName(stored['firstName'], stored['lastName'])\n const name = composedName || lead.name\n const listFields = crmLeadListFields({\n ...stored,\n email: lead.email,\n ...(name ? { name } : {}),\n visibleTo: [...new Set([...storedScope, ...scope])],\n ...(campaignsField && campaigns ? { [campaignsField]: campaigns } : {}),\n })\n tx.set(\n leadRef,\n {\n email: lead.email,\n ...seen,\n ...(composedName ? { name: composedName } : {}),\n ...phoneFill,\n ...listFields,\n ...(campaignsField && campaigns ? { [campaignsField]: campaigns } : {}),\n /*\n * WIDENED BY THE CAPTURE, NEVER BY THE LOOKUP (AGL-3275).\n *\n * `arrayUnion` rather than a replace, exactly as `upsert-contact`\n * stamps a contact: this site just collected this person, so it may\n * see the row. A site that merely FOUND them — the unscoped dedupe\n * lookup in `readLeadForHost` — gains nothing, which is what keeps\n * an agency's clients apart on a record they share.\n */\n visibleTo: FieldValue.arrayUnion(...scope),\n /*\n * EVERY SITE THAT CAPTURED THIS PERSON, not just the first\n * (AGL-3275).\n *\n * This was written once, on create, and that was sound while the\n * collection sat under one host and could hold only that host's\n * name. On the org the row is shared, so a sibling brand capturing\n * a person the first brand already holds has to be recorded here or\n * the \"Known by\" answer silently omits it — the same `arrayUnion`\n * the contact door has always used for this field, now that a lead\n * has the same question to answer.\n */\n [CAPTURED_BY_HOST_FIELD]: FieldValue.arrayUnion(hostId),\n ...(existing.exists\n ? {}\n : {\n firstSeenAtMs: now,\n createdAt: FieldValue.serverTimestamp(),\n // Under \"All sites except…\", the marker a site added later\n // joins by: a new lead's sites are the default's (AGL-4047).\n ...marker,\n }),\n /*\n * The basis is recorded under the GROUP, keyed by its host, because\n * {@link readMarketingBasis} is one function over four silos and a\n * silo whose basis lived somewhere else would need the reader to\n * know which collection it was handed. A reader that has to be told\n * the shape is a reader that can be told the wrong one.\n */\n ...(lead.marketingConsent\n ? marketingConsentFieldsForGroup(\n consentGroupForGrant(group, lead.disclosedConsentGroup),\n consentAtMs,\n )\n : {}),\n },\n { merge: true },\n )\n return false\n })\n if (refused) {\n await recordVisitorRecordCeilingTrip({\n hostRef,\n hostId,\n kind: 'leads',\n ceiling: maxPerHost,\n })\n return NOT_STORED\n }\n if (created && usedBeforeCreate !== null) {\n await rearmVisitorRecordCeilingNotice({\n hostRef,\n kind: 'leads',\n used: usedBeforeCreate,\n ceiling: maxPerHost,\n })\n }\n /*\n * ATTRIBUTED ON CREATION ONLY.\n *\n * A returning visitor's capture is an update — the campaign did not\n * produce a lead, it produced another visit by a person the site already\n * held — and crediting it would let whichever campaign ran most recently\n * re-earn every lead on the list. `created` is set inside the transaction\n * that decides it, so the attribution and the write agree about whether\n * this person is new.\n *\n * Awaited rather than fired off: `addHostLead` already returns only after\n * its own write, and a caller that `void`s it (every one of them) is\n * unaffected. Never throws, so a failure here cannot cost the lead.\n */\n /*\n * THE ADDRESS'S DOMAIN, checked after the response (AGL-3328): a lead\n * whose domain takes no mail reads \"Would bounce\". Queued, never\n * awaited — the write above is the capture, and this costs it nothing.\n */\n scheduleCapturedEmailCheck({\n orgId: leadsRef.parent?.id ?? null,\n hostId,\n email: lead.email,\n predicted,\n })\n if (created && options.touch) {\n await creditConversion({\n hostId,\n kind: 'lead',\n refId: leadRef.id,\n touch: options.touch,\n convertedAtMs: now,\n })\n }\n return { stored: true, created, sourceAdded }\n } catch (error) {\n // Same posture the three original call sites had (`.catch(() => undefined)`\n // / `.catch(console.error)`): a lead that failed to store must not fail\n // the sign-up or the booking that produced it.\n console.error('lead write failed', error)\n return NOT_STORED\n }\n}\n\n/** What {@link addHostLeadOutcome} did with one capture. */\nexport interface HostLeadOutcome {\n /** Whether the lead was written — false when refused or failed. */\n stored: boolean\n /** Whether it was a new person. */\n created: boolean\n /** Whether this capture's `source` was new on the lead — see the write. */\n sourceAdded: boolean\n}\n\nconst NOT_STORED: HostLeadOutcome = { stored: false, created: false, sourceAdded: false }\n\n/**\n * {@link addHostLeadOutcome}, answering only whether the lead was stored —\n * the question every door but a form's asks.\n */\nexport async function addHostLead(\n options: Parameters<typeof addHostLeadOutcome>[0],\n): Promise<boolean> {\n return (await addHostLeadOutcome(options)).stored\n}\n"],"names":["CAPTURED_BY_HOST_FIELD","checkVisitorRecordCeiling","containerMembershipField","LEADS_MAX_PER_HOST","marketingConsentFieldsForGroup","normalizeContainerIds","personKey","readMarketingBasis","utcMonthKey","VISITOR_RECORD_NOTICE_SENT_FIELD","visitorRecordAcceptFillsCeiling","visitorRecordCeilingAnnounced","visitorRecordRefusedCounterId","FieldValue","creditConversion","notifyHostManagers","scheduleCapturedEmailCheck","firebaseAdmin","consentGroupForSite","getOrgForHost","orgDataCollectionForHost","scopedToHost","composeContactName","crmLeadListFields","crmReadTokens","crmScopeFields","consentGroupForGrant","firestore","app","orgLeadsForHost","hostId","orgLeadsQueryForHost","ref","query","leadReadTokensForHost","group","leadScopeForHost","org","leadScopeFieldsForHost","visibleTo","resolved","catch","readLeadForHost","key","orgRow","doc","get","exists","leadForWrite","existed","carried","recordVisitorRecordCeilingTrip","options","hostRef","kind","ceiling","monthKey","refusedRef","collection","refusedSnapshot","announced","data","now","Date","set","increment","lastRefusedAtMs","merge","leads","type","title","body","toLocaleString","link","error","console","rearmVisitorRecordCeilingNotice","used","addHostLeadOutcome","lead","maxPerHost","leadsRef","email","leadRef","scope","marker","seen","sources","arrayUnion","source","lastSeenAtMs","submissionCount","name","created","sourceAdded","predicted","usedBeforeCreate","refused","runTransaction","tx","existing","stored","count","exceeded","prior","consentAtMs","basis","basisAtMs","storedSources","Array","isArray","includes","phoneFill","String","trim","phone","storedScope","campaignsField","campaignIds","length","campaigns","composedName","listFields","Set","firstSeenAtMs","createdAt","serverTimestamp","marketingConsent","disclosedConsentGroup","NOT_STORED","orgId","parent","id","touch","refId","convertedAtMs","addHostLead"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED,SACEA,sBAAsB,EACtBC,yBAAyB,EACzBC,wBAAwB,EACxBC,kBAAkB,EAClBC,8BAA8B,EAC9BC,qBAAqB,EACrBC,SAAS,EACTC,kBAAkB,EAClBC,WAAW,EACXC,gCAAgC,EAChCC,+BAA+B,EAC/BC,6BAA6B,EAC7BC,6BAA6B,QAExB,sBAAqB;AAC5B,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,gBAAgB,QAEX,uDAAsD;AAC7D,SAASC,kBAAkB,QAAQ,qBAAiB;AACpD,SAASC,0BAA0B,QAAQ,2BAAuB;AAClE,OAAOC,mBAAmB,sBAAkB;AAC5C,SACEC,mBAAmB,EACnBC,aAAa,EACbC,wBAAwB,EAExBC,YAAY,QACP,qBAAiB;AACxB,SACEC,kBAAkB,EAClBC,iBAAiB,EACjBC,aAAa,EACbC,cAAc,QACT,sBAAqB;AAE5B,8EAA8E;AAC9E,8EAA8E;AAC9E,SAASC,oBAAoB,QAAQ,wCAAuC;AAE5E,MAAMC,YAAY,IAAMV,cAAcW,GAAG,GAAGD,SAAS;AAErD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4CC,GAGD;;;CAGC,GACD,OAAO,eAAeE,gBACpBC,MAAc;IAEd,OAAOV,yBAAyBU,QAAQ;AAC1C;AAEA;;;;;;CAMC,GACD,OAAO,eAAeC,qBAAqBD,MAAc;IAIvD,MAAME,MAAM,MAAMH,gBAAgBC;IAClC,OAAO;QAAEE;QAAKC,OAAOZ,aAAaW,KAAKF;IAAQ;AACjD;AAEA;;;CAGC,GACD,OAAO,eAAeI,sBACpBJ,MAAc,EACd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AO,AAAC,CAAA,MAAM0B,mBAAmB1B,QAAO,EAAGiD,MAAM;AACnD"}
|
|
@@ -252,21 +252,6 @@ export declare function mediaRestoreRefusal(options: {
|
|
|
252
252
|
status: number;
|
|
253
253
|
message: string;
|
|
254
254
|
} | null;
|
|
255
|
-
/**
|
|
256
|
-
* Put a deleted asset back: object, variants, document and counters.
|
|
257
|
-
*
|
|
258
|
-
* Order is the same argument as the delete, run backwards. Bytes first, then
|
|
259
|
-
* the commit — so the only partial state this can leave is an object restored
|
|
260
|
-
* with no document, which the tombstone (still present, because the commit is
|
|
261
|
-
* what consumes it) makes a retry away from finished. The reverse order would
|
|
262
|
-
* publish a document whose bytes may never arrive.
|
|
263
|
-
*
|
|
264
|
-
* The commit itself carries the document write, the tombstone delete and both
|
|
265
|
-
* counter increments together, and it re-reads the tombstone inside the
|
|
266
|
-
* transaction. That re-read is what makes a double-click harmless: the second
|
|
267
|
-
* transaction finds no tombstone, commits nothing, and the caller is told the
|
|
268
|
-
* file is already back rather than being charged for it twice.
|
|
269
|
-
*/
|
|
270
255
|
export declare function restoreMediaFromTombstone(options: {
|
|
271
256
|
scopeRef: FirebaseFirestore.DocumentReference;
|
|
272
257
|
bucket: TombstoneStorageBucket;
|
|
@@ -17,8 +17,10 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
17
17
|
*/ import { FieldValue, Timestamp } from "firebase-admin/firestore";
|
|
18
18
|
import { checkQuota } from "@aglyn/aglyn/server";
|
|
19
19
|
import { mediaFilterKeys } from "@aglyn/aglyn/app-utils/media-metadata";
|
|
20
|
+
import { reconcileAllExcept } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
20
21
|
import { removeMediaDeliveryCopies, withoutMediaDeliveryCopies } from "./media-delivery.js";
|
|
21
22
|
import { mediaDerivedObjectPaths } from "./media-variants.js";
|
|
23
|
+
import { orgHostIdsFromDoc } from "./scope-sharing-sweep.js";
|
|
22
24
|
/**
|
|
23
25
|
* What a DAM delete has to leave behind for an undo to be possible at all
|
|
24
26
|
* (AGL-1467).
|
|
@@ -308,7 +310,31 @@ import { mediaDerivedObjectPaths } from "./media-variants.js";
|
|
|
308
310
|
* transaction. That re-read is what makes a double-click harmless: the second
|
|
309
311
|
* transaction finds no tombstone, commits nothing, and the caller is told the
|
|
310
312
|
* file is already back rather than being charged for it twice.
|
|
311
|
-
*/
|
|
313
|
+
*/ /**
|
|
314
|
+
* The scope a restored file of the workspace library is written with, when it
|
|
315
|
+
* carries the marker of "all sites except some" (AGL-4047): `visibleTo` and the
|
|
316
|
+
* marker as `reconcileAllExcept` answers them for the workspace's sites today.
|
|
317
|
+
* Empty for anything else: an unmarked file, a site's own library, or a marker
|
|
318
|
+
* the helper can't act on (left as it was, for the weekly drift report).
|
|
319
|
+
*
|
|
320
|
+
* Spread over the whole document, which a `set` with no merge writes, so a
|
|
321
|
+
* marker that drops to All sites is taken off by deleting the keys from the
|
|
322
|
+
* copy, never by storing a null.
|
|
323
|
+
*/ async function restoredScopeFields(transaction, scopeRef, media) {
|
|
324
|
+
if (media['scopeMode'] === undefined || scopeRef.parent.id !== 'orgs') return {};
|
|
325
|
+
const org = await transaction.get(scopeRef);
|
|
326
|
+
const answer = reconcileAllExcept(media, orgHostIdsFromDoc(org.data()));
|
|
327
|
+
if (!answer.fields) return {};
|
|
328
|
+
if (!answer.fields.scopeMode) {
|
|
329
|
+
delete media['scopeMode'];
|
|
330
|
+
delete media['scopeExcept'];
|
|
331
|
+
return {
|
|
332
|
+
visibleTo: answer.fields.visibleTo
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
return _extends({}, answer.fields);
|
|
336
|
+
}
|
|
337
|
+
export async function restoreMediaFromTombstone(options) {
|
|
312
338
|
var _options_nowMs, _counter_get;
|
|
313
339
|
const { scopeRef, bucket, mediaId, billing } = options;
|
|
314
340
|
const nowMs = (_options_nowMs = options.nowMs) != null ? _options_nowMs : Date.now();
|
|
@@ -406,7 +432,13 @@ import { mediaDerivedObjectPaths } from "./media-variants.js";
|
|
|
406
432
|
// With the library's filter keys re-derived, so a file deleted before
|
|
407
433
|
// they existed comes back findable by them (AGL-3327).
|
|
408
434
|
const media = withoutMediaDeliveryCopies(record.media);
|
|
409
|
-
|
|
435
|
+
// Shared with all sites except some (AGL-4047): the sites it reaches are
|
|
436
|
+
// a list the sweep keeps up as sites come and go, and the sweep never saw
|
|
437
|
+
// this file while it was deleted. So it comes back reaching the sites
|
|
438
|
+
// the workspace has NOW, read in this transaction, as the sweep would
|
|
439
|
+
// have left it. Any other file comes back as it was.
|
|
440
|
+
const scope = await restoredScopeFields(transaction, scopeRef, media);
|
|
441
|
+
transaction.set(mediaRef, _extends({}, media, scope, mediaFilterKeys(media), {
|
|
410
442
|
folderId: (_media_folderId = media.folderId) != null ? _media_folderId : null
|
|
411
443
|
}));
|
|
412
444
|
transaction.delete(tombstoneRef);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/media-tombstone.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 { FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport { checkQuota } from '@aglyn/aglyn/server'\nimport { mediaFilterKeys } from '@aglyn/aglyn/app-utils/media-metadata'\nimport {\n removeMediaDeliveryCopies,\n withoutMediaDeliveryCopies,\n} from './media-delivery'\nimport { mediaDerivedObjectPaths } from './media-variants'\n\n/**\n * What a DAM delete has to leave behind for an undo to be possible at all\n * (AGL-1467).\n *\n * ## The gap this closes\n *\n * The bucket has soft-delete on with a **seven-day** retention, so the bytes\n * of a deleted asset really are still there. That was only ever half of an\n * undo, and AGL-1461 shipped honest copy rather than a button because of the\n * other half: `/api/media/upload`'s DELETE branch hard-deleted the Firestore\n * document. After it ran, nothing in the product knew the asset's id, file\n * name, folder, tags, alt text, description, custom metadata, `visibleTo`\n * scope tokens, `cdnPath` or `variants` — and `File.restore()` needs a\n * **generation number** that nobody had captured. Surviving bytes with no\n * address are not a recovery story. On 2026-08-13 two files deleted in error\n * came back only because an unrelated analysis document happened to have\n * recorded their ids; a customer has no such document.\n *\n * A tombstone is the three facts that make the bytes addressable again:\n *\n * 1. the media document verbatim, as it was at the moment of the delete;\n * 2. the **generation** of the storage object and of every CDN variant,\n * read BEFORE the delete — afterwards there is no live object to ask;\n * 3. `sizeBytes`, so the counter decrement can be reversed by exactly the\n * amount it moved rather than by a recomputation that can drift.\n *\n * ## Where it lives, and why that is the whole erasure answer\n *\n * `{hosts|orgs}/{scopeId}/mediaTombstones/{mediaId}` — a subcollection of the\n * scope that owned the asset, never a top-level collection keyed by media id.\n *\n * This is the load-bearing choice. `eraseHost` ends in\n * `recursiveDelete(hostRef)` and `eraseOrg` ends in `recursiveDelete(orgRef)`,\n * and a path-scoped cascade takes every subcollection under the path with it.\n * Put the tombstones there and an erasure removes them with no new code — put\n * them in a top-level `mediaTombstones/{id}` with an `orgId` field and they\n * become exactly the shape AGL-1444 and AGL-1448 had to go back and wire by\n * hand: a collection the cascade is structurally blind to, holding a verbatim\n * copy of customer content, surviving the request that promised it was gone.\n * A tombstone is customer data. It has to die with the customer.\n *\n * (The property is asserted rather than assumed —\n * `erase-media-tombstones.emulator.spec.ts` erases a host and an org that each\n * hold one and looks for the survivor.)\n *\n * ## Retention: the same seven days as the bytes, and not a day more\n *\n * `expiresAt` is stamped at `MEDIA_TOMBSTONE_RETENTION_MS` past the delete,\n * which is the bucket's soft-delete window exactly. Both other numbers are\n * wrong for the same reason from opposite directions: a shorter tombstone\n * strands recoverable bytes with no address, which is today's defect made\n * smaller, and a longer one can only ever produce a failed restore while\n * holding a copy of a customer's asset for no reachable purpose. AGL-1443 is\n * open on precisely that — a durable copy of customer data whose retention\n * nobody chose — and this must not become a second instance of it.\n *\n * The field is enforced two ways, because neither alone is enough. A Firestore\n * TTL policy on `mediaTombstones.expiresAt` reaps them (see\n * `docs/FIRESTORE_MANUAL_CONFIG.md`), and TTL deletion is explicitly not\n * prompt — so `restoreMediaFromTombstone` treats an expired tombstone as\n * absent and deletes it on sight rather than trusting the sweeper.\n */\n\n/** The subcollection, under the scope that owned the asset. */\nexport const MEDIA_TOMBSTONE_COLLECTION = 'mediaTombstones'\n\n/**\n * How long a tombstone lives: the bucket's soft-delete retention, exactly.\n *\n * Changing this without changing the bucket policy breaks the invariant the\n * whole module rests on — see the header.\n */\nexport const MEDIA_TOMBSTONE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000\n\n/** Days, for the copy that has to name the window to a person. */\nexport const MEDIA_TOMBSTONE_RETENTION_DAYS = Math.round(\n MEDIA_TOMBSTONE_RETENTION_MS / (24 * 60 * 60 * 1000),\n)\n\n/**\n * One deleted object and the generation that addresses it.\n *\n * `generation` is nullable on purpose: reading it is a Storage round-trip that\n * can fail, and an asset whose object was ALREADY missing (replaced, swept,\n * never written) must still produce a tombstone — the document half of the\n * restore is worth having on its own. A null generation means \"nothing to\n * restore here\", not \"restore failed\".\n */\nexport interface MediaObjectGeneration {\n path: string\n generation: string | null\n}\n\n/** The stored tombstone document. */\nexport interface MediaTombstoneDoc {\n /** The media document verbatim, exactly as the delete found it. */\n media: Record<string, unknown>\n /** Primary object first, then every CDN variant. */\n objects: MediaObjectGeneration[]\n /** The counter decrement to reverse, taken from the document. */\n sizeBytes: number\n fileName: string\n deletedBy: string\n deletedAt: Timestamp | number\n /**\n * Hard bound — see the header. Written as a **Timestamp**, which the TTL\n * policy requires (a number field cannot carry one, which is why\n * `bookings.expiresAtMs` is documented as not a TTL target). Read through\n * `isMediaTombstoneExpired`, which takes either form so a hand-written\n * fixture and the real write are both legible.\n */\n expiresAt: Timestamp | number\n}\n\n/**\n * The slice of `File` this module needs; the real one satisfies it.\n *\n * `restore` takes a NUMBER because the SDK's `RestoreOptions` does, while the\n * tombstone stores the generation as a string — a GCS generation is a\n * microsecond timestamp (~1.7e15), comfortably inside a double, but a string\n * is what survives JSON, a Firestore round-trip and a log line without anyone\n * having to reason about that. The conversion happens once, at the call.\n */\nexport interface TombstoneStorageFile {\n getMetadata(): Promise<any>\n delete(): Promise<any>\n exists(): Promise<any>\n restore(options: { generation: number }): Promise<any>\n}\n\n/** The slice of `Bucket` this module needs. */\nexport interface TombstoneStorageBucket {\n file(path: string): TombstoneStorageFile\n}\n\n/** When a tombstone written now stops being useful. */\nexport function mediaTombstoneExpiry(deletedAtMs: number): number {\n return deletedAtMs + MEDIA_TOMBSTONE_RETENTION_MS\n}\n\n/** Milliseconds out of a Firestore Timestamp or a plain number. */\nfunction toMillis(value: unknown): number {\n const timestamp = value as { toMillis?: () => number }\n if (typeof timestamp?.toMillis === 'function') return timestamp.toMillis()\n return Number(value ?? 0)\n}\n\n/**\n * Whether the bytes this tombstone addresses are past the bucket's window.\n *\n * Missing or unreadable reads as EXPIRED, which is the safe direction: the\n * failure mode of a false positive is a refusal with a clear message, and the\n * failure mode of a false negative is a restore that half-succeeds against\n * bytes the bucket has already reaped.\n */\nexport function isMediaTombstoneExpired(\n tombstone: Pick<MediaTombstoneDoc, 'expiresAt'>,\n nowMs: number,\n): boolean {\n return !(toMillis(tombstone.expiresAt) > nowMs)\n}\n\n/**\n * Read the generation of each object, best-effort (AGL-1467).\n *\n * Must run BEFORE the delete. Once the object is soft-deleted there is no live\n * generation to read, and the number is the only handle `restore()` takes —\n * this is the single fact whose absence made undo impossible rather than\n * merely unbuilt.\n *\n * A failure here degrades the tombstone to its document half rather than\n * failing the delete: an author who asked for a file to go must not be told\n * \"no\" because a metadata read timed out.\n */\nexport async function captureObjectGenerations(\n bucket: TombstoneStorageBucket,\n paths: readonly string[],\n): Promise<MediaObjectGeneration[]> {\n return Promise.all(\n paths.map(async (path) => {\n try {\n const response = await bucket.file(path).getMetadata()\n const metadata = Array.isArray(response) ? response[0] : response\n const generation = metadata?.generation\n return {\n path,\n generation:\n generation === undefined || generation === null\n ? null\n : String(generation),\n }\n } catch {\n return { path, generation: null }\n }\n }),\n )\n}\n\n/**\n * Removes the delivery provider's copies of a deleted asset (AGL-2824).\n *\n * Unlike the bucket's objects they are not kept for a restore — a restore\n * copies the video again — and no tombstone records them. The library is\n * read off the scope reference (`hosts/{id}` or `orgs/{id}`). Nothing runs\n * when no provider is configured to store, and a failure is logged rather\n * than answered, like the object deletes beside it.\n */\nasync function removeDeliveryCopies(\n scopeRef: FirebaseFirestore.DocumentReference,\n mediaId: string,\n): Promise<void> {\n const collection = scopeRef.parent?.id\n if (collection !== 'hosts' && collection !== 'orgs') return\n await removeMediaDeliveryCopies({\n asset: { collection, scopeId: scopeRef.id, mediaId },\n })\n}\n\nexport interface DeleteMediaResult {\n /** False when there was no document to delete (already gone). */\n deleted: boolean\n /** Present when a tombstone was written — the id is the media id. */\n tombstone?: { mediaId: string; expiresAt: number; fileName: string }\n}\n\n/**\n * Delete a media document and leave a tombstone behind, in one commit.\n *\n * **The invariant: the media document is never destroyed except in the same\n * transaction that writes its tombstone and moves the counter.** All three\n * belong to one commit, so there is no interleaving in which the document is\n * gone and the record of it is not — which is the state the product was\n * permanently in before this issue.\n *\n * The object delete happens AFTER that commit, deliberately, and the ordering\n * is a choice between two partial failures:\n *\n * - object first: a failed commit leaves a live document pointing at bytes\n * that are already soft-deleted — a broken asset in the library that\n * nothing detects;\n * - commit first: a failed object delete leaves a tombstone whose object is\n * still live, which `restoreMediaFromTombstone` handles by skipping the\n * restore for an object that is already there.\n *\n * The second is recoverable by the code in this file. The first is not\n * recoverable by anything.\n */\nexport async function deleteMediaWithTombstone(options: {\n scopeRef: FirebaseFirestore.DocumentReference\n bucket: TombstoneStorageBucket\n mediaId: string\n /** Path of the primary object, resolved by the caller (legacy fallback). */\n objectPath: string\n /** Who asked — an erasure record with no actor is half a record. */\n uid: string\n nowMs?: number\n}): Promise<DeleteMediaResult> {\n const { scopeRef, bucket, mediaId, objectPath, uid } = options\n const nowMs = options.nowMs ?? Date.now()\n const mediaRef = scopeRef.collection('media').doc(mediaId)\n const snapshot = await mediaRef.get()\n if (!snapshot.exists) {\n // No document, so nothing to record and nothing to restore to. The object\n // sweep below still runs: an orphan object is exactly what this branch is\n // for, and it predates the tombstone.\n await bucket.file(objectPath).delete().catch(() => undefined)\n await removeDeliveryCopies(scopeRef, mediaId)\n return { deleted: false }\n }\n\n // Every derived object, not only the variants (AGL-3486): a display copy,\n // a film's poster and its renditions are kept and restored with the rest.\n const variantPaths = mediaDerivedObjectPaths(objectPath, snapshot)\n // BEFORE the delete — the whole point. See `captureObjectGenerations`.\n const objects = await captureObjectGenerations(bucket, [\n objectPath,\n ...variantPaths,\n ])\n\n const sizeBytes = Number(snapshot.get('sizeBytes') ?? 0)\n const fileName = String(snapshot.get('fileName') ?? mediaId)\n const expiresAt = mediaTombstoneExpiry(nowMs)\n const tombstoneRef = scopeRef\n .collection(MEDIA_TOMBSTONE_COLLECTION)\n .doc(mediaId)\n const counterRef = scopeRef.collection('counters').doc('media')\n\n const committed = await scopeRef.firestore.runTransaction(\n async (transaction) => {\n const fresh = await transaction.get(mediaRef)\n // Someone else deleted it between the read above and here. Their commit\n // wrote the tombstone; ours must not write a second one over it.\n if (!fresh.exists) return false\n const data = (fresh.data() ?? {}) as Record<string, unknown>\n const tombstone: MediaTombstoneDoc = {\n media: data,\n objects,\n sizeBytes: Number(data['sizeBytes'] ?? sizeBytes) || 0,\n fileName: String(data['fileName'] ?? fileName),\n deletedBy: uid,\n deletedAt: Timestamp.fromMillis(nowMs),\n // Timestamp, not a number: the TTL policy on\n // `mediaTombstones.expiresAt` cannot key on anything else.\n expiresAt: Timestamp.fromMillis(expiresAt),\n }\n transaction.set(tombstoneRef, tombstone)\n transaction.delete(mediaRef)\n transaction.set(\n counterRef,\n {\n bytes: FieldValue.increment(-tombstone.sizeBytes),\n count: FieldValue.increment(-1),\n },\n { merge: true },\n )\n return true\n },\n )\n\n // Object and variants last, best-effort, exactly as before — the bucket\n // keeps them for the retention window either way.\n await bucket.file(objectPath).delete().catch(() => undefined)\n await Promise.all(\n variantPaths.map((path) =>\n bucket.file(path).delete().catch(() => undefined),\n ),\n )\n await removeDeliveryCopies(scopeRef, mediaId)\n\n if (!committed) return { deleted: false }\n return { deleted: true, tombstone: { mediaId, expiresAt, fileName } }\n}\n\nexport interface RestoreMediaResult {\n ok: boolean\n /** HTTP status the route should answer with. */\n status: number\n /** A real sentence for a person — never a bare code. */\n message: string\n fileName?: string\n}\n\n/**\n * Why a restore cannot proceed, decided without touching Storage (AGL-1467).\n *\n * Pure, because these are the answers a person actually sees and the two\n * interesting ones are cheap to get wrong: an expired tombstone must fail\n * CLEANLY rather than half-succeed against bytes the bucket has already\n * reaped, and a restore that would breach the plan must say so rather than\n * push the counter past the limit in silence.\n *\n * ## The quota call\n *\n * A restore re-adds real bytes, so it is gated exactly like an upload —\n * `storagePerHostMb`, same off-by-one — and REFUSED when it would breach the\n * plan. Waiving it would let delete-then-restore launder an over-quota\n * library, which is the AGL-1471/AGL-1279 shape (a limit evaluated at a moment\n * the caller controls). Refusing is safe precisely because the tombstone\n * outlives the refusal: the asset is still restorable for the rest of the\n * window once space is freed, which is what makes \"no, and here is why\"\n * an honest answer rather than a loss.\n *\n * Note what is NOT metered: the soft-deleted bytes themselves. They sit in the\n * bucket for seven days at Aglyn's cost, and counting them would mean deleting\n * a file did not free space until a week later — which breaks the one action\n * an author takes when they hit the wall. The window is the price of offering\n * undo, not an allocation to bill back.\n */\nexport function mediaRestoreRefusal(options: {\n tombstone: Pick<MediaTombstoneDoc, 'expiresAt' | 'sizeBytes' | 'fileName'>\n nowMs: number\n /** Counter bytes as they stand now, with the asset already removed. */\n usedBytes: number\n billing: Record<string, unknown> | undefined\n}): { status: number; message: string } | null {\n const { tombstone, nowMs, usedBytes, billing } = options\n if (isMediaTombstoneExpired(tombstone, nowMs)) {\n return {\n status: 410,\n message:\n `\"${tombstone.fileName}\" was deleted more than ` +\n `${MEDIA_TOMBSTONE_RETENTION_DAYS} days ago, so its file is no ` +\n 'longer recoverable.',\n }\n }\n const usedMb = (usedBytes + Number(tombstone.sizeBytes ?? 0)) / (1024 * 1024)\n const quota = checkQuota(\n billing as never,\n 'storagePerHostMb',\n Math.ceil(usedMb) - 1,\n )\n if (!quota.allowed) {\n return {\n status: 403,\n message:\n `Restoring \"${tombstone.fileName}\" would put this library over its ` +\n `storage limit (${quota.limit} MB). Free up space and try again — ` +\n 'the file stays restorable until the window closes.',\n }\n }\n return null\n}\n\n/**\n * Put a deleted asset back: object, variants, document and counters.\n *\n * Order is the same argument as the delete, run backwards. Bytes first, then\n * the commit — so the only partial state this can leave is an object restored\n * with no document, which the tombstone (still present, because the commit is\n * what consumes it) makes a retry away from finished. The reverse order would\n * publish a document whose bytes may never arrive.\n *\n * The commit itself carries the document write, the tombstone delete and both\n * counter increments together, and it re-reads the tombstone inside the\n * transaction. That re-read is what makes a double-click harmless: the second\n * transaction finds no tombstone, commits nothing, and the caller is told the\n * file is already back rather than being charged for it twice.\n */\nexport async function restoreMediaFromTombstone(options: {\n scopeRef: FirebaseFirestore.DocumentReference\n bucket: TombstoneStorageBucket\n mediaId: string\n billing: Record<string, unknown> | undefined\n nowMs?: number\n}): Promise<RestoreMediaResult> {\n const { scopeRef, bucket, mediaId, billing } = options\n const nowMs = options.nowMs ?? Date.now()\n const mediaRef = scopeRef.collection('media').doc(mediaId)\n const tombstoneRef = scopeRef\n .collection(MEDIA_TOMBSTONE_COLLECTION)\n .doc(mediaId)\n const counterRef = scopeRef.collection('counters').doc('media')\n\n const tombstoneSnapshot = await tombstoneRef.get()\n if (!tombstoneSnapshot.exists) {\n // Either it was never written, or the window closed and the TTL swept it.\n // Both are the same fact to the caller, and neither is an error state the\n // product can act on.\n const media = await mediaRef.get()\n if (media.exists) {\n return {\n ok: true,\n status: 200,\n message: 'That file is already back in the library.',\n fileName: String(media.get('fileName') ?? mediaId),\n }\n }\n return {\n ok: false,\n status: 404,\n message: 'That file can no longer be restored.',\n }\n }\n\n const tombstone = tombstoneSnapshot.data() as MediaTombstoneDoc\n const counter = await counterRef.get()\n const usedBytes = Number(counter.get('bytes') ?? 0)\n const refusal = mediaRestoreRefusal({\n tombstone,\n nowMs,\n usedBytes,\n billing,\n })\n if (refusal) {\n // An expired tombstone is dead weight — a copy of customer data whose only\n // possible future is this refusal. Reap it here rather than waiting on a\n // TTL sweep that is documented as unprompt.\n if (refusal.status === 410) {\n await tombstoneRef.delete().catch(() => undefined)\n }\n return { ok: false, ...refusal, fileName: tombstone.fileName }\n }\n\n const objects = Array.isArray(tombstone.objects) ? tombstone.objects : []\n const [primary, ...variants] = objects\n const restoreObject = async (\n object: MediaObjectGeneration,\n ): Promise<boolean> => {\n if (!object?.generation) return false\n const file = bucket.file(object.path)\n // Already live — the delete's object sweep is best-effort, so this is a\n // real branch, not a defensive one. `restore()` on a live generation is\n // not a no-op, so the check has to come first.\n const existing = await file.exists().catch(() => [false])\n if (Array.isArray(existing) ? existing[0] : existing) return true\n await file.restore({ generation: Number(object.generation) })\n return true\n }\n\n if (primary) {\n try {\n await restoreObject(primary)\n } catch (error) {\n console.error(\n `restoreMediaFromTombstone: object restore failed for ${mediaId}`,\n error,\n )\n return {\n ok: false,\n status: 502,\n message:\n `\"${tombstone.fileName}\" could not be restored — its file could ` +\n 'not be recovered from storage. Nothing was changed.',\n fileName: tombstone.fileName,\n }\n }\n }\n // Variants are derived artifacts the platform can regenerate, and the upload\n // path already refuses to fail an asset for them. Same call here.\n for (const variant of variants) {\n await restoreObject(variant).catch((error) => {\n console.error(\n `restoreMediaFromTombstone: variant ${variant?.path} failed`,\n error,\n )\n return false\n })\n }\n\n const restored = await scopeRef.firestore.runTransaction(\n async (transaction) => {\n const fresh = await transaction.get(tombstoneRef)\n if (!fresh.exists) return false\n const record = fresh.data() as MediaTombstoneDoc\n // Without its delivery copy record: the delete removed those copies,\n // and a record of them would name objects that are gone (AGL-2824).\n // With the library's filter keys re-derived, so a file deleted before\n // they existed comes back findable by them (AGL-3327).\n const media = withoutMediaDeliveryCopies(record.media)\n transaction.set(mediaRef, {\n ...media,\n ...mediaFilterKeys(media as Parameters<typeof mediaFilterKeys>[0]),\n folderId: (media as { folderId?: unknown }).folderId ?? null,\n })\n transaction.delete(tombstoneRef)\n transaction.set(\n counterRef,\n {\n bytes: FieldValue.increment(Number(record.sizeBytes ?? 0)),\n count: FieldValue.increment(1),\n },\n { merge: true },\n )\n return true\n },\n )\n\n return {\n ok: true,\n status: 200,\n message: restored\n ? `Restored \"${tombstone.fileName}\".`\n : 'That file is already back in the library.',\n fileName: tombstone.fileName,\n }\n}\n"],"names":["FieldValue","Timestamp","checkQuota","mediaFilterKeys","removeMediaDeliveryCopies","withoutMediaDeliveryCopies","mediaDerivedObjectPaths","MEDIA_TOMBSTONE_COLLECTION","MEDIA_TOMBSTONE_RETENTION_MS","MEDIA_TOMBSTONE_RETENTION_DAYS","Math","round","mediaTombstoneExpiry","deletedAtMs","toMillis","value","timestamp","Number","isMediaTombstoneExpired","tombstone","nowMs","expiresAt","captureObjectGenerations","bucket","paths","Promise","all","map","path","response","file","getMetadata","metadata","Array","isArray","generation","undefined","String","removeDeliveryCopies","scopeRef","mediaId","collection","parent","id","asset","scopeId","deleteMediaWithTombstone","options","snapshot","objectPath","uid","Date","now","mediaRef","doc","get","exists","delete","catch","deleted","variantPaths","objects","sizeBytes","fileName","tombstoneRef","counterRef","committed","firestore","runTransaction","transaction","fresh","data","media","deletedBy","deletedAt","fromMillis","set","bytes","increment","count","merge","mediaRestoreRefusal","usedBytes","billing","status","message","usedMb","quota","ceil","allowed","limit","restoreMediaFromTombstone","counter","tombstoneSnapshot","ok","refusal","primary","variants","restoreObject","object","existing","restore","error","console","variant","restored","record","folderId"],"mappings":";AAAA;;;;;;;;;;;;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,QAAQnE,2BAA2BqG,OAAOlC,KAAK;QACrDH,YAAYO,GAAG,CAACvB,UAAU,aACrBmB,OACArE,gBAAgBqE;YACnBmC,QAAQ,GAAE,kBAAA,AAACnC,MAAiCmC,QAAQ,YAA1C,kBAA8C;;QAE1DtC,YAAYZ,MAAM,CAACO;QACnBK,YAAYO,GAAG,CACbX,YACA;YACEY,OAAO7E,WAAW8E,SAAS,CAAC7D,QAAOyF,oBAAAA,OAAO5C,SAAS,YAAhB4C,oBAAoB;YACvD3B,OAAO/E,WAAW8E,SAAS,CAAC;QAC9B,GACA;YAAEE,OAAO;QAAK;QAEhB,OAAO;IACT;IAGF,OAAO;QACLc,IAAI;QACJV,QAAQ;QACRC,SAASoB,WACL,CAAC,UAAU,EAAEtF,UAAU4C,QAAQ,CAAC,EAAE,CAAC,GACnC;QACJA,UAAU5C,UAAU4C,QAAQ;IAC9B;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/media-tombstone.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 { FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport { checkQuota } from '@aglyn/aglyn/server'\nimport { mediaFilterKeys } from '@aglyn/aglyn/app-utils/media-metadata'\nimport { reconcileAllExcept } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n removeMediaDeliveryCopies,\n withoutMediaDeliveryCopies,\n} from './media-delivery'\nimport { mediaDerivedObjectPaths } from './media-variants'\nimport { orgHostIdsFromDoc } from './scope-sharing-sweep'\n\n/**\n * What a DAM delete has to leave behind for an undo to be possible at all\n * (AGL-1467).\n *\n * ## The gap this closes\n *\n * The bucket has soft-delete on with a **seven-day** retention, so the bytes\n * of a deleted asset really are still there. That was only ever half of an\n * undo, and AGL-1461 shipped honest copy rather than a button because of the\n * other half: `/api/media/upload`'s DELETE branch hard-deleted the Firestore\n * document. After it ran, nothing in the product knew the asset's id, file\n * name, folder, tags, alt text, description, custom metadata, `visibleTo`\n * scope tokens, `cdnPath` or `variants` — and `File.restore()` needs a\n * **generation number** that nobody had captured. Surviving bytes with no\n * address are not a recovery story. On 2026-08-13 two files deleted in error\n * came back only because an unrelated analysis document happened to have\n * recorded their ids; a customer has no such document.\n *\n * A tombstone is the three facts that make the bytes addressable again:\n *\n * 1. the media document verbatim, as it was at the moment of the delete;\n * 2. the **generation** of the storage object and of every CDN variant,\n * read BEFORE the delete — afterwards there is no live object to ask;\n * 3. `sizeBytes`, so the counter decrement can be reversed by exactly the\n * amount it moved rather than by a recomputation that can drift.\n *\n * ## Where it lives, and why that is the whole erasure answer\n *\n * `{hosts|orgs}/{scopeId}/mediaTombstones/{mediaId}` — a subcollection of the\n * scope that owned the asset, never a top-level collection keyed by media id.\n *\n * This is the load-bearing choice. `eraseHost` ends in\n * `recursiveDelete(hostRef)` and `eraseOrg` ends in `recursiveDelete(orgRef)`,\n * and a path-scoped cascade takes every subcollection under the path with it.\n * Put the tombstones there and an erasure removes them with no new code — put\n * them in a top-level `mediaTombstones/{id}` with an `orgId` field and they\n * become exactly the shape AGL-1444 and AGL-1448 had to go back and wire by\n * hand: a collection the cascade is structurally blind to, holding a verbatim\n * copy of customer content, surviving the request that promised it was gone.\n * A tombstone is customer data. It has to die with the customer.\n *\n * (The property is asserted rather than assumed —\n * `erase-media-tombstones.emulator.spec.ts` erases a host and an org that each\n * hold one and looks for the survivor.)\n *\n * ## Retention: the same seven days as the bytes, and not a day more\n *\n * `expiresAt` is stamped at `MEDIA_TOMBSTONE_RETENTION_MS` past the delete,\n * which is the bucket's soft-delete window exactly. Both other numbers are\n * wrong for the same reason from opposite directions: a shorter tombstone\n * strands recoverable bytes with no address, which is today's defect made\n * smaller, and a longer one can only ever produce a failed restore while\n * holding a copy of a customer's asset for no reachable purpose. AGL-1443 is\n * open on precisely that — a durable copy of customer data whose retention\n * nobody chose — and this must not become a second instance of it.\n *\n * The field is enforced two ways, because neither alone is enough. A Firestore\n * TTL policy on `mediaTombstones.expiresAt` reaps them (see\n * `docs/FIRESTORE_MANUAL_CONFIG.md`), and TTL deletion is explicitly not\n * prompt — so `restoreMediaFromTombstone` treats an expired tombstone as\n * absent and deletes it on sight rather than trusting the sweeper.\n */\n\n/** The subcollection, under the scope that owned the asset. */\nexport const MEDIA_TOMBSTONE_COLLECTION = 'mediaTombstones'\n\n/**\n * How long a tombstone lives: the bucket's soft-delete retention, exactly.\n *\n * Changing this without changing the bucket policy breaks the invariant the\n * whole module rests on — see the header.\n */\nexport const MEDIA_TOMBSTONE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000\n\n/** Days, for the copy that has to name the window to a person. */\nexport const MEDIA_TOMBSTONE_RETENTION_DAYS = Math.round(\n MEDIA_TOMBSTONE_RETENTION_MS / (24 * 60 * 60 * 1000),\n)\n\n/**\n * One deleted object and the generation that addresses it.\n *\n * `generation` is nullable on purpose: reading it is a Storage round-trip that\n * can fail, and an asset whose object was ALREADY missing (replaced, swept,\n * never written) must still produce a tombstone — the document half of the\n * restore is worth having on its own. A null generation means \"nothing to\n * restore here\", not \"restore failed\".\n */\nexport interface MediaObjectGeneration {\n path: string\n generation: string | null\n}\n\n/** The stored tombstone document. */\nexport interface MediaTombstoneDoc {\n /** The media document verbatim, exactly as the delete found it. */\n media: Record<string, unknown>\n /** Primary object first, then every CDN variant. */\n objects: MediaObjectGeneration[]\n /** The counter decrement to reverse, taken from the document. */\n sizeBytes: number\n fileName: string\n deletedBy: string\n deletedAt: Timestamp | number\n /**\n * Hard bound — see the header. Written as a **Timestamp**, which the TTL\n * policy requires (a number field cannot carry one, which is why\n * `bookings.expiresAtMs` is documented as not a TTL target). Read through\n * `isMediaTombstoneExpired`, which takes either form so a hand-written\n * fixture and the real write are both legible.\n */\n expiresAt: Timestamp | number\n}\n\n/**\n * The slice of `File` this module needs; the real one satisfies it.\n *\n * `restore` takes a NUMBER because the SDK's `RestoreOptions` does, while the\n * tombstone stores the generation as a string — a GCS generation is a\n * microsecond timestamp (~1.7e15), comfortably inside a double, but a string\n * is what survives JSON, a Firestore round-trip and a log line without anyone\n * having to reason about that. The conversion happens once, at the call.\n */\nexport interface TombstoneStorageFile {\n getMetadata(): Promise<any>\n delete(): Promise<any>\n exists(): Promise<any>\n restore(options: { generation: number }): Promise<any>\n}\n\n/** The slice of `Bucket` this module needs. */\nexport interface TombstoneStorageBucket {\n file(path: string): TombstoneStorageFile\n}\n\n/** When a tombstone written now stops being useful. */\nexport function mediaTombstoneExpiry(deletedAtMs: number): number {\n return deletedAtMs + MEDIA_TOMBSTONE_RETENTION_MS\n}\n\n/** Milliseconds out of a Firestore Timestamp or a plain number. */\nfunction toMillis(value: unknown): number {\n const timestamp = value as { toMillis?: () => number }\n if (typeof timestamp?.toMillis === 'function') return timestamp.toMillis()\n return Number(value ?? 0)\n}\n\n/**\n * Whether the bytes this tombstone addresses are past the bucket's window.\n *\n * Missing or unreadable reads as EXPIRED, which is the safe direction: the\n * failure mode of a false positive is a refusal with a clear message, and the\n * failure mode of a false negative is a restore that half-succeeds against\n * bytes the bucket has already reaped.\n */\nexport function isMediaTombstoneExpired(\n tombstone: Pick<MediaTombstoneDoc, 'expiresAt'>,\n nowMs: number,\n): boolean {\n return !(toMillis(tombstone.expiresAt) > nowMs)\n}\n\n/**\n * Read the generation of each object, best-effort (AGL-1467).\n *\n * Must run BEFORE the delete. Once the object is soft-deleted there is no live\n * generation to read, and the number is the only handle `restore()` takes —\n * this is the single fact whose absence made undo impossible rather than\n * merely unbuilt.\n *\n * A failure here degrades the tombstone to its document half rather than\n * failing the delete: an author who asked for a file to go must not be told\n * \"no\" because a metadata read timed out.\n */\nexport async function captureObjectGenerations(\n bucket: TombstoneStorageBucket,\n paths: readonly string[],\n): Promise<MediaObjectGeneration[]> {\n return Promise.all(\n paths.map(async (path) => {\n try {\n const response = await bucket.file(path).getMetadata()\n const metadata = Array.isArray(response) ? response[0] : response\n const generation = metadata?.generation\n return {\n path,\n generation:\n generation === undefined || generation === null\n ? null\n : String(generation),\n }\n } catch {\n return { path, generation: null }\n }\n }),\n )\n}\n\n/**\n * Removes the delivery provider's copies of a deleted asset (AGL-2824).\n *\n * Unlike the bucket's objects they are not kept for a restore — a restore\n * copies the video again — and no tombstone records them. The library is\n * read off the scope reference (`hosts/{id}` or `orgs/{id}`). Nothing runs\n * when no provider is configured to store, and a failure is logged rather\n * than answered, like the object deletes beside it.\n */\nasync function removeDeliveryCopies(\n scopeRef: FirebaseFirestore.DocumentReference,\n mediaId: string,\n): Promise<void> {\n const collection = scopeRef.parent?.id\n if (collection !== 'hosts' && collection !== 'orgs') return\n await removeMediaDeliveryCopies({\n asset: { collection, scopeId: scopeRef.id, mediaId },\n })\n}\n\nexport interface DeleteMediaResult {\n /** False when there was no document to delete (already gone). */\n deleted: boolean\n /** Present when a tombstone was written — the id is the media id. */\n tombstone?: { mediaId: string; expiresAt: number; fileName: string }\n}\n\n/**\n * Delete a media document and leave a tombstone behind, in one commit.\n *\n * **The invariant: the media document is never destroyed except in the same\n * transaction that writes its tombstone and moves the counter.** All three\n * belong to one commit, so there is no interleaving in which the document is\n * gone and the record of it is not — which is the state the product was\n * permanently in before this issue.\n *\n * The object delete happens AFTER that commit, deliberately, and the ordering\n * is a choice between two partial failures:\n *\n * - object first: a failed commit leaves a live document pointing at bytes\n * that are already soft-deleted — a broken asset in the library that\n * nothing detects;\n * - commit first: a failed object delete leaves a tombstone whose object is\n * still live, which `restoreMediaFromTombstone` handles by skipping the\n * restore for an object that is already there.\n *\n * The second is recoverable by the code in this file. The first is not\n * recoverable by anything.\n */\nexport async function deleteMediaWithTombstone(options: {\n scopeRef: FirebaseFirestore.DocumentReference\n bucket: TombstoneStorageBucket\n mediaId: string\n /** Path of the primary object, resolved by the caller (legacy fallback). */\n objectPath: string\n /** Who asked — an erasure record with no actor is half a record. */\n uid: string\n nowMs?: number\n}): Promise<DeleteMediaResult> {\n const { scopeRef, bucket, mediaId, objectPath, uid } = options\n const nowMs = options.nowMs ?? Date.now()\n const mediaRef = scopeRef.collection('media').doc(mediaId)\n const snapshot = await mediaRef.get()\n if (!snapshot.exists) {\n // No document, so nothing to record and nothing to restore to. The object\n // sweep below still runs: an orphan object is exactly what this branch is\n // for, and it predates the tombstone.\n await bucket.file(objectPath).delete().catch(() => undefined)\n await removeDeliveryCopies(scopeRef, mediaId)\n return { deleted: false }\n }\n\n // Every derived object, not only the variants (AGL-3486): a display copy,\n // a film's poster and its renditions are kept and restored with the rest.\n const variantPaths = mediaDerivedObjectPaths(objectPath, snapshot)\n // BEFORE the delete — the whole point. See `captureObjectGenerations`.\n const objects = await captureObjectGenerations(bucket, [\n objectPath,\n ...variantPaths,\n ])\n\n const sizeBytes = Number(snapshot.get('sizeBytes') ?? 0)\n const fileName = String(snapshot.get('fileName') ?? mediaId)\n const expiresAt = mediaTombstoneExpiry(nowMs)\n const tombstoneRef = scopeRef\n .collection(MEDIA_TOMBSTONE_COLLECTION)\n .doc(mediaId)\n const counterRef = scopeRef.collection('counters').doc('media')\n\n const committed = await scopeRef.firestore.runTransaction(\n async (transaction) => {\n const fresh = await transaction.get(mediaRef)\n // Someone else deleted it between the read above and here. Their commit\n // wrote the tombstone; ours must not write a second one over it.\n if (!fresh.exists) return false\n const data = (fresh.data() ?? {}) as Record<string, unknown>\n const tombstone: MediaTombstoneDoc = {\n media: data,\n objects,\n sizeBytes: Number(data['sizeBytes'] ?? sizeBytes) || 0,\n fileName: String(data['fileName'] ?? fileName),\n deletedBy: uid,\n deletedAt: Timestamp.fromMillis(nowMs),\n // Timestamp, not a number: the TTL policy on\n // `mediaTombstones.expiresAt` cannot key on anything else.\n expiresAt: Timestamp.fromMillis(expiresAt),\n }\n transaction.set(tombstoneRef, tombstone)\n transaction.delete(mediaRef)\n transaction.set(\n counterRef,\n {\n bytes: FieldValue.increment(-tombstone.sizeBytes),\n count: FieldValue.increment(-1),\n },\n { merge: true },\n )\n return true\n },\n )\n\n // Object and variants last, best-effort, exactly as before — the bucket\n // keeps them for the retention window either way.\n await bucket.file(objectPath).delete().catch(() => undefined)\n await Promise.all(\n variantPaths.map((path) =>\n bucket.file(path).delete().catch(() => undefined),\n ),\n )\n await removeDeliveryCopies(scopeRef, mediaId)\n\n if (!committed) return { deleted: false }\n return { deleted: true, tombstone: { mediaId, expiresAt, fileName } }\n}\n\nexport interface RestoreMediaResult {\n ok: boolean\n /** HTTP status the route should answer with. */\n status: number\n /** A real sentence for a person — never a bare code. */\n message: string\n fileName?: string\n}\n\n/**\n * Why a restore cannot proceed, decided without touching Storage (AGL-1467).\n *\n * Pure, because these are the answers a person actually sees and the two\n * interesting ones are cheap to get wrong: an expired tombstone must fail\n * CLEANLY rather than half-succeed against bytes the bucket has already\n * reaped, and a restore that would breach the plan must say so rather than\n * push the counter past the limit in silence.\n *\n * ## The quota call\n *\n * A restore re-adds real bytes, so it is gated exactly like an upload —\n * `storagePerHostMb`, same off-by-one — and REFUSED when it would breach the\n * plan. Waiving it would let delete-then-restore launder an over-quota\n * library, which is the AGL-1471/AGL-1279 shape (a limit evaluated at a moment\n * the caller controls). Refusing is safe precisely because the tombstone\n * outlives the refusal: the asset is still restorable for the rest of the\n * window once space is freed, which is what makes \"no, and here is why\"\n * an honest answer rather than a loss.\n *\n * Note what is NOT metered: the soft-deleted bytes themselves. They sit in the\n * bucket for seven days at Aglyn's cost, and counting them would mean deleting\n * a file did not free space until a week later — which breaks the one action\n * an author takes when they hit the wall. The window is the price of offering\n * undo, not an allocation to bill back.\n */\nexport function mediaRestoreRefusal(options: {\n tombstone: Pick<MediaTombstoneDoc, 'expiresAt' | 'sizeBytes' | 'fileName'>\n nowMs: number\n /** Counter bytes as they stand now, with the asset already removed. */\n usedBytes: number\n billing: Record<string, unknown> | undefined\n}): { status: number; message: string } | null {\n const { tombstone, nowMs, usedBytes, billing } = options\n if (isMediaTombstoneExpired(tombstone, nowMs)) {\n return {\n status: 410,\n message:\n `\"${tombstone.fileName}\" was deleted more than ` +\n `${MEDIA_TOMBSTONE_RETENTION_DAYS} days ago, so its file is no ` +\n 'longer recoverable.',\n }\n }\n const usedMb = (usedBytes + Number(tombstone.sizeBytes ?? 0)) / (1024 * 1024)\n const quota = checkQuota(\n billing as never,\n 'storagePerHostMb',\n Math.ceil(usedMb) - 1,\n )\n if (!quota.allowed) {\n return {\n status: 403,\n message:\n `Restoring \"${tombstone.fileName}\" would put this library over its ` +\n `storage limit (${quota.limit} MB). Free up space and try again — ` +\n 'the file stays restorable until the window closes.',\n }\n }\n return null\n}\n\n/**\n * Put a deleted asset back: object, variants, document and counters.\n *\n * Order is the same argument as the delete, run backwards. Bytes first, then\n * the commit — so the only partial state this can leave is an object restored\n * with no document, which the tombstone (still present, because the commit is\n * what consumes it) makes a retry away from finished. The reverse order would\n * publish a document whose bytes may never arrive.\n *\n * The commit itself carries the document write, the tombstone delete and both\n * counter increments together, and it re-reads the tombstone inside the\n * transaction. That re-read is what makes a double-click harmless: the second\n * transaction finds no tombstone, commits nothing, and the caller is told the\n * file is already back rather than being charged for it twice.\n */\n/**\n * The scope a restored file of the workspace library is written with, when it\n * carries the marker of \"all sites except some\" (AGL-4047): `visibleTo` and the\n * marker as `reconcileAllExcept` answers them for the workspace's sites today.\n * Empty for anything else: an unmarked file, a site's own library, or a marker\n * the helper can't act on (left as it was, for the weekly drift report).\n *\n * Spread over the whole document, which a `set` with no merge writes, so a\n * marker that drops to All sites is taken off by deleting the keys from the\n * copy, never by storing a null.\n */\nasync function restoredScopeFields(\n transaction: FirebaseFirestore.Transaction,\n scopeRef: FirebaseFirestore.DocumentReference,\n media: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n if (media['scopeMode'] === undefined || scopeRef.parent.id !== 'orgs') return {}\n const org = await transaction.get(scopeRef)\n const answer = reconcileAllExcept(media, orgHostIdsFromDoc(org.data()))\n if (!answer.fields) return {}\n if (!answer.fields.scopeMode) {\n delete media['scopeMode']\n delete media['scopeExcept']\n return { visibleTo: answer.fields.visibleTo }\n }\n return { ...answer.fields }\n}\n\nexport async function restoreMediaFromTombstone(options: {\n scopeRef: FirebaseFirestore.DocumentReference\n bucket: TombstoneStorageBucket\n mediaId: string\n billing: Record<string, unknown> | undefined\n nowMs?: number\n}): Promise<RestoreMediaResult> {\n const { scopeRef, bucket, mediaId, billing } = options\n const nowMs = options.nowMs ?? Date.now()\n const mediaRef = scopeRef.collection('media').doc(mediaId)\n const tombstoneRef = scopeRef\n .collection(MEDIA_TOMBSTONE_COLLECTION)\n .doc(mediaId)\n const counterRef = scopeRef.collection('counters').doc('media')\n\n const tombstoneSnapshot = await tombstoneRef.get()\n if (!tombstoneSnapshot.exists) {\n // Either it was never written, or the window closed and the TTL swept it.\n // Both are the same fact to the caller, and neither is an error state the\n // product can act on.\n const media = await mediaRef.get()\n if (media.exists) {\n return {\n ok: true,\n status: 200,\n message: 'That file is already back in the library.',\n fileName: String(media.get('fileName') ?? mediaId),\n }\n }\n return {\n ok: false,\n status: 404,\n message: 'That file can no longer be restored.',\n }\n }\n\n const tombstone = tombstoneSnapshot.data() as MediaTombstoneDoc\n const counter = await counterRef.get()\n const usedBytes = Number(counter.get('bytes') ?? 0)\n const refusal = mediaRestoreRefusal({\n tombstone,\n nowMs,\n usedBytes,\n billing,\n })\n if (refusal) {\n // An expired tombstone is dead weight — a copy of customer data whose only\n // possible future is this refusal. Reap it here rather than waiting on a\n // TTL sweep that is documented as unprompt.\n if (refusal.status === 410) {\n await tombstoneRef.delete().catch(() => undefined)\n }\n return { ok: false, ...refusal, fileName: tombstone.fileName }\n }\n\n const objects = Array.isArray(tombstone.objects) ? tombstone.objects : []\n const [primary, ...variants] = objects\n const restoreObject = async (\n object: MediaObjectGeneration,\n ): Promise<boolean> => {\n if (!object?.generation) return false\n const file = bucket.file(object.path)\n // Already live — the delete's object sweep is best-effort, so this is a\n // real branch, not a defensive one. `restore()` on a live generation is\n // not a no-op, so the check has to come first.\n const existing = await file.exists().catch(() => [false])\n if (Array.isArray(existing) ? existing[0] : existing) return true\n await file.restore({ generation: Number(object.generation) })\n return true\n }\n\n if (primary) {\n try {\n await restoreObject(primary)\n } catch (error) {\n console.error(\n `restoreMediaFromTombstone: object restore failed for ${mediaId}`,\n error,\n )\n return {\n ok: false,\n status: 502,\n message:\n `\"${tombstone.fileName}\" could not be restored — its file could ` +\n 'not be recovered from storage. Nothing was changed.',\n fileName: tombstone.fileName,\n }\n }\n }\n // Variants are derived artifacts the platform can regenerate, and the upload\n // path already refuses to fail an asset for them. Same call here.\n for (const variant of variants) {\n await restoreObject(variant).catch((error) => {\n console.error(\n `restoreMediaFromTombstone: variant ${variant?.path} failed`,\n error,\n )\n return false\n })\n }\n\n const restored = await scopeRef.firestore.runTransaction(\n async (transaction) => {\n const fresh = await transaction.get(tombstoneRef)\n if (!fresh.exists) return false\n const record = fresh.data() as MediaTombstoneDoc\n // Without its delivery copy record: the delete removed those copies,\n // and a record of them would name objects that are gone (AGL-2824).\n // With the library's filter keys re-derived, so a file deleted before\n // they existed comes back findable by them (AGL-3327).\n const media = withoutMediaDeliveryCopies(record.media)\n // Shared with all sites except some (AGL-4047): the sites it reaches are\n // a list the sweep keeps up as sites come and go, and the sweep never saw\n // this file while it was deleted. So it comes back reaching the sites\n // the workspace has NOW, read in this transaction, as the sweep would\n // have left it. Any other file comes back as it was.\n const scope = await restoredScopeFields(transaction, scopeRef, media)\n transaction.set(mediaRef, {\n ...media,\n ...scope,\n ...mediaFilterKeys(media as Parameters<typeof mediaFilterKeys>[0]),\n folderId: (media as { folderId?: unknown }).folderId ?? null,\n })\n transaction.delete(tombstoneRef)\n transaction.set(\n counterRef,\n {\n bytes: FieldValue.increment(Number(record.sizeBytes ?? 0)),\n count: FieldValue.increment(1),\n },\n { merge: true },\n )\n return true\n },\n )\n\n return {\n ok: true,\n status: 200,\n message: restored\n ? `Restored \"${tombstone.fileName}\".`\n : 'That file is already back in the library.',\n fileName: tombstone.fileName,\n }\n}\n"],"names":["FieldValue","Timestamp","checkQuota","mediaFilterKeys","reconcileAllExcept","removeMediaDeliveryCopies","withoutMediaDeliveryCopies","mediaDerivedObjectPaths","orgHostIdsFromDoc","MEDIA_TOMBSTONE_COLLECTION","MEDIA_TOMBSTONE_RETENTION_MS","MEDIA_TOMBSTONE_RETENTION_DAYS","Math","round","mediaTombstoneExpiry","deletedAtMs","toMillis","value","timestamp","Number","isMediaTombstoneExpired","tombstone","nowMs","expiresAt","captureObjectGenerations","bucket","paths","Promise","all","map","path","response","file","getMetadata","metadata","Array","isArray","generation","undefined","String","removeDeliveryCopies","scopeRef","mediaId","collection","parent","id","asset","scopeId","deleteMediaWithTombstone","options","snapshot","objectPath","uid","Date","now","mediaRef","doc","get","exists","delete","catch","deleted","variantPaths","objects","sizeBytes","fileName","tombstoneRef","counterRef","committed","firestore","runTransaction","transaction","fresh","data","media","deletedBy","deletedAt","fromMillis","set","bytes","increment","count","merge","mediaRestoreRefusal","usedBytes","billing","status","message","usedMb","quota","ceil","allowed","limit","restoredScopeFields","org","answer","fields","scopeMode","visibleTo","restoreMediaFromTombstone","counter","tombstoneSnapshot","ok","refusal","primary","variants","restoreObject","object","existing","restore","error","console","variant","restored","record","scope","folderId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,SAASC,UAAU,QAAQ,sBAAqB;AAChD,SAASC,eAAe,QAAQ,wCAAuC;AACvE,SAASC,kBAAkB,QAAQ,sCAAqC;AACxE,SACEC,yBAAyB,EACzBC,0BAA0B,QACrB,sBAAkB;AACzB,SAASC,uBAAuB,QAAQ,sBAAkB;AAC1D,SAASC,iBAAiB,QAAQ,2BAAuB;AAEzD;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