@tearleads/client-sdk 0.1.22 → 0.1.24
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/client/organizations/organizationGroupHistory.js +4 -7
- package/client/organizations/organizationGroupHistory.js.map +1 -1
- package/client/organizations/organizationReadModels.js +2 -86
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/principalMutations.js +53 -133
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/principalMutationDispatch.js +2 -2
- package/client/principalMutationDispatch.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicyVerification.js +5 -5
- package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
- package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js +21 -7
- package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js.map +1 -1
- package/data/keyingProjectionVerification/types.d.ts +1 -8
- package/data/keyingProjectionVerification/types.js +0 -9
- package/data/keyingProjectionVerification/types.js.map +1 -1
- package/data/keyingProjectionVerification.d.ts +1 -1
- package/data/keyingProjectionVerification.js.map +1 -1
- package/data/persistence/documents/documentsPersistence.js +7 -0
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/data/persistence/documents/orphanBlobPersistence.d.ts +13 -0
- package/data/persistence/documents/orphanBlobPersistence.js +2 -0
- package/data/persistence/documents/orphanBlobPersistence.js.map +1 -0
- package/data/persistence/documents/types.d.ts +2 -0
- package/data/persistence/documents/types.js.map +1 -1
- package/data/persistence/principalHistoryPrefixPersistence.d.ts +5 -1
- package/data/persistence/principalHistoryPrefixPersistence.js +22 -5
- package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -1
- package/data/principals/principalMutationJournalShape.d.ts +1 -1
- package/data/principals/principalMutationJournalShape.js +2 -2
- package/data/principals/principalMutationJournalShape.js.map +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/attachmentHydration.js +2 -2
- package/stores/documents/documentStore/attachmentHydration.js.map +1 -1
- package/stores/documents/documentStore/attachments.js +7 -5
- package/stores/documents/documentStore/attachments.js.map +1 -1
- package/stores/documents/documentStore/discard.js +3 -2
- package/stores/documents/documentStore/discard.js.map +1 -1
- package/stores/documents/documentStore/orphanMaintenance.js +3 -5
- package/stores/documents/documentStore/orphanMaintenance.js.map +1 -1
- package/stores/documents/documentStore/persistence.js +3 -4
- package/stores/documents/documentStore/persistence.js.map +1 -1
- package/stores/documents/documentStore/syncDetachedAttachments.js +3 -2
- package/stores/documents/documentStore/syncDetachedAttachments.js.map +1 -1
- package/stores/documents/documentStore/syncRequest.js +3 -4
- package/stores/documents/documentStore/syncRequest.js.map +1 -1
- package/workflows/container-contents/container-state/groupGrantVerification.js +23 -74
- package/workflows/container-contents/container-state/groupGrantVerification.js.map +1 -1
- package/workflows/container-contents/container-state/groupShareEpoch.js +6 -23
- package/workflows/container-contents/container-state/groupShareEpoch.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +5 -3
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/types.js.map +1 -1
- package/workflows/container-contents/documentLinks.d.ts +1 -1
- package/workflows/container-contents/documentLinks.js.map +1 -1
- package/workflows/container-contents/documentPurge.d.ts +1 -1
- package/workflows/container-contents/documentPurge.js +4 -4
- package/workflows/container-contents/documentPurge.js.map +1 -1
- package/workflows/container-contents/metadataRemoteSync.d.ts +1 -1
- package/workflows/container-contents/metadataRemoteSync.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +2 -2
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/remoteHydration/verifiedDestination.js +6 -7
- package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +1 -1
- package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
- package/workflows/containers/child/runtimeCurrentGroupShare.js.map +1 -1
- package/workflows/documents/orphanBlobReclaimState.js +20 -0
- package/workflows/documents/orphanBlobReclaimState.js.map +1 -0
- package/workflows/documents/orphanBlobReclaims.d.ts +3 -2
- package/workflows/documents/orphanBlobReclaims.js +49 -47
- package/workflows/documents/orphanBlobReclaims.js.map +1 -1
- package/workflows/organizations/groupMetadataRuntime.js +11 -8
- package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
- package/workflows/organizations/organizationGroupNames.js +8 -55
- package/workflows/organizations/organizationGroupNames.js.map +1 -1
- package/workflows/organizations/principalOperationReceipt.js +1 -1
- package/workflows/organizations/principalOperationReceipt.js.map +1 -1
- package/workflows/organizations/runtimeGroupMetadataAuthority.js +16 -0
- package/workflows/organizations/runtimeGroupMetadataAuthority.js.map +1 -0
- package/workflows/principals/runtimePolicyWarmer.js +29 -27
- package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifiedDestination.js","sourceRoot":"","sources":["verifiedDestination.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6CAA6C,EAAE,MAAM,2CAA2C,CAAC;AAC1G,OAAO,EAEL,iCAAiC,GAClC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,+BAA+B,EAAE,MAAM,oEAAoE,CAAC;AACrH,OAAO,EAAE,oCAAoC,EAAE,MAAM,6EAA6E,CAAC;AACnI,OAAO,EAAE,+BAA+B,EAAE,MAAM,4EAA4E,CAAC;AAC7H,OAAO,EACL,yBAAyB,EACzB,yCAAyC,EACzC,gCAAgC,GACjC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,oCAAoC,EAAE,MAAM,qDAAqD,CAAC;AAC3G,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAE1F,OAAO,EACL,qBAAqB,EAErB,uBAAuB,GACxB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,6BAA6B,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,iCAAiC,EAAE,MAAM,sB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C;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport {\n type HeldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../data/containers/containerBinding\";\nimport { verifiedContainerCreateManifest } from \"../../../data/keyingProjectionVerification/containerCreateManifest\";\nimport { verifyContainerDestinationProjection } from \"../../../data/keyingProjectionVerification/containerDestinationVerification\";\nimport { verifyContainerWriterProjection } from \"../../../data/keyingProjectionVerification/containerProjectionVerification\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n runWithSecurityIncidentReporting,\n} from \"../../../data/keyingProjectionVerification/error\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport type { PrefetchedDestinationProjection } from \"./destinationPrefetch\";\nimport {\n cachedDestinationRole,\n type DestinationRole,\n rememberDestinationRole,\n} from \"./destinationRoleCache\";\nimport { resolveWithMetadataRootReload } from \"./destinationRootReload\";\nimport { assertPermittedDestinationBinding } from \"./replacementBinding\";\nimport type {\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationState,\n} from \"./types\";\n\n/** The identity a role is verified and cached under. */\ntype DestinationIdentity = Pick<RemoteContainer, \"id\" | \"organizationId\">;\n\nasync function destinationRoleFromPath(input: {\n listed: DestinationIdentity;\n path: readonly VerifiedContainerAccessManifest[];\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): Promise<{ role: DestinationRole; parentId: string | null }> {\n const { listed, path } = input;\n const head = path.at(-1);\n if (\n !head ||\n head.state.containerId !== listed.id ||\n head.state.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination manifest has the wrong identity\",\n );\n }\n const metadataSlot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: listed.organizationId,\n });\n if (\n head.state.systemSlot !== null &&\n path.length !== (head.state.systemSlot === metadataSlot ? 1 : 2)\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"system destination has the wrong signed topology\",\n );\n }\n // The head may be a later grant signed by any admin; only the epoch-1\n // create names the creator, and roots are always created by the org owner.\n const created = verifiedContainerCreateManifest({\n head,\n label: \"Container destination\",\n verifiedByHash: input.verifiedByHash,\n });\n const root = path[0];\n if (!root) throw new Error(\"Destination root is unavailable\");\n const rootCreated = verifiedContainerCreateManifest({\n head: root,\n label: \"Destination root\",\n verifiedByHash: input.verifiedByHash,\n });\n return {\n parentId: head.state.parentContainerId,\n role: {\n createSignerUserId: created.event.event.signerUserId,\n rootContainerId: rootCreated.state.containerId,\n rootCreateManifestHash: rootCreated.manifestHash,\n rootMetadataDocumentId: rootCreated.state.metadataDocumentId,\n metadataDocumentId: head.state.metadataDocumentId,\n ...(head.state.parentContainerId === null ||\n head.state.systemSlot !== null\n ? { parentId: head.state.parentContainerId }\n : {}),\n systemSlot: head.state.systemSlot,\n },\n };\n}\n\n/**\n * The session's root id arrives in an unsigned login response, so the root it\n * names must prove it belongs to this user: every acknowledged organization was\n * created by the session user, whose device signed the root's `container.create`.\n * A verified root created by anyone else is a substitution, never the merge\n * target for pre-login local content, whatever grants it carries. The check\n * runs on cache reuse too, since the cache is not scoped to the session user.\n */\nfunction assertRootCreatedBySessionUser(\n role: DestinationRole,\n runtime: RemoteContainerHydrationState[\"runtime\"],\n): void {\n if (role.systemSlot !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"acknowledged session root cannot be a system container\",\n );\n }\n if (role.createSignerUserId !== runtime.auth.userId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"acknowledged session root was not created by the session user\",\n );\n }\n}\n\nfunction assertAcknowledgedRootSigner(input: {\n listed: DestinationIdentity;\n role: DestinationRole;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): void {\n const { listed, role, runtime } = input;\n if (role.parentId !== null || listed.id !== runtime.auth.rootContainerId) {\n return;\n }\n assertRootCreatedBySessionUser(role, runtime);\n}\n\n/**\n * Authenticate destination roles before admitting a binding or advancing any\n * placement pin. Shared rehomes additionally require signed replacement evidence.\n */\nasync function verifyDestinationRole(input: {\n heldBinding: HeldContainerBinding | null;\n prefetched: PrefetchedDestinationProjection | undefined;\n verifyCurrentPlacement: boolean;\n onVerifiedCheckpoint:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n isCurrent?: (() => boolean) | undefined;\n listed: DestinationIdentity;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): Promise<{ role: DestinationRole; parentId: string | null } | null> {\n const { isCurrent, listed, runtime } = input;\n const projection = input.prefetched\n ? input.prefetched.projection\n : await runtime.apiClient.getContainerWriterProjection(listed.id);\n if (!projection || isCurrent?.() === false) return null;\n if (\n projection.containerId !== listed.id ||\n projection.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination projection has the wrong identity\",\n );\n }\n const verificationInput = {\n execSql: runtime.infra.execSql,\n projection,\n resolveUserKey: runtime.resolveTrustedUserIdentity,\n stillCurrent: isCurrent,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n };\n const { path, verifiedByHash } =\n await verifyContainerDestinationProjection(verificationInput);\n if (isCurrent?.() === false) return null;\n const destination = await destinationRoleFromPath({\n listed,\n path,\n verifiedByHash,\n });\n const { role } = destination;\n // Refuse a rebinding before group checks or placement pins run for it.\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (role.parentId === null && role.systemSlot !== null) {\n const head = path.at(-1);\n if (!head) throw new Error(\"Metadata root manifest is unavailable\");\n await createGroupMetadataContainerVerifier({\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId: listed.organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: isCurrent ?? (() => true),\n })(head.state);\n }\n if (isCurrent?.() === false) return null;\n if (input.verifyCurrentPlacement) {\n // Check the immutable role before allowing current placement to advance pins.\n assertAcknowledgedRootSigner({ listed, role, runtime });\n const currentPath = await verifyContainerWriterProjection({\n ...verificationInput,\n stillCurrent: isCurrent,\n });\n const currentHead = currentPath.at(-1);\n if (!currentHead)\n throw new Error(\"Recovery placement manifest is unavailable\");\n input.onVerifiedCheckpoint?.(currentHead.checkpoint);\n }\n if (isCurrent?.() === false) return null;\n return destination;\n}\n\ntype VerifyRemoteContainerDestinationInput = {\n heldBinding: HeldContainerBinding | null;\n /** The held folder was re-homed away from the listed organization. */\n supersededListing?: boolean | undefined;\n /** Fetched ahead by page hydration; ignored when placement is refreshed. */\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n refresh?: boolean;\n onVerifiedCheckpoint?:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n isCurrent?: (() => boolean) | undefined;\n};\n\n/** A cached immutable role, or a freshly verified one with its signed parent. */\nasync function resolveDestinationRole(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<{\n freshlyVerified: boolean;\n parentId: string | null | undefined;\n role: DestinationRole;\n} | null> {\n const { remoteContainer: listed, isCurrent } = input;\n const runtime = input.state.runtime;\n const cached = input.refresh\n ? undefined\n : cachedDestinationRole(runtime.infra.execSql, listed);\n // Ordinary parent edges are not immutable. A refresh authenticates current\n // placement; a forged root hint must also be corrected from a signed path.\n if (cached && !(cached.parentId === undefined && listed.parentId === null)) {\n return { freshlyVerified: false, parentId: cached.parentId, role: cached };\n }\n const verified = await verifyDestinationRole({\n heldBinding: input.heldBinding,\n prefetched: input.refresh ? undefined : input.prefetchedProjection,\n isCurrent,\n listed,\n runtime,\n verifyCurrentPlacement: input.refresh === true,\n onVerifiedCheckpoint: input.onVerifiedCheckpoint,\n });\n if (!verified) return null;\n return {\n freshlyVerified: true,\n parentId:\n input.refresh || listed.parentId === null\n ? verified.parentId\n : verified.role.parentId,\n role: verified.role,\n };\n}\n\n/**\n * Listing hints never establish a metadata target or a system/root role, and a\n * held folder keeps its organization and metadata target unless its own user\n * re-created it or its pinned founder authorized a verified replacement.\n * A conflicting proof is refused before placement pins\n * advance or its role is cached.\n */\nexport async function verifyRemoteContainerDestination(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<RemoteContainer | null> {\n const { remoteContainer: listed, state, isCurrent } = input;\n const runtime = state.runtime;\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: listed.id,\n objectKind: \"container\",\n operation: \"container.destination.verify\",\n organizationId: listed.organizationId,\n },\n async () => {\n if (input.supersededListing) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container was re-homed away from the listed organization\",\n );\n }\n // A held ordinary binding was verified (or signed by this device) when\n // it was stored; a listing that repeats it needs no second proof.\n if (\n !input.refresh &&\n listingRepeatsHeldOrdinaryBinding(input.heldBinding, listed)\n ) {\n return { ...listed, systemSlot: null };\n }\n if (input.refresh)\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n // A metadata root read before a reserved-group commit is reloaded once.\n const resolved = await resolveWithMetadataRootReload(\n input,\n resolveDestinationRole,\n () => runtime.apiClient.evictContainerWriterProjection(listed.id),\n ).catch((error: unknown) => {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error))\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n throw error;\n });\n if (!resolved || isCurrent?.() === false) return null;\n const { role, parentId } = resolved;\n // Fresh verification checked this binding before any placement pins.\n // A cached role still needs the held binding and replacement proof checked.\n if (!resolved.freshlyVerified)\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (resolved.freshlyVerified)\n rememberDestinationRole(runtime.infra.execSql, listed, role);\n assertAcknowledgedRootSigner({ listed, role, runtime });\n return {\n ...listed,\n metadataDocumentId: role.metadataDocumentId,\n parentId: parentId === undefined ? listed.parentId : parentId,\n systemSlot: role.systemSlot,\n };\n },\n );\n}\n\n/** The root the unsigned login answer named, in the expected organization. */\nexport function isSessionRootState(\n remoteRootState: ContainerState,\n state: RemoteContainerHydrationState,\n): boolean {\n const { container } = remoteRootState;\n const { auth } = state.runtime;\n return (\n container.parentId === null &&\n !container.systemSlot &&\n container.id === auth.rootContainerId &&\n container.organizationId === auth.organizationId\n );\n}\n\n/**\n * Whether the session root may absorb the pre-login local roots. The unsigned\n * login answer only names the root; the merge target must also be the verified\n * root whose epoch-1 `container.create` the session user signed. A row persisted\n * earlier as an ordinary shared container (another user's root this device once\n * hydrated) never passed that check for this session, so the creator is checked\n * here, at the reconciliation boundary itself, before any local content is\n * re-parented. The role comes only from the cache remote hydration fills when\n * it verifies the destination: this gate never fetches, so a local refresh stays\n * independent of the network. Without a cached role the merge is left pending\n * (no incident) until hydration verifies the root and reconciles from the\n * cache. A different creator is a `signer_mismatch` incident and never a merge;\n * the refusal is the \"no merge\" outcome, so the refresh that carried it\n * completes with the local content left in place.\n */\nexport async function isVerifiedLocalRootReconciliationTarget(input: {\n remoteRootState: ContainerState;\n state: RemoteContainerHydrationState;\n}): Promise<boolean> {\n const { remoteRootState, state } = input;\n const { container } = remoteRootState;\n const runtime = state.runtime;\n if (!isSessionRootState(remoteRootState, state)) return false;\n const role = cachedDestinationRole(runtime.infra.execSql, container);\n if (!role) return false;\n try {\n if (role.parentId !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"session root reconciliation target is not a verified root\",\n );\n }\n assertRootCreatedBySessionUser(role, runtime);\n return true;\n } catch (error) {\n const reported = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: container.id,\n objectKind: \"container\",\n operation: \"container.root.reconcile\",\n organizationId: container.organizationId,\n },\n );\n if (!reported) throw error;\n return false;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"verifiedDestination.js","sourceRoot":"","sources":["verifiedDestination.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6CAA6C,EAAE,MAAM,2CAA2C,CAAC;AAC1G,OAAO,EAEL,iCAAiC,GAClC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,+BAA+B,EAAE,MAAM,oEAAoE,CAAC;AACrH,OAAO,EAAE,oCAAoC,EAAE,MAAM,6EAA6E,CAAC;AACnI,OAAO,EAAE,+BAA+B,EAAE,MAAM,4EAA4E,CAAC;AAC7H,OAAO,EACL,yBAAyB,EACzB,yCAAyC,EACzC,gCAAgC,GACjC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,mCAAmC,EAAE,MAAM,mDAAmD,CAAC;AACxG,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAE1F,OAAO,EACL,qBAAqB,EAErB,uBAAuB,GACxB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,6BAA6B,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,iCAAiC,EAAE,MAAM,sBAAsB,CAAC;AAUzE,KAAK,UAAU,uBAAuB,CAAC,KAItC;IACC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC;IAC/B,MAAM,IAAI,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACzB,IACE,CAAC,IAAI;QACL,IAAI,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC,EAAE;QACpC,IAAI,CAAC,KAAK,CAAC,cAAc,KAAK,MAAM,CAAC,cAAc,EACnD,CAAC;QACD,MA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,CAAC;IAC9B,IAAI,CAAC,kBAAkB,CAAC,eAAe,EAAE,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,IAAI,GAAG,qBAAqB,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACrE,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IACxB,IAAI,CAAC;QACH,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;YAC3B,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,2DAA2D,CAC5D,CAAC;QACJ,CAAC;QACD,8BAA8B,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,KAAK,EACL,OAAO,CAAC,IAAI,CAAC,sBAAsB,EACnC;YACE,QAAQ,EAAE,SAAS,CAAC,EAAE;YACtB,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,0BAA0B;YACrC,cAAc,EAAE,SAAS,CAAC,cAAc;SACzC,CACF,CAAC;QACF,IAAI,CAAC,QAAQ;YAAE,MAAM,KAAK,CAAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport {\n type HeldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../data/containers/containerBinding\";\nimport { verifiedContainerCreateManifest } from \"../../../data/keyingProjectionVerification/containerCreateManifest\";\nimport { verifyContainerDestinationProjection } from \"../../../data/keyingProjectionVerification/containerDestinationVerification\";\nimport { verifyContainerWriterProjection } from \"../../../data/keyingProjectionVerification/containerProjectionVerification\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n runWithSecurityIncidentReporting,\n} from \"../../../data/keyingProjectionVerification/error\";\nimport { verifyRuntimeGroupMetadataAuthority } from \"../../organizations/runtimeGroupMetadataAuthority\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport type { PrefetchedDestinationProjection } from \"./destinationPrefetch\";\nimport {\n cachedDestinationRole,\n type DestinationRole,\n rememberDestinationRole,\n} from \"./destinationRoleCache\";\nimport { resolveWithMetadataRootReload } from \"./destinationRootReload\";\nimport { assertPermittedDestinationBinding } from \"./replacementBinding\";\nimport type {\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationState,\n} from \"./types\";\n\n/** The identity a role is verified and cached under. */\ntype DestinationIdentity = Pick<RemoteContainer, \"id\" | \"organizationId\">;\n\nasync function destinationRoleFromPath(input: {\n listed: DestinationIdentity;\n path: readonly VerifiedContainerAccessManifest[];\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): Promise<{ role: DestinationRole; parentId: string | null }> {\n const { listed, path } = input;\n const head = path.at(-1);\n if (\n !head ||\n head.state.containerId !== listed.id ||\n head.state.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination manifest has the wrong identity\",\n );\n }\n const metadataSlot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: listed.organizationId,\n });\n if (\n head.state.systemSlot !== null &&\n path.length !== (head.state.systemSlot === metadataSlot ? 1 : 2)\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"system destination has the wrong signed topology\",\n );\n }\n // The head may be a later grant signed by any admin; only the epoch-1\n // create names the creator, and roots are always created by the org owner.\n const created = verifiedContainerCreateManifest({\n head,\n label: \"Container destination\",\n verifiedByHash: input.verifiedByHash,\n });\n const root = path[0];\n if (!root) throw new Error(\"Destination root is unavailable\");\n const rootCreated = verifiedContainerCreateManifest({\n head: root,\n label: \"Destination root\",\n verifiedByHash: input.verifiedByHash,\n });\n return {\n parentId: head.state.parentContainerId,\n role: {\n createSignerUserId: created.event.event.signerUserId,\n rootContainerId: rootCreated.state.containerId,\n rootCreateManifestHash: rootCreated.manifestHash,\n rootMetadataDocumentId: rootCreated.state.metadataDocumentId,\n metadataDocumentId: head.state.metadataDocumentId,\n ...(head.state.parentContainerId === null ||\n head.state.systemSlot !== null\n ? { parentId: head.state.parentContainerId }\n : {}),\n systemSlot: head.state.systemSlot,\n },\n };\n}\n\n/**\n * The session's root id arrives in an unsigned login response, so the root it\n * names must prove it belongs to this user: every acknowledged organization was\n * created by the session user, whose device signed the root's `container.create`.\n * A verified root created by anyone else is a substitution, never the merge\n * target for pre-login local content, whatever grants it carries. The check\n * runs on cache reuse too, since the cache is not scoped to the session user.\n */\nfunction assertRootCreatedBySessionUser(\n role: DestinationRole,\n runtime: RemoteContainerHydrationState[\"runtime\"],\n): void {\n if (role.systemSlot !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"acknowledged session root cannot be a system container\",\n );\n }\n if (role.createSignerUserId !== runtime.auth.userId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"acknowledged session root was not created by the session user\",\n );\n }\n}\n\nfunction assertAcknowledgedRootSigner(input: {\n listed: DestinationIdentity;\n role: DestinationRole;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): void {\n const { listed, role, runtime } = input;\n if (role.parentId !== null || listed.id !== runtime.auth.rootContainerId) {\n return;\n }\n assertRootCreatedBySessionUser(role, runtime);\n}\n\n/**\n * Authenticate destination roles before admitting a binding or advancing any\n * placement pin. Shared rehomes additionally require signed replacement evidence.\n */\nasync function verifyDestinationRole(input: {\n heldBinding: HeldContainerBinding | null;\n prefetched: PrefetchedDestinationProjection | undefined;\n verifyCurrentPlacement: boolean;\n onVerifiedCheckpoint:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n isCurrent?: (() => boolean) | undefined;\n listed: DestinationIdentity;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): Promise<{ role: DestinationRole; parentId: string | null } | null> {\n const { isCurrent, listed, runtime } = input;\n const projection = input.prefetched\n ? input.prefetched.projection\n : await runtime.apiClient.getContainerWriterProjection(listed.id);\n if (!projection || isCurrent?.() === false) return null;\n if (\n projection.containerId !== listed.id ||\n projection.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination projection has the wrong identity\",\n );\n }\n const verificationInput = {\n execSql: runtime.infra.execSql,\n projection,\n resolveUserKey: runtime.resolveTrustedUserIdentity,\n stillCurrent: isCurrent,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n };\n const { path, verifiedByHash } =\n await verifyContainerDestinationProjection(verificationInput);\n if (isCurrent?.() === false) return null;\n const destination = await destinationRoleFromPath({\n listed,\n path,\n verifiedByHash,\n });\n const { role } = destination;\n // Refuse a rebinding before group checks or placement pins run for it.\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (role.parentId === null && role.systemSlot !== null) {\n const head = path.at(-1);\n if (!head) throw new Error(\"Metadata root manifest is unavailable\");\n await verifyRuntimeGroupMetadataAuthority({\n runtime,\n organizationId: listed.organizationId,\n organizationReference: projection.policyEvidence.organization?.head,\n state: head.state,\n stillCurrent: isCurrent ?? (() => true),\n });\n }\n if (isCurrent?.() === false) return null;\n if (input.verifyCurrentPlacement) {\n // Check the immutable role before allowing current placement to advance pins.\n assertAcknowledgedRootSigner({ listed, role, runtime });\n const currentPath = await verifyContainerWriterProjection({\n ...verificationInput,\n stillCurrent: isCurrent,\n });\n const currentHead = currentPath.at(-1);\n if (!currentHead)\n throw new Error(\"Recovery placement manifest is unavailable\");\n input.onVerifiedCheckpoint?.(currentHead.checkpoint);\n }\n if (isCurrent?.() === false) return null;\n return destination;\n}\n\ntype VerifyRemoteContainerDestinationInput = {\n heldBinding: HeldContainerBinding | null;\n /** The held folder was re-homed away from the listed organization. */\n supersededListing?: boolean | undefined;\n /** Fetched ahead by page hydration; ignored when placement is refreshed. */\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n refresh?: boolean;\n onVerifiedCheckpoint?:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n isCurrent?: (() => boolean) | undefined;\n};\n\n/** A cached immutable role, or a freshly verified one with its signed parent. */\nasync function resolveDestinationRole(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<{\n freshlyVerified: boolean;\n parentId: string | null | undefined;\n role: DestinationRole;\n} | null> {\n const { remoteContainer: listed, isCurrent } = input;\n const runtime = input.state.runtime;\n const cached = input.refresh\n ? undefined\n : cachedDestinationRole(runtime.infra.execSql, listed);\n // Ordinary parent edges are not immutable. A refresh authenticates current\n // placement; a forged root hint must also be corrected from a signed path.\n if (cached && !(cached.parentId === undefined && listed.parentId === null)) {\n return { freshlyVerified: false, parentId: cached.parentId, role: cached };\n }\n const verified = await verifyDestinationRole({\n heldBinding: input.heldBinding,\n prefetched: input.refresh ? undefined : input.prefetchedProjection,\n isCurrent,\n listed,\n runtime,\n verifyCurrentPlacement: input.refresh === true,\n onVerifiedCheckpoint: input.onVerifiedCheckpoint,\n });\n if (!verified) return null;\n return {\n freshlyVerified: true,\n parentId:\n input.refresh || listed.parentId === null\n ? verified.parentId\n : verified.role.parentId,\n role: verified.role,\n };\n}\n\n/**\n * Listing hints never establish a metadata target or a system/root role, and a\n * held folder keeps its organization and metadata target unless its own user\n * re-created it or its pinned founder authorized a verified replacement.\n * A conflicting proof is refused before placement pins\n * advance or its role is cached.\n */\nexport async function verifyRemoteContainerDestination(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<RemoteContainer | null> {\n const { remoteContainer: listed, state, isCurrent } = input;\n const runtime = state.runtime;\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: listed.id,\n objectKind: \"container\",\n operation: \"container.destination.verify\",\n organizationId: listed.organizationId,\n },\n async () => {\n if (input.supersededListing) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container was re-homed away from the listed organization\",\n );\n }\n // A held ordinary binding was verified (or signed by this device) when\n // it was stored; a listing that repeats it needs no second proof.\n if (\n !input.refresh &&\n listingRepeatsHeldOrdinaryBinding(input.heldBinding, listed)\n ) {\n return { ...listed, systemSlot: null };\n }\n if (input.refresh)\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n // A metadata root read before a reserved-group commit is reloaded once.\n const resolved = await resolveWithMetadataRootReload(\n input,\n resolveDestinationRole,\n () => runtime.apiClient.evictContainerWriterProjection(listed.id),\n ).catch((error: unknown) => {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error))\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n throw error;\n });\n if (!resolved || isCurrent?.() === false) return null;\n const { role, parentId } = resolved;\n // Fresh verification checked this binding before any placement pins.\n // A cached role still needs the held binding and replacement proof checked.\n if (!resolved.freshlyVerified)\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (resolved.freshlyVerified)\n rememberDestinationRole(runtime.infra.execSql, listed, role);\n assertAcknowledgedRootSigner({ listed, role, runtime });\n return {\n ...listed,\n metadataDocumentId: role.metadataDocumentId,\n parentId: parentId === undefined ? listed.parentId : parentId,\n systemSlot: role.systemSlot,\n };\n },\n );\n}\n\n/** The root the unsigned login answer named, in the expected organization. */\nexport function isSessionRootState(\n remoteRootState: ContainerState,\n state: RemoteContainerHydrationState,\n): boolean {\n const { container } = remoteRootState;\n const { auth } = state.runtime;\n return (\n container.parentId === null &&\n !container.systemSlot &&\n container.id === auth.rootContainerId &&\n container.organizationId === auth.organizationId\n );\n}\n\n/**\n * Whether the session root may absorb the pre-login local roots. The unsigned\n * login answer only names the root; the merge target must also be the verified\n * root whose epoch-1 `container.create` the session user signed. A row persisted\n * earlier as an ordinary shared container (another user's root this device once\n * hydrated) never passed that check for this session, so the creator is checked\n * here, at the reconciliation boundary itself, before any local content is\n * re-parented. The role comes only from the cache remote hydration fills when\n * it verifies the destination: this gate never fetches, so a local refresh stays\n * independent of the network. Without a cached role the merge is left pending\n * (no incident) until hydration verifies the root and reconciles from the\n * cache. A different creator is a `signer_mismatch` incident and never a merge;\n * the refusal is the \"no merge\" outcome, so the refresh that carried it\n * completes with the local content left in place.\n */\nexport async function isVerifiedLocalRootReconciliationTarget(input: {\n remoteRootState: ContainerState;\n state: RemoteContainerHydrationState;\n}): Promise<boolean> {\n const { remoteRootState, state } = input;\n const { container } = remoteRootState;\n const runtime = state.runtime;\n if (!isSessionRootState(remoteRootState, state)) return false;\n const role = cachedDestinationRole(runtime.infra.execSql, container);\n if (!role) return false;\n try {\n if (role.parentId !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"session root reconciliation target is not a verified root\",\n );\n }\n assertRootCreatedBySessionUser(role, runtime);\n return true;\n } catch (error) {\n const reported = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: container.id,\n objectKind: \"container\",\n operation: \"container.root.reconcile\",\n organizationId: container.organizationId,\n },\n );\n if (!reported) throw error;\n return false;\n }\n}\n"]}
|
|
@@ -25,7 +25,7 @@ export function createRuntimeCurrentGroupShare(runtime) {
|
|
|
25
25
|
: {}),
|
|
26
26
|
recoverPendingPrincipalMutation: async (organizationId) => {
|
|
27
27
|
// Built-in clients supply journal recovery; standalone hosts retain
|
|
28
|
-
//
|
|
28
|
+
// responsibility for transport and exact-outcome recovery.
|
|
29
29
|
await api.recoverPendingPrincipalMutation?.(organizationId);
|
|
30
30
|
},
|
|
31
31
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtimeCurrentGroupShare.js","sourceRoot":"","sources":["runtimeCurrentGroupShare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,IAAI,KAAK,CAAC,WAAW,KAAK,KAAK,CAAC,WAAW;gBACnD,OAAO,uBAAuB,CAAC;oBAC7B,OAAO;oBACP,KAAK;oBACL,MAAM;oBACN,sBAAsB;iBACvB,CAAC,CAAC;YACL,MAAM,YAAY,GAAG,MAAM,mCAAmC,CAAC;gBAC7D,GAAG,KAAK;gBACR,kBAAkB;gBAClB,oBAAoB,EAClB,uCAAuC,CAAC,kBAAkB,CAAC;gBAC7D,SAAS,EAAE;oBACT,eAAe,EAAE,MAAM;oBACvB,SAAS,EAAE,KAAK,CAAC,gBAAgB;oBACjC,WAAW,EAAE,OAAO;iBACrB;gBACD,wBAAwB;aACzB,CAAC,CAAC;YACH,OAAO,mCAAmC,CAAC;gBACzC,GAAG,KAAK;gBACR,kBAAkB,EAAE,kBAAkB;gBACtC,sBAAsB;gBACtB,YAAY,EAAE,YAAY,CAAC,YAAY;gBACvC,IAAI,EAAE,YAAY,CAAC,IAAI;gBACvB,MAAM,EAAE,GAAG,EAAE,CACX,4BAA4B,CAAC,GAAG,EAAE,CAChC,KAAK,CAAC,SAAS,CAAC,cAAc,CAC5B,KAAK,CAAC,WAAW,EACjB,YAAY,CAAC,IAAI,CAAC,OAAO,EACzB;oBACE,qCAAqC,EACnC,KAAK,CAAC,MAAM,CAAC,cAAc;iBAC9B,CACF,CACF;aACJ,CAAC,CAAC;QACL,CAAC,CACF,CACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n nullOnProjectionVerificationCancellation,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { inheritPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryRuntime\";\nimport { createRuntimeCurrentGroupMutation } from \"../../organizations/runtimeCurrentGroupMutation\";\nimport { commitCurrentShareGrant } from \"./currentShareGrantMutation\";\nimport { createRuntimeCurrentSharePrincipalPolicy } from \"./currentSharePrincipalPolicy\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"./mutationSubmit\";\nimport type { shareRemoteContainerWithGroup } from \"./share\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport { resolveShareProjection } from \"./shareProjection\";\n\n/** Current evidence covers planning, any compound grant mint, and acknowledgement. */\nexport function createRuntimeCurrentGroupShare(\n runtime: Parameters<typeof createRuntimeCurrentSharePrincipalPolicy>[0],\n): typeof shareRemoteContainerWithGroup | undefined {\n const readCurrent = createRuntimeCurrentSharePrincipalPolicy(runtime);\n const api = runtime.apiClient;\n const readPages = api.getPrincipalPolicyPages;\n if (!readCurrent || !readPages) return undefined;\n const mutate = createRuntimeCurrentGroupMutation(\n inheritPrincipalHistoryProtection(runtime, {\n ...runtime,\n apiClient: {\n getPrincipalPolicyPages: readPages.bind(api),\n ...(api.getProjectionPolicyHistoryPages\n ? {\n getProjectionPolicyHistoryPages:\n api.getProjectionPolicyHistoryPages.bind(api),\n }\n : {}),\n recoverPendingPrincipalMutation: async (organizationId: string) => {\n // Built-in clients supply journal recovery; standalone hosts retain\n // responsibility for transport and exact-outcome recovery.\n await api.recoverPendingPrincipalMutation?.(organizationId);\n },\n },\n }),\n );\n if (!mutate) throw new Error(\"Current group mutation custody is unavailable\");\n return async (input) => {\n if (input.stillCurrent?.() === false) return null;\n const recitationStillCurrent = input.stillCurrent ?? (() => true);\n return nullOnProjectionVerificationCancellation(() =>\n readCurrent(\n {\n expectedGroupName: input.expectedGroupName ?? undefined,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n },\n async ({ policy, checkpointPolicies, stillCurrent }) => {\n const share = { ...input, stillCurrent };\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n share,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const grant = policy.grants.find(\n (candidate) => candidate.containerId === input.containerId,\n );\n if (!grant || grant.accessLevel !== input.accessLevel)\n return commitCurrentShareGrant({\n runtime,\n share,\n mutate,\n recitationStillCurrent,\n });\n const materialized = await buildMaterializedContainerSharePlan({\n ...share,\n previousProjection,\n principalPolicyCache:\n principalPolicyCacheForVerifiedPolicies(checkpointPolicies),\n recipient: {\n principalPolicy: policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n });\n return submitAcknowledgedContainerMutation({\n ...share,\n recitationPolicies: checkpointPolicies,\n recitationStillCurrent,\n containerKey: materialized.containerKey,\n plan: materialized.plan,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materialized.plan.request,\n {\n expectedPaymentRequiredOrganizationId:\n input.author.organizationId,\n },\n ),\n ),\n });\n },\n ),\n );\n };\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const states = new WeakMap();
|
|
2
|
+
export function orphanBlobReclaimState(persistence, execSql) {
|
|
3
|
+
let connections = states.get(persistence);
|
|
4
|
+
if (!connections) {
|
|
5
|
+
connections = new WeakMap();
|
|
6
|
+
states.set(persistence, connections);
|
|
7
|
+
}
|
|
8
|
+
let state = connections.get(execSql);
|
|
9
|
+
if (!state) {
|
|
10
|
+
state = {
|
|
11
|
+
deferredStorageKeys: new Map(),
|
|
12
|
+
rerun: false,
|
|
13
|
+
running: undefined,
|
|
14
|
+
sweepKey: `sweep:document-orphans:${crypto.randomUUID()}`,
|
|
15
|
+
};
|
|
16
|
+
connections.set(execSql, state);
|
|
17
|
+
}
|
|
18
|
+
return state;
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=orphanBlobReclaimState.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orphanBlobReclaimState.js","sourceRoot":"","sources":["orphanBlobReclaimState.ts"],"names":[],"mappings":"AAUA,MAAM,MAAM,GAAG,IAAI,OAAO,EAGvB,CAAC;AAEJ,MAAM,UAAU,sBAAsB,CACpC,WAA0C,EAC1C,OAAgB;IAEhB,IAAI,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC1C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,CAAC,GAAG,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;IACvC,CAAC;IACD,IAAI,KAAK,GAAG,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,KAAK,GAAG;YACN,mBAAmB,EAAE,IAAI,GAAG,EAAE;YAC9B,KAAK,EAAE,KAAK;YACZ,OAAO,EAAE,SAAS;YAClB,QAAQ,EAAE,0BAA0B,MAAM,CAAC,UAAU,EAAE,EAAE;SAC1D,CAAC;QACF,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAClC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { DocumentOrphanBlobPersistence } from \"../../data/persistence/documents/orphanBlobPersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nexport interface OrphanBlobReclaimState {\n deferredStorageKeys: Map<string, number>;\n rerun: boolean;\n running: Promise<void> | undefined;\n sweepKey: string;\n}\n\nconst states = new WeakMap<\n DocumentOrphanBlobPersistence,\n WeakMap<ExecSql, OrphanBlobReclaimState>\n>();\n\nexport function orphanBlobReclaimState(\n persistence: DocumentOrphanBlobPersistence,\n execSql: ExecSql,\n): OrphanBlobReclaimState {\n let connections = states.get(persistence);\n if (!connections) {\n connections = new WeakMap();\n states.set(persistence, connections);\n }\n let state = connections.get(execSql);\n if (!state) {\n state = {\n deferredStorageKeys: new Map(),\n rerun: false,\n running: undefined,\n sweepKey: `sweep:document-orphans:${crypto.randomUUID()}`,\n };\n connections.set(execSql, state);\n }\n return state;\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import type { DocumentsPersistence } from "../../data/persistence/documents/types.js";
|
|
1
2
|
import type { DocumentsWorkflowRuntimeGroups } from "./runtime.js";
|
|
2
3
|
type DocumentOrphanBlobReclaimRuntime = Pick<DocumentsWorkflowRuntimeGroups, "infra" | "util">;
|
|
3
|
-
/**
|
|
4
|
-
export declare function reclaimDocumentOrphanBlobs(runtime: DocumentOrphanBlobReclaimRuntime): Promise<void>;
|
|
4
|
+
/** Await all requested batches; maintenance failures never fail committed writes. */
|
|
5
|
+
export declare function reclaimDocumentOrphanBlobs(runtime: DocumentOrphanBlobReclaimRuntime, persistence?: DocumentsPersistence): Promise<void>;
|
|
5
6
|
export {};
|
|
@@ -1,17 +1,13 @@
|
|
|
1
1
|
import { errorMessage } from "../../data/errorMessage.js";
|
|
2
|
-
import { acknowledgeDocumentOrphanBlobReclaim, deleteOrphanedDocumentSideRows, isDocumentBlobStorageKeyReferenced, listDocumentOrphanBlobReclaims, } from "../../data/persistence/documents/internal/orphanSideRows.js";
|
|
3
2
|
import { resolveCanonicalExecSql, runOncePerConnection, runSerializedSqlMutation, } from "../../data/sqlite/sqlSchema.js";
|
|
4
3
|
import { runSerializedDocumentBlobMutation } from "./blobMutationLock.js";
|
|
4
|
+
import { orphanBlobReclaimState, } from "./orphanBlobReclaimState.js";
|
|
5
5
|
import { defaultDocumentsPersistence } from "./persistence.js";
|
|
6
|
-
const reclaimByExecSql = new WeakMap();
|
|
7
|
-
const reclaimRerunByExecSql = new WeakSet();
|
|
8
|
-
const deferredStorageKeysByExecSql = new WeakMap();
|
|
9
6
|
const ORPHAN_BLOB_RECLAIM_BATCH_SIZE = 16;
|
|
10
7
|
const ORPHAN_BLOB_RECLAIM_TIME_BUDGET_MS = 250;
|
|
11
8
|
const ORPHAN_BLOB_RECLAIM_RETRY_DELAY_MS = 30_000;
|
|
12
9
|
const ORPHAN_BLOB_RECLAIM_LOG_SAMPLE_SIZE = 3;
|
|
13
10
|
const ORPHAN_BLOB_RECLAIM_YIELD_MS = 16;
|
|
14
|
-
const DOCUMENT_ORPHAN_SWEEP_ONCE_KEY = "sweep:document-orphans";
|
|
15
11
|
function clearExpiredDeferredStorageKeys(deferredStorageKeys, now) {
|
|
16
12
|
for (const [storageKey, retryAt] of deferredStorageKeys) {
|
|
17
13
|
if (retryAt <= now)
|
|
@@ -23,38 +19,36 @@ function waitForMaintenanceYield() {
|
|
|
23
19
|
setTimeout(resolve, ORPHAN_BLOB_RECLAIM_YIELD_MS);
|
|
24
20
|
});
|
|
25
21
|
}
|
|
26
|
-
async function sweepAgedDocumentOrphans(execSql) {
|
|
22
|
+
async function sweepAgedDocumentOrphans(execSql, persistence, state) {
|
|
27
23
|
let swept = false;
|
|
28
|
-
await runOncePerConnection(execSql,
|
|
24
|
+
await runOncePerConnection(execSql, state.sweepKey, async () => {
|
|
29
25
|
swept = true;
|
|
30
|
-
while (await
|
|
26
|
+
while (await persistence.orphanBlobs.sweep(execSql)) {
|
|
31
27
|
await waitForMaintenanceYield();
|
|
32
28
|
}
|
|
33
29
|
});
|
|
34
30
|
return swept;
|
|
35
31
|
}
|
|
36
|
-
async function reclaimQueuedBlobs(runtime) {
|
|
32
|
+
async function reclaimQueuedBlobs(runtime, persistence, state) {
|
|
37
33
|
const execSql = runtime.infra.execSql;
|
|
38
|
-
await
|
|
34
|
+
await persistence.ensureSchema(execSql);
|
|
39
35
|
let shouldContinue = false;
|
|
40
36
|
const startedAt = Date.now();
|
|
41
|
-
const
|
|
42
|
-
const deferredStorageKeys = deferredStorageKeysByExecSql.get(canonicalExecSql) ??
|
|
43
|
-
new Map();
|
|
44
|
-
deferredStorageKeysByExecSql.set(canonicalExecSql, deferredStorageKeys);
|
|
37
|
+
const { deferredStorageKeys } = state;
|
|
45
38
|
const failedStorageKeys = [];
|
|
46
39
|
let warmedBlobStore = false;
|
|
47
40
|
let sweptAgedOrphans = false;
|
|
48
41
|
reclaimQueue: while (true) {
|
|
49
42
|
clearExpiredDeferredStorageKeys(deferredStorageKeys, Date.now());
|
|
50
|
-
const queuedStorageKeys = await
|
|
43
|
+
const queuedStorageKeys = await persistence.orphanBlobs.list(execSql, ORPHAN_BLOB_RECLAIM_BATCH_SIZE + deferredStorageKeys.size);
|
|
51
44
|
const storageKeys = queuedStorageKeys
|
|
52
45
|
.filter((storageKey) => !deferredStorageKeys.has(storageKey))
|
|
53
46
|
.slice(0, ORPHAN_BLOB_RECLAIM_BATCH_SIZE);
|
|
54
47
|
if (storageKeys.length === 0) {
|
|
55
48
|
// Explicit delete paths get priority. Once their queue is drained, sweep
|
|
56
49
|
// crash residue once per connection and immediately drain what it queues.
|
|
57
|
-
if (!sweptAgedOrphans &&
|
|
50
|
+
if (!sweptAgedOrphans &&
|
|
51
|
+
(await sweepAgedDocumentOrphans(execSql, persistence, state))) {
|
|
58
52
|
sweptAgedOrphans = true;
|
|
59
53
|
continue;
|
|
60
54
|
}
|
|
@@ -72,8 +66,8 @@ async function reclaimQueuedBlobs(runtime) {
|
|
|
72
66
|
for (const storageKey of storageKeys) {
|
|
73
67
|
await runSerializedDocumentBlobMutation(execSql, storageKey, async () => {
|
|
74
68
|
const shouldDelete = await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
75
|
-
if (await
|
|
76
|
-
await
|
|
69
|
+
if (await persistence.orphanBlobs.isReferenced(lockedExecSql, storageKey)) {
|
|
70
|
+
await persistence.orphanBlobs.acknowledge(lockedExecSql, storageKey);
|
|
77
71
|
return false;
|
|
78
72
|
}
|
|
79
73
|
return true;
|
|
@@ -82,7 +76,7 @@ async function reclaimQueuedBlobs(runtime) {
|
|
|
82
76
|
return;
|
|
83
77
|
try {
|
|
84
78
|
await runtime.infra.blobStore.deleteBytes(storageKey);
|
|
85
|
-
await runSerializedSqlMutation(execSql, (lockedExecSql) =>
|
|
79
|
+
await runSerializedSqlMutation(execSql, (lockedExecSql) => persistence.orphanBlobs.acknowledge(lockedExecSql, storageKey));
|
|
86
80
|
}
|
|
87
81
|
catch {
|
|
88
82
|
failedStorageKeys.push(storageKey);
|
|
@@ -95,9 +89,6 @@ async function reclaimQueuedBlobs(runtime) {
|
|
|
95
89
|
}
|
|
96
90
|
}
|
|
97
91
|
}
|
|
98
|
-
if (deferredStorageKeys.size === 0) {
|
|
99
|
-
deferredStorageKeysByExecSql.delete(canonicalExecSql);
|
|
100
|
-
}
|
|
101
92
|
if (failedStorageKeys.length > 0) {
|
|
102
93
|
const sample = failedStorageKeys
|
|
103
94
|
.slice(0, ORPHAN_BLOB_RECLAIM_LOG_SAMPLE_SIZE)
|
|
@@ -106,36 +97,47 @@ async function reclaimQueuedBlobs(runtime) {
|
|
|
106
97
|
}
|
|
107
98
|
return shouldContinue;
|
|
108
99
|
}
|
|
109
|
-
|
|
110
|
-
export function reclaimDocumentOrphanBlobs(runtime) {
|
|
100
|
+
function runDocumentOrphanReclaims(runtime, persistence = defaultDocumentsPersistence) {
|
|
111
101
|
if (runtime.infra.dbStatus !== "ready") {
|
|
112
102
|
return Promise.resolve();
|
|
113
103
|
}
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
return existing;
|
|
104
|
+
const state = orphanBlobReclaimState(persistence.orphanBlobs, resolveCanonicalExecSql(runtime.infra.execSql));
|
|
105
|
+
if (state.running) {
|
|
106
|
+
state.rerun = true;
|
|
107
|
+
return state.running;
|
|
119
108
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
}
|
|
109
|
+
const reclaim = (async () => {
|
|
110
|
+
try {
|
|
111
|
+
let hasMore;
|
|
112
|
+
do {
|
|
113
|
+
state.rerun = false;
|
|
114
|
+
hasMore = false;
|
|
115
|
+
try {
|
|
116
|
+
hasMore = await reclaimQueuedBlobs(runtime, persistence, state);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
const message = errorMessage(error);
|
|
120
|
+
runtime.util.log(`Documents: orphan maintenance failed: ${message}`);
|
|
121
|
+
}
|
|
122
|
+
if (hasMore || state.rerun)
|
|
123
|
+
await waitForMaintenanceYield();
|
|
124
|
+
} while (hasMore || state.rerun);
|
|
136
125
|
}
|
|
137
|
-
|
|
138
|
-
|
|
126
|
+
finally {
|
|
127
|
+
state.running = undefined;
|
|
128
|
+
state.rerun = false;
|
|
129
|
+
}
|
|
130
|
+
})();
|
|
131
|
+
state.running = reclaim;
|
|
139
132
|
return reclaim;
|
|
140
133
|
}
|
|
134
|
+
/** Await all requested batches; maintenance failures never fail committed writes. */
|
|
135
|
+
export async function reclaimDocumentOrphanBlobs(runtime, persistence = defaultDocumentsPersistence) {
|
|
136
|
+
try {
|
|
137
|
+
await runDocumentOrphanReclaims(runtime, persistence);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
runtime.util.log(`Documents: orphan maintenance failed: ${errorMessage(error)}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
141
143
|
//# sourceMappingURL=orphanBlobReclaims.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orphanBlobReclaims.js","sourceRoot":"","sources":["orphanBlobReclaims.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EACL,oCAAoC,EACpC,8BAA8B,EAC9B,kCAAkC,EAClC,8BAA8B,GAC/B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAEL,uBAAuB,EACvB,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iCAAiC,EAAE,MAAM,oBAAoB,CAAC;AACvE,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAG5D,MAAM,gBAAgB,GAAG,IA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D,OAAO,CAAC,GAAG,EAAE;QACZ,gBAAgB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACjC,MAAM,iBAAiB,GAAG,qBAAqB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAChE,IAAI,cAAc,IAAI,iBAAiB,EAAE,CAAC;YACxC,UAAU,CAAC,GAAG,EAAE;gBACd,KAAK,0BAA0B,CAAC,OAAO,CAAC,CAAC;YAC3C,CAAC,EAAE,4BAA4B,CAAC,CAAC;QACnC,CAAC;IACH,CAAC,CAAC,CAAC;IACL,gBAAgB,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACvC,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { errorMessage } from \"../../data/errorMessage\";\nimport {\n acknowledgeDocumentOrphanBlobReclaim,\n deleteOrphanedDocumentSideRows,\n isDocumentBlobStorageKeyReferenced,\n listDocumentOrphanBlobReclaims,\n} from \"../../data/persistence/documents/internal/orphanSideRows\";\nimport {\n type ExecSql,\n resolveCanonicalExecSql,\n runOncePerConnection,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\nimport { runSerializedDocumentBlobMutation } from \"./blobMutationLock\";\nimport { defaultDocumentsPersistence } from \"./persistence\";\nimport type { DocumentsWorkflowRuntimeGroups } from \"./runtime\";\n\nconst reclaimByExecSql = new WeakMap<ExecSql, Promise<void>>();\nconst reclaimRerunByExecSql = new WeakSet<ExecSql>();\nconst deferredStorageKeysByExecSql = new WeakMap<\n ExecSql,\n Map<string, number>\n>();\nconst ORPHAN_BLOB_RECLAIM_BATCH_SIZE = 16;\nconst ORPHAN_BLOB_RECLAIM_TIME_BUDGET_MS = 250;\nconst ORPHAN_BLOB_RECLAIM_RETRY_DELAY_MS = 30_000;\nconst ORPHAN_BLOB_RECLAIM_LOG_SAMPLE_SIZE = 3;\nconst ORPHAN_BLOB_RECLAIM_YIELD_MS = 16;\nconst DOCUMENT_ORPHAN_SWEEP_ONCE_KEY = \"sweep:document-orphans\";\n\ntype DocumentOrphanBlobReclaimRuntime = Pick<\n DocumentsWorkflowRuntimeGroups,\n \"infra\" | \"util\"\n>;\n\nfunction clearExpiredDeferredStorageKeys(\n deferredStorageKeys: Map<string, number>,\n now: number,\n): void {\n for (const [storageKey, retryAt] of deferredStorageKeys) {\n if (retryAt <= now) deferredStorageKeys.delete(storageKey);\n }\n}\n\nfunction waitForMaintenanceYield(): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ORPHAN_BLOB_RECLAIM_YIELD_MS);\n });\n}\n\nasync function sweepAgedDocumentOrphans(execSql: ExecSql): Promise<boolean> {\n let swept = false;\n await runOncePerConnection(\n execSql,\n DOCUMENT_ORPHAN_SWEEP_ONCE_KEY,\n async () => {\n swept = true;\n while (await deleteOrphanedDocumentSideRows(execSql)) {\n await waitForMaintenanceYield();\n }\n },\n );\n return swept;\n}\n\nasync function reclaimQueuedBlobs(\n runtime: DocumentOrphanBlobReclaimRuntime,\n): Promise<boolean> {\n const execSql = runtime.infra.execSql;\n await defaultDocumentsPersistence.ensureSchema(execSql);\n let shouldContinue = false;\n\n const startedAt = Date.now();\n const canonicalExecSql = resolveCanonicalExecSql(execSql);\n const deferredStorageKeys =\n deferredStorageKeysByExecSql.get(canonicalExecSql) ??\n new Map<string, number>();\n deferredStorageKeysByExecSql.set(canonicalExecSql, deferredStorageKeys);\n const failedStorageKeys: string[] = [];\n let warmedBlobStore = false;\n let sweptAgedOrphans = false;\n\n reclaimQueue: while (true) {\n clearExpiredDeferredStorageKeys(deferredStorageKeys, Date.now());\n const queuedStorageKeys = await listDocumentOrphanBlobReclaims(\n execSql,\n ORPHAN_BLOB_RECLAIM_BATCH_SIZE + deferredStorageKeys.size,\n );\n const storageKeys = queuedStorageKeys\n .filter((storageKey) => !deferredStorageKeys.has(storageKey))\n .slice(0, ORPHAN_BLOB_RECLAIM_BATCH_SIZE);\n if (storageKeys.length === 0) {\n // Explicit delete paths get priority. Once their queue is drained, sweep\n // crash residue once per connection and immediately drain what it queues.\n if (!sweptAgedOrphans && (await sweepAgedDocumentOrphans(execSql))) {\n sweptAgedOrphans = true;\n continue;\n }\n break;\n }\n\n const firstStorageKey = storageKeys[0];\n if (!warmedBlobStore && firstStorageKey) {\n // Initialize lazy keyring/OPFS-backed stores before taking any blob-key\n // lock. A failed preview is harmless: deletion can still reclaim the key.\n await runtime.infra.blobStore\n .openByteSource(firstStorageKey)\n .catch(() => undefined);\n warmedBlobStore = true;\n }\n\n for (const storageKey of storageKeys) {\n await runSerializedDocumentBlobMutation(execSql, storageKey, async () => {\n const shouldDelete = await runSerializedSqlMutation(\n execSql,\n async (lockedExecSql) => {\n if (\n await isDocumentBlobStorageKeyReferenced(\n lockedExecSql,\n storageKey,\n )\n ) {\n await acknowledgeDocumentOrphanBlobReclaim(\n lockedExecSql,\n storageKey,\n );\n return false;\n }\n return true;\n },\n );\n if (!shouldDelete) return;\n try {\n await runtime.infra.blobStore.deleteBytes(storageKey);\n await runSerializedSqlMutation(execSql, (lockedExecSql) =>\n acknowledgeDocumentOrphanBlobReclaim(lockedExecSql, storageKey),\n );\n } catch {\n failedStorageKeys.push(storageKey);\n deferredStorageKeys.set(\n storageKey,\n Date.now() + ORPHAN_BLOB_RECLAIM_RETRY_DELAY_MS,\n );\n }\n });\n if (Date.now() - startedAt >= ORPHAN_BLOB_RECLAIM_TIME_BUDGET_MS) {\n shouldContinue = true;\n break reclaimQueue;\n }\n }\n }\n\n if (deferredStorageKeys.size === 0) {\n deferredStorageKeysByExecSql.delete(canonicalExecSql);\n }\n if (failedStorageKeys.length > 0) {\n const sample = failedStorageKeys\n .slice(0, ORPHAN_BLOB_RECLAIM_LOG_SAMPLE_SIZE)\n .join(\", \");\n runtime.util.log(\n `Documents: orphan maintenance deferred ${failedStorageKeys.length} blob(s): ${sample}`,\n );\n }\n return shouldContinue;\n}\n\n/** Sweep orphan rows and reclaim their queued local attachment bytes. */\nexport function reclaimDocumentOrphanBlobs(\n runtime: DocumentOrphanBlobReclaimRuntime,\n): Promise<void> {\n if (runtime.infra.dbStatus !== \"ready\") {\n return Promise.resolve();\n }\n const execSql = resolveCanonicalExecSql(runtime.infra.execSql);\n const existing = reclaimByExecSql.get(execSql);\n if (existing) {\n reclaimRerunByExecSql.add(execSql);\n return existing;\n }\n\n let shouldContinue = false;\n const reclaim = reclaimQueuedBlobs(runtime)\n .then((hasMore) => {\n shouldContinue = hasMore;\n })\n .catch((error: unknown) => {\n const message = errorMessage(error);\n runtime.util.log(`Documents: orphan maintenance failed: ${message}`);\n })\n .finally(() => {\n reclaimByExecSql.delete(execSql);\n const wasRerunRequested = reclaimRerunByExecSql.delete(execSql);\n if (shouldContinue || wasRerunRequested) {\n setTimeout(() => {\n void reclaimDocumentOrphanBlobs(runtime);\n }, ORPHAN_BLOB_RECLAIM_YIELD_MS);\n }\n });\n reclaimByExecSql.set(execSql, reclaim);\n return reclaim;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"orphanBlobReclaims.js","sourceRoot":"","sources":["orphanBlobReclaims.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAEvD,OAAO,EAEL,uBAAuB,EACvB,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iCAAiC,EAAE,MAAM,oBAAoB,CAAC;AACvE,OAAO,EAEL,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAG5D,MAAM,8BAA8B,GAAG,EAAE,CAAC;AAC1C,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAC/C,MAAM,kCAAkC,GAAG,MAAM,CAAC;AAClD,MAAM,mCAAmC,GAAG,CAAC,CAAC;AAC9C,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAOxC,SAAS,+BAA+B,CACtC,mBAAwC,EACxC,GAAW;IAEX,KAAK,MAAM,CAAC,UAAU,EAAE,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AAI,CAAC;QACH,MAAM,yBAAyB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;IACxD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,yCAAyC,YAAY,CAAC,KAAK,CAAC,EAAE,CAC/D,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { errorMessage } from \"../../data/errorMessage\";\nimport type { DocumentsPersistence } from \"../../data/persistence/documents/types\";\nimport {\n type ExecSql,\n resolveCanonicalExecSql,\n runOncePerConnection,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\nimport { runSerializedDocumentBlobMutation } from \"./blobMutationLock\";\nimport {\n type OrphanBlobReclaimState,\n orphanBlobReclaimState,\n} from \"./orphanBlobReclaimState\";\nimport { defaultDocumentsPersistence } from \"./persistence\";\nimport type { DocumentsWorkflowRuntimeGroups } from \"./runtime\";\n\nconst ORPHAN_BLOB_RECLAIM_BATCH_SIZE = 16;\nconst ORPHAN_BLOB_RECLAIM_TIME_BUDGET_MS = 250;\nconst ORPHAN_BLOB_RECLAIM_RETRY_DELAY_MS = 30_000;\nconst ORPHAN_BLOB_RECLAIM_LOG_SAMPLE_SIZE = 3;\nconst ORPHAN_BLOB_RECLAIM_YIELD_MS = 16;\n\ntype DocumentOrphanBlobReclaimRuntime = Pick<\n DocumentsWorkflowRuntimeGroups,\n \"infra\" | \"util\"\n>;\n\nfunction clearExpiredDeferredStorageKeys(\n deferredStorageKeys: Map<string, number>,\n now: number,\n): void {\n for (const [storageKey, retryAt] of deferredStorageKeys) {\n if (retryAt <= now) deferredStorageKeys.delete(storageKey);\n }\n}\n\nfunction waitForMaintenanceYield(): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ORPHAN_BLOB_RECLAIM_YIELD_MS);\n });\n}\n\nasync function sweepAgedDocumentOrphans(\n execSql: ExecSql,\n persistence: DocumentsPersistence,\n state: OrphanBlobReclaimState,\n): Promise<boolean> {\n let swept = false;\n await runOncePerConnection(execSql, state.sweepKey, async () => {\n swept = true;\n while (await persistence.orphanBlobs.sweep(execSql)) {\n await waitForMaintenanceYield();\n }\n });\n return swept;\n}\n\nasync function reclaimQueuedBlobs(\n runtime: DocumentOrphanBlobReclaimRuntime,\n persistence: DocumentsPersistence,\n state: OrphanBlobReclaimState,\n): Promise<boolean> {\n const execSql = runtime.infra.execSql;\n await persistence.ensureSchema(execSql);\n let shouldContinue = false;\n\n const startedAt = Date.now();\n const { deferredStorageKeys } = state;\n const failedStorageKeys: string[] = [];\n let warmedBlobStore = false;\n let sweptAgedOrphans = false;\n\n reclaimQueue: while (true) {\n clearExpiredDeferredStorageKeys(deferredStorageKeys, Date.now());\n const queuedStorageKeys = await persistence.orphanBlobs.list(\n execSql,\n ORPHAN_BLOB_RECLAIM_BATCH_SIZE + deferredStorageKeys.size,\n );\n const storageKeys = queuedStorageKeys\n .filter((storageKey) => !deferredStorageKeys.has(storageKey))\n .slice(0, ORPHAN_BLOB_RECLAIM_BATCH_SIZE);\n if (storageKeys.length === 0) {\n // Explicit delete paths get priority. Once their queue is drained, sweep\n // crash residue once per connection and immediately drain what it queues.\n if (\n !sweptAgedOrphans &&\n (await sweepAgedDocumentOrphans(execSql, persistence, state))\n ) {\n sweptAgedOrphans = true;\n continue;\n }\n break;\n }\n\n const firstStorageKey = storageKeys[0];\n if (!warmedBlobStore && firstStorageKey) {\n // Initialize lazy keyring/OPFS-backed stores before taking any blob-key\n // lock. A failed preview is harmless: deletion can still reclaim the key.\n await runtime.infra.blobStore\n .openByteSource(firstStorageKey)\n .catch(() => undefined);\n warmedBlobStore = true;\n }\n\n for (const storageKey of storageKeys) {\n await runSerializedDocumentBlobMutation(execSql, storageKey, async () => {\n const shouldDelete = await runSerializedSqlMutation(\n execSql,\n async (lockedExecSql) => {\n if (\n await persistence.orphanBlobs.isReferenced(\n lockedExecSql,\n storageKey,\n )\n ) {\n await persistence.orphanBlobs.acknowledge(\n lockedExecSql,\n storageKey,\n );\n return false;\n }\n return true;\n },\n );\n if (!shouldDelete) return;\n try {\n await runtime.infra.blobStore.deleteBytes(storageKey);\n await runSerializedSqlMutation(execSql, (lockedExecSql) =>\n persistence.orphanBlobs.acknowledge(lockedExecSql, storageKey),\n );\n } catch {\n failedStorageKeys.push(storageKey);\n deferredStorageKeys.set(\n storageKey,\n Date.now() + ORPHAN_BLOB_RECLAIM_RETRY_DELAY_MS,\n );\n }\n });\n if (Date.now() - startedAt >= ORPHAN_BLOB_RECLAIM_TIME_BUDGET_MS) {\n shouldContinue = true;\n break reclaimQueue;\n }\n }\n }\n\n if (failedStorageKeys.length > 0) {\n const sample = failedStorageKeys\n .slice(0, ORPHAN_BLOB_RECLAIM_LOG_SAMPLE_SIZE)\n .join(\", \");\n runtime.util.log(\n `Documents: orphan maintenance deferred ${failedStorageKeys.length} blob(s): ${sample}`,\n );\n }\n return shouldContinue;\n}\n\nfunction runDocumentOrphanReclaims(\n runtime: DocumentOrphanBlobReclaimRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n): Promise<void> {\n if (runtime.infra.dbStatus !== \"ready\") {\n return Promise.resolve();\n }\n const state = orphanBlobReclaimState(\n persistence.orphanBlobs,\n resolveCanonicalExecSql(runtime.infra.execSql),\n );\n if (state.running) {\n state.rerun = true;\n return state.running;\n }\n\n const reclaim = (async () => {\n try {\n let hasMore: boolean;\n do {\n state.rerun = false;\n hasMore = false;\n try {\n hasMore = await reclaimQueuedBlobs(runtime, persistence, state);\n } catch (error) {\n const message = errorMessage(error);\n runtime.util.log(`Documents: orphan maintenance failed: ${message}`);\n }\n if (hasMore || state.rerun) await waitForMaintenanceYield();\n } while (hasMore || state.rerun);\n } finally {\n state.running = undefined;\n state.rerun = false;\n }\n })();\n state.running = reclaim;\n return reclaim;\n}\n\n/** Await all requested batches; maintenance failures never fail committed writes. */\nexport async function reclaimDocumentOrphanBlobs(\n runtime: DocumentOrphanBlobReclaimRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n): Promise<void> {\n try {\n await runDocumentOrphanReclaims(runtime, persistence);\n } catch (error) {\n runtime.util.log(\n `Documents: orphan maintenance failed: ${errorMessage(error)}`,\n );\n }\n}\n"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
1
2
|
import { createProjectionUserKeyResolver } from "../../data/keyingProjectionVerification/userKeyResolver.js";
|
|
2
3
|
import { createRuntimePrincipalPolicyCurrentResolver, } from "../principals/runtimePolicyRecovery.js";
|
|
3
4
|
import { createRuntimePrincipalPolicyWarmer } from "../principals/runtimePolicyWarmer.js";
|
|
4
5
|
import { createCurrentGroupMetadataContainerVerifier } from "./currentGroupMetadataAuthority.js";
|
|
5
6
|
import { createGroupMetadataAccess, } from "./groupMetadataAccess.js";
|
|
6
|
-
import { createGroupMetadataContainerVerifier } from "./groupMetadataContainerAuthority.js";
|
|
7
7
|
export function createRuntimeGroupMetadataAccess(runtime, organizationId, stillCurrent, verifyMetadataContainer, currentRecovery) {
|
|
8
8
|
const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;
|
|
9
9
|
if (!targetSecretKey)
|
|
@@ -25,13 +25,11 @@ export function createRuntimeGroupMetadataAccess(runtime, organizationId, stillC
|
|
|
25
25
|
};
|
|
26
26
|
return createGroupMetadataAccess({
|
|
27
27
|
verifyMetadataContainer: verifyMetadataContainer ??
|
|
28
|
-
(
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
})
|
|
34
|
-
: createGroupMetadataContainerVerifier(authorityInput)),
|
|
28
|
+
createCurrentGroupMetadataContainerVerifier({
|
|
29
|
+
...authorityInput,
|
|
30
|
+
resolveCurrentPolicy: requireCurrentResolver(resolveCurrentPolicy),
|
|
31
|
+
recoveryBatch: currentRecovery?.recoveryBatch,
|
|
32
|
+
}),
|
|
35
33
|
apiClient: runtime.apiClient,
|
|
36
34
|
execSql: runtime.infra.execSql,
|
|
37
35
|
organizationId,
|
|
@@ -41,4 +39,9 @@ export function createRuntimeGroupMetadataAccess(runtime, organizationId, stillC
|
|
|
41
39
|
warmReferencedPrincipalPolicies: warmer,
|
|
42
40
|
});
|
|
43
41
|
}
|
|
42
|
+
function requireCurrentResolver(resolve) {
|
|
43
|
+
if (!resolve)
|
|
44
|
+
throw new ProjectionDependencyUnavailableError("Group metadata requires private paged recovery");
|
|
45
|
+
return resolve;
|
|
46
|
+
}
|
|
44
47
|
//# sourceMappingURL=groupMetadataRuntime.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupMetadataRuntime.js","sourceRoot":"","sources":["groupMetadataRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,+BAA+B,EAAE,MAAM,yDAAyD,CAAC;AAI1G,OAAO,EACL,2CAA2C,GAE5C,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,kCAAkC,EAAE,MAAM,mCAAmC,CAAC;AACvF,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EACL,yBAAyB,GAE1B,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"groupMetadataRuntime.js","sourceRoot":"","sources":["groupMetadataRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,+BAA+B,EAAE,MAAM,yDAAyD,CAAC;AAI1G,OAAO,EACL,2CAA2C,GAE5C,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,kCAAkC,EAAE,MAAM,mCAAmC,CAAC;AACvF,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EACL,yBAAyB,GAE1B,MAAM,uBAAuB,CAAC;AAmB/B,MAAM,UAAU,gCAAgC,CAC9C,OAA6B,EAC7B,cAAsB,EACtB,YAA4B,EAC5B,uBAA6E,EAC7E,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cesContent":["import type { EncapsulationKeyPair } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { createProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport {\n createRuntimePrincipalPolicyCurrentResolver,\n type PrincipalPolicyRecoveryRuntime,\n} from \"../principals/runtimePolicyRecovery\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../principals/runtimePolicyWarmer\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\nimport {\n createGroupMetadataAccess,\n type GroupMetadataAccessInput,\n} from \"./groupMetadataAccess\";\nimport type { PrincipalPolicyReadApi } from \"./groupPolicyMutationContext\";\n\ninterface GroupMetadataRuntime {\n readonly state?: PrincipalPolicyRecoveryRuntime[\"state\"];\n readonly apiClient: GroupMetadataAccessInput[\"apiClient\"] &\n PrincipalPolicyReadApi &\n PrincipalPolicyRecoveryRuntime[\"apiClient\"];\n readonly crypto: {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n };\n readonly infra: { readonly execSql: ExecSql };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: {\n readonly log: (message: string) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n };\n}\n\nexport function createRuntimeGroupMetadataAccess(\n runtime: GroupMetadataRuntime,\n organizationId: string,\n stillCurrent?: () => boolean,\n verifyMetadataContainer?: GroupMetadataAccessInput[\"verifyMetadataContainer\"],\n currentRecovery?: {\n readonly resolveCurrentPolicy: ReturnType<\n typeof createRuntimePrincipalPolicyCurrentResolver\n >;\n readonly recoveryBatch: object;\n },\n) {\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!targetSecretKey) throw new Error(\"Group metadata identity is locked\");\n // The signed metadata projection selects exact citations. Reuse matching\n // private evidence with its dependencies and pins before bounded online reads.\n const warmer = createRuntimePrincipalPolicyWarmer(runtime, {\n preferLocalCurrent: true,\n });\n const resolveCurrentPolicy =\n currentRecovery?.resolveCurrentPolicy ??\n createRuntimePrincipalPolicyCurrentResolver(runtime);\n const authorityInput = {\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: stillCurrent ?? (() => true),\n };\n return createGroupMetadataAccess({\n verifyMetadataContainer:\n verifyMetadataContainer ??\n createCurrentGroupMetadataContainerVerifier({\n ...authorityInput,\n resolveCurrentPolicy: requireCurrentResolver(resolveCurrentPolicy),\n recoveryBatch: currentRecovery?.recoveryBatch,\n }),\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: warmer,\n });\n}\n\nfunction requireCurrentResolver(\n resolve: ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>,\n) {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n return resolve;\n}\n"]}
|
|
@@ -1,60 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { retainVerifiedPrincipalPolicyBundle } from "../../data/persistence/verifiedPrincipalPolicyRetentionPersistence.js";
|
|
1
|
+
import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
3
2
|
import { hydrateCurrentOrganizationGroupNames } from "./currentOrganizationGroupNames.js";
|
|
4
|
-
import { verifyDirectoryGroup, } from "./groupNameUniqueness.js";
|
|
5
|
-
import { loadGroupNameDirectoryAuthority } from "./organizationGroupNamePolicies.js";
|
|
6
3
|
/** Verify names against the signed directory before projecting decrypted labels. */
|
|
7
4
|
export async function hydrateOrganizationGroupNames(input) {
|
|
8
|
-
if (input.resolveCurrentPolicy)
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
if (!authority)
|
|
16
|
-
throw new Error("Group directory authority is unavailable");
|
|
17
|
-
const names = [];
|
|
18
|
-
const unreadableGroupIds = new Set();
|
|
19
|
-
for (const group of input.directory.groups) {
|
|
20
|
-
const head = authority.descriptor.groupHeads.find((head) => head.principalId === group.groupId);
|
|
21
|
-
if (!head || head.stateHash !== group.currentState?.stateHash)
|
|
22
|
-
throw new Error("Group listing does not match the signed directory");
|
|
23
|
-
const verified = await verifyDirectoryGroup({
|
|
24
|
-
...input,
|
|
25
|
-
descriptor: authority.descriptor,
|
|
26
|
-
externalAuthority: authority.externalAuthority,
|
|
27
|
-
}, head);
|
|
28
|
-
// An undecryptable name stays blank for its group alone, and is flagged so
|
|
29
|
-
// the group is never offered for selection by name.
|
|
30
|
-
if (verified.name === null) {
|
|
31
|
-
unreadableGroupIds.add(group.groupId);
|
|
32
|
-
}
|
|
33
|
-
else {
|
|
34
|
-
names.push({
|
|
35
|
-
groupId: group.groupId,
|
|
36
|
-
name: verified.name,
|
|
37
|
-
stateHash: head.stateHash,
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
await retainVerifiedPrincipalPolicyBundle({
|
|
41
|
-
...input,
|
|
42
|
-
bundle: verified.bundle,
|
|
43
|
-
policy: verified.policy,
|
|
44
|
-
updatedAt: new Date().toISOString(),
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
if (!input.stillCurrent())
|
|
48
|
-
throw new Error("Group directory access changed");
|
|
49
|
-
await saveOrganizationGroupDisplayNames({ ...input, names });
|
|
50
|
-
const byId = new Map(names.map((entry) => [entry.groupId, entry.name]));
|
|
51
|
-
return {
|
|
52
|
-
...input.directory,
|
|
53
|
-
groups: input.directory.groups.map((group) => ({
|
|
54
|
-
...group,
|
|
55
|
-
name: byId.get(group.groupId) ?? "",
|
|
56
|
-
nameUnreadable: unreadableGroupIds.has(group.groupId),
|
|
57
|
-
})),
|
|
58
|
-
};
|
|
5
|
+
if (!input.resolveCurrentPolicy)
|
|
6
|
+
throw new ProjectionDependencyUnavailableError("Group names require private paged recovery");
|
|
7
|
+
return hydrateCurrentOrganizationGroupNames({
|
|
8
|
+
...input,
|
|
9
|
+
organizationReference: input.organizationPolicyReference,
|
|
10
|
+
resolveCurrentPolicy: input.resolveCurrentPolicy,
|
|
11
|
+
});
|
|
59
12
|
}
|
|
60
13
|
//# sourceMappingURL=organizationGroupNames.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationGroupNames.js","sourceRoot":"","sources":["organizationGroupNames.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"organizationGroupNames.js","sourceRoot":"","sources":["organizationGroupNames.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,oCAAoC,EAAE,MAAM,iCAAiC,CAAC;AAIvF,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,KAaC;IAED,IAAI,CAAC,KAAK,CAAC,oBAAoB;QAC7B,MAAM,IAAI,oCAAoC,CAC5C,4CAA4C,CAC7C,CAAC;IACJ,OAAO,oCAAoC,CAAC;QAC1C,GAAG,KAAK;QACR,qBAAqB,EAAE,KAAK,CAAC,2BAA2B;QACxD,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { hydrateCurrentOrganizationGroupNames } from \"./currentOrganizationGroupNames\";\nimport type { DirectoryGroupWalkInput } from \"./groupNameUniqueness\";\nimport type { OrganizationDirectoryAndGroups } from \"./readModel\";\n\n/** Verify names against the signed directory before projecting decrypted labels. */\nexport async function hydrateOrganizationGroupNames(\n input: Omit<DirectoryGroupWalkInput, \"descriptor\" | \"externalAuthority\"> & {\n readonly directory: OrganizationDirectoryAndGroups;\n readonly organizationPolicyReference?: ReferencedPrincipalHead | null;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n readonly createCurrentNameReader?: Parameters<\n typeof hydrateCurrentOrganizationGroupNames\n >[0][\"createCurrentNameReader\"];\n readonly resolveCurrentPolicy?:\n | Parameters<\n typeof hydrateCurrentOrganizationGroupNames\n >[0][\"resolveCurrentPolicy\"]\n | undefined;\n },\n): Promise<OrganizationDirectoryAndGroups> {\n if (!input.resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group names require private paged recovery\",\n );\n return hydrateCurrentOrganizationGroupNames({\n ...input,\n organizationReference: input.organizationPolicyReference,\n resolveCurrentPolicy: input.resolveCurrentPolicy,\n });\n}\n"]}
|
|
@@ -5,7 +5,7 @@ import { assertAuthoredPrincipalMutationReceipt, assertAuthoredPrincipalPolicyRe
|
|
|
5
5
|
/** Match both the operation's route and its exact authored policy artifacts. */
|
|
6
6
|
export async function assertAuthoredPrincipalOperationReceipt(mutation, response) {
|
|
7
7
|
switch (mutation.kind) {
|
|
8
|
-
case
|
|
8
|
+
case "compound":
|
|
9
9
|
if (!isCommitOrganizationGroupPolicyResponse(response))
|
|
10
10
|
break;
|
|
11
11
|
return assertAuthoredPrincipalMutationReceipt(mutation.request, response);
|