@aglyn/tenant-data-admin 1.0.0-beta.198 → 1.0.0-beta.200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/admin-audit-write.d.ts +28 -0
  3. package/src/lib/server/admin-audit-write.js +46 -0
  4. package/src/lib/server/admin-audit-write.js.map +1 -0
  5. package/src/lib/server/admin-audit.d.ts +4 -9
  6. package/src/lib/server/admin-audit.js +12 -31
  7. package/src/lib/server/admin-audit.js.map +1 -1
  8. package/src/lib/server/collection-live-pages.d.ts +83 -0
  9. package/src/lib/server/collection-live-pages.js +198 -0
  10. package/src/lib/server/collection-live-pages.js.map +1 -0
  11. package/src/lib/server/consent-group-carry.js +2 -0
  12. package/src/lib/server/consent-group-carry.js.map +1 -1
  13. package/src/lib/server/contact-company-link.js +3 -0
  14. package/src/lib/server/contact-company-link.js.map +1 -1
  15. package/src/lib/server/contact-lifecycle-floor.js +3 -0
  16. package/src/lib/server/contact-lifecycle-floor.js.map +1 -1
  17. package/src/lib/server/contact-merge.js +4 -0
  18. package/src/lib/server/contact-merge.js.map +1 -1
  19. package/src/lib/server/crm-booking-activity.js +3 -2
  20. package/src/lib/server/crm-booking-activity.js.map +1 -1
  21. package/src/lib/server/crm-records.d.ts +15 -0
  22. package/src/lib/server/crm-records.js +52 -0
  23. package/src/lib/server/crm-records.js.map +1 -1
  24. package/src/lib/server/csp-aggregate.d.ts +16 -0
  25. package/src/lib/server/csp-aggregate.js +36 -0
  26. package/src/lib/server/csp-aggregate.js.map +1 -1
  27. package/src/lib/server/duplicate-resource.js +12 -5
  28. package/src/lib/server/duplicate-resource.js.map +1 -1
  29. package/src/lib/server/email-delivery-log.d.ts +33 -0
  30. package/src/lib/server/email-delivery-log.js +43 -2
  31. package/src/lib/server/email-delivery-log.js.map +1 -1
  32. package/src/lib/server/email-suppression.d.ts +11 -14
  33. package/src/lib/server/email-suppression.js +14 -31
  34. package/src/lib/server/email-suppression.js.map +1 -1
  35. package/src/lib/server/erase-person.js +22 -3
  36. package/src/lib/server/erase-person.js.map +1 -1
  37. package/src/lib/server/erase.js +4 -3
  38. package/src/lib/server/erase.js.map +1 -1
  39. package/src/lib/server/host-memberships.d.ts +34 -0
  40. package/src/lib/server/host-memberships.js +89 -1
  41. package/src/lib/server/host-memberships.js.map +1 -1
  42. package/src/lib/server/host-visitor-records.js +23 -3
  43. package/src/lib/server/host-visitor-records.js.map +1 -1
  44. package/src/lib/server/list-members.d.ts +11 -0
  45. package/src/lib/server/list-members.js +28 -1
  46. package/src/lib/server/list-members.js.map +1 -1
  47. package/src/lib/server/list-query.d.ts +36 -0
  48. package/src/lib/server/list-query.js +49 -0
  49. package/src/lib/server/list-query.js.map +1 -0
  50. package/src/lib/server/live-page-usage.d.ts +33 -0
  51. package/src/lib/server/live-page-usage.js +61 -1
  52. package/src/lib/server/live-page-usage.js.map +1 -1
  53. package/src/lib/server/media-tombstone.js +8 -2
  54. package/src/lib/server/media-tombstone.js.map +1 -1
  55. package/src/lib/server/org-member-list-fields.d.ts +31 -0
  56. package/src/lib/server/org-member-list-fields.js +38 -0
  57. package/src/lib/server/org-member-list-fields.js.map +1 -0
  58. package/src/lib/server/organizations.js +37 -7
  59. package/src/lib/server/organizations.js.map +1 -1
  60. package/src/lib/server/replay-erasures.js +2 -1
  61. package/src/lib/server/replay-erasures.js.map +1 -1
  62. package/src/lib/server/sso-enforcement.js +2 -1
  63. package/src/lib/server/sso-enforcement.js.map +1 -1
  64. package/src/lib/server/upsert-contact.js +8 -4
  65. package/src/lib/server/upsert-contact.js.map +1 -1
@@ -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 {\n removeMediaDeliveryCopies,\n withoutMediaDeliveryCopies,\n} from './media-delivery'\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 const variantWidths: number[] = snapshot.get('variants') ?? []\n const variantPaths = variantWidths.map(\n (width) => `${objectPath}__w${width}.webp`,\n )\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 transaction.set(mediaRef, withoutMediaDeliveryCopies(record.media))\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","removeMediaDeliveryCopies","withoutMediaDeliveryCopies","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","variantWidths","variantPaths","width","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"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,SAASC,UAAU,QAAQ,sBAAqB;AAChD,SACEC,yBAAyB,EACzBC,0BAA0B,QACrB,sBAAkB;AAEzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6DC,GAED,6DAA6D,GAC7D,OAAO,MAAMC,6BAA6B,kBAAiB;AAE3D;;;;;CAKC,GACD,OAAO,MAAMC,+BAA+B,IAAI,KAAK,KAAK,KAAK,KAAI;AAEnE,gEAAgE,GAChE,OAAO,MAAMC,iCAAiCC,KAAKC,KAAK,CACtDH,+BAAgC,CAAA,KAAK,KAAK,KAAK,IAAG,GACnD;AA0DD,qDAAqD,GACrD,OAAO,SAASI,qBAAqBC,WAAmB;IACtD,OAAOA,cAAcL;AACvB;AAEA,iEAAiE,GACjE,SAASM,SAASC,KAAc;IAC9B,MAAMC,YAAYD;IAClB,IAAI,QAAOC,6BAAAA,UAAWF,QAAQ,MAAK,YAAY,OAAOE,UAAUF,QAAQ;IACxE,OAAOG,OAAOF,gBAAAA,QAAS;AACzB;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,wBACdC,SAA+C,EAC/CC,KAAa;IAEb,OAAO,CAAEN,CAAAA,SAASK,UAAUE,SAAS,IAAID,KAAI;AAC/C;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeE,yBACpBC,MAA8B,EAC9BC,KAAwB;IAExB,OAAOC,QAAQC,GAAG,CAChBF,MAAMG,GAAG,CAAC,OAAOC;QACf,IAAI;YACF,MAAMC,WAAW,MAAMN,OAAOO,IAAI,CAAC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AAS8B,SAAS,CAACC,cAAc,CACtD,OAAOC;YAWkCqC;QAVvC,MAAMpC,QAAQ,MAAMD,YAAYhB,GAAG,CAACW;QACpC,IAAI,CAACM,MAAMhB,MAAM,EAAE,OAAO;QAC1B,MAAMoD,SAASpC,MAAMC,IAAI;QACzB,qEAAqE;QACrE,oEAAoE;QACpEF,YAAYO,GAAG,CAACzB,UAAU/C,2BAA2BsG,OAAOlC,KAAK;QACjEH,YAAYd,MAAM,CAACS;QACnBK,YAAYO,GAAG,CACbX,YACA;YACEY,OAAO7E,WAAW8E,SAAS,CAAC/D,QAAO2F,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,EAAExF,UAAU8C,QAAQ,CAAC,EAAE,CAAC,GACnC;QACJA,UAAU9C,UAAU8C,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 {\n removeMediaDeliveryCopies,\n withoutMediaDeliveryCopies,\n} from './media-delivery'\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 const variantWidths: number[] = snapshot.get('variants') ?? []\n const variantPaths = variantWidths.map(\n (width) => `${objectPath}__w${width}.webp`,\n )\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","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","variantWidths","variantPaths","width","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","vari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AAMhB,MAAM,EAAE,OAAO;QAC1B,MAAMoD,SAASpC,MAAMC,IAAI;QACzB,qEAAqE;QACrE,oEAAoE;QACpE,sEAAsE;QACtE,uDAAuD;QACvD,MAAMC,QAAQpE,2BAA2BsG,OAAOlC,KAAK;QACrDH,YAAYO,GAAG,CAACzB,UAAU,aACrBqB,OACAtE,gBAAgBsE;YACnBmC,QAAQ,GAAE,kBAAA,AAACnC,MAAiCmC,QAAQ,YAA1C,kBAA8C;;QAE1DtC,YAAYd,MAAM,CAACS;QACnBK,YAAYO,GAAG,CACbX,YACA;YACEY,OAAO9E,WAAW+E,SAAS,CAAC/D,QAAO2F,oBAAAA,OAAO5C,SAAS,YAAhB4C,oBAAoB;YACvD3B,OAAOhF,WAAW+E,SAAS,CAAC;QAC9B,GACA;YAAEE,OAAO;QAAK;QAEhB,OAAO;IACT;IAGF,OAAO;QACLc,IAAI;QACJV,QAAQ;QACRC,SAASoB,WACL,CAAC,UAAU,EAAExF,UAAU8C,QAAQ,CAAC,EAAE,CAAC,GACnC;QACJA,UAAU9C,UAAU8C,QAAQ;IAC9B;AACF"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { AglynOrgMember } from '@aglyn/aglyn/server';
18
+ /** The member fields `orgMemberListFields` derives from. */
19
+ export type OrgMemberListSource = Pick<Partial<AglynOrgMember>, 'role' | 'allHosts' | 'hostAccess' | 'displayName' | 'email'> & {
20
+ /** The job title the members route stores (AGL-364). */
21
+ title?: unknown;
22
+ };
23
+ /** The words the roster's search box finds a member by. */
24
+ export declare function orgMemberSearchTokens(member: OrgMemberListSource | null | undefined): string[];
25
+ /** Every field the roster's query reads that a member does not store as such. */
26
+ export declare function orgMemberListFields(member: OrgMemberListSource | null | undefined): {
27
+ consoleUserType: 'manager' | 'collaborator';
28
+ searchTokens: string[];
29
+ };
30
+ /** The fields `orgMemberListFields` writes, for a `mergeFields` write. */
31
+ export declare const ORG_MEMBER_LIST_FIELD_NAMES: readonly ["consoleUserType", "searchTokens"];
@@ -0,0 +1,38 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { addressSearchWords } from "@aglyn/aglyn/app-utils/activity-search";
17
+ import { nameSearchTokens } from "@aglyn/aglyn/app-utils/name-search";
18
+ import { consoleUserType } from "@aglyn/aglyn/app-utils/organizations";
19
+ /** The words the roster's search box finds a member by. */ export function orgMemberSearchTokens(member) {
20
+ const text = (value)=>typeof value === 'string' ? value.trim() : '';
21
+ return nameSearchTokens([
22
+ text(member == null ? void 0 : member.displayName),
23
+ ...addressSearchWords(member == null ? void 0 : member.email),
24
+ text(member == null ? void 0 : member.title)
25
+ ].filter(Boolean).join(' '));
26
+ }
27
+ /** Every field the roster's query reads that a member does not store as such. */ export function orgMemberListFields(member) {
28
+ return {
29
+ consoleUserType: consoleUserType(member),
30
+ searchTokens: orgMemberSearchTokens(member)
31
+ };
32
+ }
33
+ /** The fields `orgMemberListFields` writes, for a `mergeFields` write. */ export const ORG_MEMBER_LIST_FIELD_NAMES = [
34
+ 'consoleUserType',
35
+ 'searchTokens'
36
+ ];
37
+
38
+ //# sourceMappingURL=org-member-list-fields.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/org-member-list-fields.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 { addressSearchWords } from '@aglyn/aglyn/app-utils/activity-search'\nimport { nameSearchTokens } from '@aglyn/aglyn/app-utils/name-search'\nimport type { AglynOrgMember } from '@aglyn/aglyn/server'\nimport { consoleUserType } from '@aglyn/aglyn/app-utils/organizations'\n\n/*\n * WHAT THE TEAM ROSTER IS FILTERED AND SEARCHED BY (AGL-3321).\n *\n * The organization's member list (`orgs/{orgId}/members`, the Members card\n * in organization settings) filters by Role and by Access, and searches a\n * member's name, address and job title — all on the roster's Firestore query\n * (`GET /api/orgs/members` with `filters` or `search`). Two of those are not\n * stored as such on a member document, so every member carries them:\n *\n * consoleUserType `manager` or `collaborator`, as `consoleUserType` reads\n * the member's reach. That verdict is DERIVED — a legacy\n * member with neither `allHosts` nor `hostAccess` is a\n * manager — so a query cannot ask the raw fields for it.\n * searchTokens the word-prefix tokens of the display name, the address\n * (its halves and its runs, `addressSearchWords`) and the\n * job title.\n *\n * Stamped by `syncOrgAuthProjections` — the pass every membership write\n * already reaches, which recomputes the rules projection on the same\n * documents — by `createOrganization` for the owner it creates, and by\n * `backfillMemberIdentity` when it fills a blank name.\n * `tools/scripts/backfill-org-member-list-fields.mjs` stamps the roster\n * written before AGL-3321, through its script-side twin, held to\n * `tools/scripts/lib/org-member-list-fields.fixtures.json`.\n *\n * A list mirror, not an authority: nothing decides access from these.\n */\n\n/** The member fields `orgMemberListFields` derives from. */\nexport type OrgMemberListSource = Pick<\n Partial<AglynOrgMember>,\n 'role' | 'allHosts' | 'hostAccess' | 'displayName' | 'email'\n> & {\n /** The job title the members route stores (AGL-364). */\n title?: unknown\n}\n\n/** The words the roster's search box finds a member by. */\nexport function orgMemberSearchTokens(member: OrgMemberListSource | null | undefined): string[] {\n const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '')\n return nameSearchTokens(\n [\n text(member?.displayName),\n ...addressSearchWords(member?.email),\n text(member?.title),\n ]\n .filter(Boolean)\n .join(' '),\n )\n}\n\n/** Every field the roster's query reads that a member does not store as such. */\nexport function orgMemberListFields(member: OrgMemberListSource | null | undefined): {\n consoleUserType: 'manager' | 'collaborator'\n searchTokens: string[]\n} {\n return {\n consoleUserType: consoleUserType(member),\n searchTokens: orgMemberSearchTokens(member),\n }\n}\n\n/** The fields `orgMemberListFields` writes, for a `mergeFields` write. */\nexport const ORG_MEMBER_LIST_FIELD_NAMES = ['consoleUserType', 'searchTokens'] as const\n"],"names":["addressSearchWords","nameSearchTokens","consoleUserType","orgMemberSearchTokens","member","text","value","trim","displayName","email","title","filter","Boolean","join","orgMemberListFields","searchTokens","ORG_MEMBER_LIST_FIELD_NAMES"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,gBAAgB,QAAQ,qCAAoC;AAErE,SAASC,eAAe,QAAQ,uCAAsC;AAuCtE,yDAAyD,GACzD,OAAO,SAASC,sBAAsBC,MAA8C;IAClF,MAAMC,OAAO,CAACC,QAAoB,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;IAC7E,OAAON,iBACL;QACEI,KAAKD,0BAAAA,OAAQI,WAAW;WACrBR,mBAAmBI,0BAAAA,OAAQK,KAAK;QACnCJ,KAAKD,0BAAAA,OAAQM,KAAK;KACnB,CACEC,MAAM,CAACC,SACPC,IAAI,CAAC;AAEZ;AAEA,+EAA+E,GAC/E,OAAO,SAASC,oBAAoBV,MAA8C;IAIhF,OAAO;QACLF,iBAAiBA,gBAAgBE;QACjCW,cAAcZ,sBAAsBC;IACtC;AACF;AAEA,wEAAwE,GACxE,OAAO,MAAMY,8BAA8B;IAAC;IAAmB;CAAe,CAAS"}
@@ -21,6 +21,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
21
21
  * client-writable (docs/MULTI_TENANT_FIRESTORE.md §8).
22
22
  */ import { consentGroupForHost, checkHostCollaboratorQuota, checkSeatQuota, countCollaboratorSeats, countManagerSeatsExcluding, createResourceUid, generateOrgSlug, projectMemberResolvedPermissions, resolveOrgPermissions, isOrgWideMember, isValidOrgSlug, hostPermissionKeys, orgPermissionLabel, pluginOrgPermissionKeys, projectHostMemberPermissions, projectHostMemberRoles, projectMemberScopeTokens, resolveCollaboratorHostPermissions, scopeTokensForHost } from "@aglyn/aglyn/server";
23
23
  import { ACCOUNT_ACQUISITION_FIELD, organizationAcquisition } from "@aglyn/aglyn/app-utils/account-acquisition";
24
+ import { activitySearchTokens } from "@aglyn/aglyn/app-utils/activity-search";
24
25
  import { nameSearchKey, nameSearchReversed, nameSearchTokens } from "@aglyn/aglyn/app-utils/name-search";
25
26
  // LEAF MODULE, NOT THE BARREL (AGL-1289). This file is itself reachable
26
27
  // through `@aglyn/aglyn/server`, and the verdict route proved this week that a
@@ -34,6 +35,7 @@ import { findUserByUidAcrossPools } from "./auth-pools.js";
34
35
  import firebaseAdmin from "./firebase-admin.js";
35
36
  import { enforceFreeWorkspaceCapInTransaction, readFreeWorkspaceCapConfig } from "./free-workspace-cap.js";
36
37
  import { deleteMemberHostProjections, syncHostProjectionForMembers, syncMemberHostProjections } from "./host-memberships.js";
38
+ import { ORG_MEMBER_LIST_FIELD_NAMES, orgMemberListFields, orgMemberSearchTokens } from "./org-member-list-fields.js";
37
39
  import { updateExisting } from "./update-existing.js";
38
40
  import { attachWorkspaceDomain } from "./workspace-domains.js";
39
41
  const firestore = ()=>firebaseAdmin.app().firestore();
@@ -252,7 +254,7 @@ reservation, now = Date.now()) {
252
254
  createdAt: FieldValue.serverTimestamp(),
253
255
  updatedAt: FieldValue.serverTimestamp()
254
256
  });
255
- tx.set(db.collection('orgs').doc(orgId).collection('members').doc(ownerUid), {
257
+ tx.set(db.collection('orgs').doc(orgId).collection('members').doc(ownerUid), _extends({
256
258
  role: 'owner',
257
259
  allHosts: true,
258
260
  email: ownerEmail != null ? ownerEmail : null,
@@ -273,7 +275,13 @@ reservation, now = Date.now()) {
273
275
  */ scopeTokens: projectMemberScopeTokens({
274
276
  role: 'owner',
275
277
  allHosts: true
276
- }),
278
+ })
279
+ }, orgMemberListFields({
280
+ role: 'owner',
281
+ allHosts: true,
282
+ email: ownerEmail != null ? ownerEmail : undefined,
283
+ displayName: ownerDisplayName != null ? ownerDisplayName : undefined
284
+ }), {
277
285
  /*
278
286
  * The permission projection, stamped here for the same reason and
279
287
  * with the same consequence if it is missed.
@@ -288,7 +296,7 @@ reservation, now = Date.now()) {
288
296
  role: 'owner',
289
297
  allHosts: true
290
298
  }, null)
291
- });
299
+ }));
292
300
  tx.set(db.collection('users').doc(ownerUid).collection('orgs').doc(orgId), // The owner reaches every site by definition (AGL-1032).
293
301
  {
294
302
  role: 'owner',
@@ -778,7 +786,8 @@ export async function listOrgMembers(orgId) {
778
786
  const MEMBER_PROJECTION_WRITE = {
779
787
  mergeFields: [
780
788
  'scopeTokens',
781
- 'resolvedPermissions'
789
+ 'resolvedPermissions',
790
+ ...ORG_MEMBER_LIST_FIELD_NAMES
782
791
  ]
783
792
  };
784
793
  /**
@@ -847,7 +856,7 @@ const MEMBER_PROJECTION_WRITE = {
847
856
  var _customRoles_get;
848
857
  return [
849
858
  orgRef.collection('members').doc(member.$id),
850
- {
859
+ _extends({
851
860
  scopeTokens: projectMemberScopeTokens(member),
852
861
  resolvedPermissions: projectMemberResolvedPermissions(member, // `?? null`, never `?? undefined`: a member whose `roleId`
853
862
  // points at a DELETED role must resolve to their role
@@ -856,7 +865,7 @@ const MEMBER_PROJECTION_WRITE = {
856
865
  // dangling id. Leaving it undefined would be the same value,
857
866
  // but the null says the lookup happened and missed.
858
867
  member.roleId ? (_customRoles_get = customRoles.get(member.roleId)) != null ? _customRoles_get : null : null)
859
- },
868
+ }, orgMemberListFields(member)),
860
869
  MEMBER_PROJECTION_WRITE
861
870
  ];
862
871
  })
@@ -904,6 +913,11 @@ const MEMBER_PROJECTION_WRITE = {
904
913
  } : {}, target.versionId ? {
905
914
  versionId: target.versionId
906
915
  } : {}),
916
+ // What the log's search box finds the entry by (AGL-3321).
917
+ searchTokens: activitySearchTokens({
918
+ actorEmail: actor.email,
919
+ target
920
+ }),
907
921
  createdAt: FieldValue.serverTimestamp()
908
922
  }).catch(()=>undefined);
909
923
  }
@@ -945,6 +959,13 @@ const MEMBER_PROJECTION_WRITE = {
945
959
  } : {}, target.versionId ? {
946
960
  versionId: target.versionId
947
961
  } : {}),
962
+ // What the log's search box finds the entry by (AGL-3321): the key's
963
+ // name stands in for an address an integration does not have.
964
+ searchTokens: activitySearchTokens({
965
+ actorEmail: actor.email,
966
+ apiKeyName: actor.apiKeyName,
967
+ target
968
+ }),
948
969
  createdAt: FieldValue.serverTimestamp()
949
970
  })).catch(()=>undefined);
950
971
  }
@@ -1472,7 +1493,16 @@ const MEMBER_PROJECTION_WRITE = {
1472
1493
  patch['photoURL'] = photoURL;
1473
1494
  }
1474
1495
  if (!Object.keys(patch).length) return [];
1475
- await ref.set(patch, {
1496
+ // A filled name is a name the roster's search finds (AGL-3321); a photo
1497
+ // alone changes nothing the search reads.
1498
+ const searchTokens = patch['displayName'] ? {
1499
+ searchTokens: orgMemberSearchTokens({
1500
+ displayName: patch['displayName'],
1501
+ email: snapshot.get('email'),
1502
+ title: snapshot.get('title')
1503
+ })
1504
+ } : {};
1505
+ await ref.set(_extends({}, patch, searchTokens), {
1476
1506
  merge: true
1477
1507
  });
1478
1508
  return Object.keys(patch);