@tearleads/client-sdk 0.1.243 → 0.1.246

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 (200) hide show
  1. package/client/organizations/principalMutations.d.ts +5 -0
  2. package/data/containers/shared/mutationAcknowledgement.d.ts +1 -1
  3. package/data/containers/shared/mutationAcknowledgement.js +3 -8
  4. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  5. package/data/documents/shared/sync/mutationAcknowledgement.js +11 -2
  6. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -1
  7. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.d.ts +26 -0
  8. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js +46 -0
  9. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js.map +1 -0
  10. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +7 -4
  11. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +5 -1
  12. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  13. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +9 -2
  14. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  15. package/data/keyingProjectionVerification/document/documentContainerProjections.js +2 -1
  16. package/data/keyingProjectionVerification/document/documentContainerProjections.js.map +1 -1
  17. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +9 -2
  18. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  19. package/data/keyingProjectionVerification/index.d.ts +1 -0
  20. package/data/keyingProjectionVerification/index.js +1 -0
  21. package/data/keyingProjectionVerification/index.js.map +1 -1
  22. package/data/persistence/container-contents/containerContentsPersistence.js +2 -0
  23. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  24. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -1
  25. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  26. package/data/persistence/container-contents/containerMetadataRevalidations.d.ts +22 -0
  27. package/data/persistence/container-contents/containerMetadataRevalidations.js +52 -0
  28. package/data/persistence/container-contents/containerMetadataRevalidations.js.map +1 -0
  29. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js +16 -4
  30. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js.map +1 -1
  31. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +13 -0
  32. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +11 -0
  33. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  34. package/data/persistence/verifiedCitations/authoredBundleCitation.d.ts +20 -0
  35. package/data/persistence/verifiedCitations/authoredBundleCitation.js +32 -0
  36. package/data/persistence/verifiedCitations/authoredBundleCitation.js.map +1 -0
  37. package/data/persistence/verifiedManifestBundlePersistence.d.ts +10 -0
  38. package/data/persistence/verifiedManifestBundlePersistence.js +95 -9
  39. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  40. package/data/sqlite/schema/containerSchema.d.ts +173 -0
  41. package/data/sqlite/schema/containerSchema.js +18 -0
  42. package/data/sqlite/schema/containerSchema.js.map +1 -1
  43. package/data/sqlite/schema/index.d.ts +84 -1
  44. package/data/sqlite/schema/index.js +1 -1
  45. package/data/sqlite/schema/index.js.map +1 -1
  46. package/internal/api-client/ApiClient.d.ts +56 -8
  47. package/internal/api-client/client/apiClientContext.d.ts +1 -0
  48. package/internal/api-client/client/containerMutations.d.ts +11 -0
  49. package/internal/api-client/client/containerReads.d.ts +1 -0
  50. package/internal/api-client/client/documents.d.ts +5 -0
  51. package/internal/api-client/client/organizations.d.ts +20 -0
  52. package/internal/api-client/client/principalPolicies.d.ts +9 -0
  53. package/internal/api-client/client/session.d.ts +10 -0
  54. package/internal/api-client/principalPolicyRequests.d.ts +7 -0
  55. package/internal/api-client/writerProjectionCitations.d.ts +3 -0
  56. package/internal/api-client/writerProjectionCitations.js +12 -0
  57. package/internal/api-client/writerProjectionCitations.js.map +1 -1
  58. package/internal/crypto/index.d.ts +1 -1
  59. package/internal/crypto/index.js +1 -1
  60. package/internal/crypto/index.js.map +1 -1
  61. package/internal/crypto/keying/accessManifestVerificationTypes.d.ts +8 -2
  62. package/internal/crypto/keying/accessManifestVerificationTypes.js.map +1 -1
  63. package/internal/crypto/keying/canonicalJsonGuard.d.ts +13 -0
  64. package/internal/crypto/keying/canonicalJsonGuard.js +23 -0
  65. package/internal/crypto/keying/canonicalJsonGuard.js.map +1 -1
  66. package/internal/crypto/keying/containerAccess.js +1 -1
  67. package/internal/crypto/keying/containerAccess.js.map +1 -1
  68. package/internal/crypto/keying/documentAccess.js +1 -1
  69. package/internal/crypto/keying/documentAccess.js.map +1 -1
  70. package/internal/crypto/keying/index.d.ts +1 -1
  71. package/internal/crypto/keying/index.js +1 -1
  72. package/internal/crypto/keying/index.js.map +1 -1
  73. package/internal/crypto/keying/keyingHashDomains.d.ts +1 -1
  74. package/internal/crypto/keying/keyingHashDomains.js.map +1 -1
  75. package/internal/crypto/organizationReplacement.js +5 -6
  76. package/internal/crypto/organizationReplacement.js.map +1 -1
  77. package/internal/loro/document.d.ts +5 -0
  78. package/internal/loro/document.js +17 -0
  79. package/internal/loro/document.js.map +1 -1
  80. package/internal/loro/index.d.ts +1 -1
  81. package/internal/loro/index.js +1 -1
  82. package/internal/loro/index.js.map +1 -1
  83. package/internal/validators/operation/attachments.d.ts +0 -12
  84. package/internal/validators/operation/auth.d.ts +40 -76
  85. package/internal/validators/operation/containerMutations.d.ts +45 -49
  86. package/internal/validators/operation/containerMutations.js +1 -1
  87. package/internal/validators/operation/containerMutations.js.map +1 -1
  88. package/internal/validators/operation/containerReads.d.ts +2 -0
  89. package/internal/validators/operation/documentMutations.d.ts +12 -24
  90. package/internal/validators/operation/documentSync.d.ts +0 -4
  91. package/internal/validators/operation/organizations.d.ts +48 -88
  92. package/internal/validators/operation/principals.d.ts +16 -16
  93. package/internal/validators/request/blob.d.ts +0 -12
  94. package/internal/validators/request/container.d.ts +0 -16
  95. package/internal/validators/request/container.js +0 -2
  96. package/internal/validators/request/container.js.map +1 -1
  97. package/internal/validators/request/containerMetadata.d.ts +0 -20
  98. package/internal/validators/request/document.d.ts +0 -22
  99. package/internal/validators/request/document.js +0 -1
  100. package/internal/validators/request/document.js.map +1 -1
  101. package/internal/validators/request/documentSyncSchema.d.ts +0 -4
  102. package/internal/validators/request/documentSyncSchema.js +0 -1
  103. package/internal/validators/request/documentSyncSchema.js.map +1 -1
  104. package/internal/validators/request/organization.d.ts +0 -16
  105. package/internal/validators/request/organizationProvisioning.d.ts +0 -242
  106. package/internal/validators/request/principal.d.ts +0 -20
  107. package/internal/validators/request/registration.d.ts +0 -76
  108. package/internal/validators/response/areas/containers.d.ts +1 -1
  109. package/internal/validators/response/areas/containers.js +1 -1
  110. package/internal/validators/response/areas/containers.js.map +1 -1
  111. package/internal/validators/response/container.d.ts +24 -0
  112. package/internal/validators/response/container.js +4 -0
  113. package/internal/validators/response/container.js.map +1 -1
  114. package/internal/validators/response/containerMetadata.d.ts +8 -0
  115. package/internal/validators/response/containerParentLanes.d.ts +2 -0
  116. package/internal/validators/response/documentMutation.d.ts +8 -0
  117. package/internal/validators/response/documentMutation.js +2 -1
  118. package/internal/validators/response/documentMutation.js.map +1 -1
  119. package/internal/validators/response/organization.d.ts +8 -0
  120. package/internal/validators/response/organizationProvisioning.d.ts +113 -0
  121. package/internal/validators/response/organizationProvisioning.js +2 -1
  122. package/internal/validators/response/organizationProvisioning.js.map +1 -1
  123. package/internal/validators/response/principal.d.ts +16 -0
  124. package/internal/validators/response/registration.d.ts +40 -0
  125. package/internal/validators/response/writerProjectionWire.d.ts +25 -0
  126. package/internal/validators/response/writerProjectionWire.js +109 -3
  127. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  128. package/package.json +1 -1
  129. package/stores/container-contents/containerContentsStore.js +2 -0
  130. package/stores/container-contents/containerContentsStore.js.map +1 -1
  131. package/stores/container-contents/hydration/startupHydration.js +6 -2
  132. package/stores/container-contents/hydration/startupHydration.js.map +1 -1
  133. package/stores/container-contents/state.js +5 -1
  134. package/stores/container-contents/state.js.map +1 -1
  135. package/stores/container-contents/syncAgent/metadataRevalidation.js +79 -0
  136. package/stores/container-contents/syncAgent/metadataRevalidation.js.map +1 -0
  137. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +6 -0
  138. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  139. package/stores/container-contents/syncAgent/syncLaneIteration.js +110 -23
  140. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  141. package/stores/documents/documentStore/rotation/index.js +3 -1
  142. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  143. package/stores/documents/documentStore/sync/syncAttachments.js +4 -1
  144. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  145. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -1
  146. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  147. package/stores/documents/documentStore/sync/syncRequest.js +3 -1
  148. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  149. package/workflows/container-contents/container-state/create/createAdoption.js +11 -3
  150. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  151. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  152. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  153. package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js +3 -0
  154. package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js.map +1 -1
  155. package/workflows/container-contents/container-state/projectionCache.js +3 -0
  156. package/workflows/container-contents/container-state/projectionCache.js.map +1 -1
  157. package/workflows/container-contents/container-state/remote.js +3 -0
  158. package/workflows/container-contents/container-state/remote.js.map +1 -1
  159. package/workflows/container-contents/containerPersistence.d.ts +1 -0
  160. package/workflows/container-contents/containerPersistence.js.map +1 -1
  161. package/workflows/container-contents/metadata/index.js +9 -3
  162. package/workflows/container-contents/metadata/index.js.map +1 -1
  163. package/workflows/container-contents/metadata/metadataSyncFollowup.js +9 -0
  164. package/workflows/container-contents/metadata/metadataSyncFollowup.js.map +1 -1
  165. package/workflows/container-contents/metadata/metadataTypes.d.ts +2 -0
  166. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  167. package/workflows/container-contents/remoteHydration/index.js +9 -0
  168. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  169. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +31 -0
  170. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  171. package/workflows/container-contents/remoteHydration/types.d.ts +9 -1
  172. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  173. package/workflows/containers/child/mutationRequestCore.js +1 -1
  174. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  175. package/workflows/containers/child/recite.js +4 -2
  176. package/workflows/containers/child/recite.js.map +1 -1
  177. package/workflows/containers/child/recitePlan.js +0 -1
  178. package/workflows/containers/child/recitePlan.js.map +1 -1
  179. package/workflows/containers/root/create.js +0 -1
  180. package/workflows/containers/root/create.js.map +1 -1
  181. package/workflows/documents/create/createAdoption.js +11 -2
  182. package/workflows/documents/create/createAdoption.js.map +1 -1
  183. package/workflows/documents/create/createResponse.js +1 -0
  184. package/workflows/documents/create/createResponse.js.map +1 -1
  185. package/workflows/documents/linkSet/index.js +0 -1
  186. package/workflows/documents/linkSet/index.js.map +1 -1
  187. package/workflows/documents/linkSet/linkSetRemote.js +1 -0
  188. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  189. package/workflows/documents/sync/syncAttemptPlanning.js +8 -2
  190. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  191. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +3 -2
  192. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  193. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js +3 -2
  194. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js.map +1 -1
  195. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +17 -10
  196. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
  197. package/workflows/registration/organizationCreation/organizationCreationIntent.d.ts +10 -0
  198. package/workflows/registration/provisioningAcknowledgement.js +16 -11
  199. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
  200. package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -2
@@ -42,6 +42,7 @@ export declare function addUserToOrganizationGroup(input: PrincipalMutationRunti
42
42
  keyTargetHash: string;
43
43
  parentContainerKeyEpochId: string | null;
44
44
  };
45
+ bundleDigest: string;
45
46
  containerId: string;
46
47
  createdAt: string;
47
48
  eventHash: string;
@@ -85,6 +86,7 @@ export declare function deleteGroupForOrganization(input: OrganizationMutationSc
85
86
  keyTargetHash: string;
86
87
  parentContainerKeyEpochId: string | null;
87
88
  };
89
+ bundleDigest: string;
88
90
  containerId: string;
89
91
  createdAt: string;
90
92
  eventHash: string;
@@ -121,6 +123,7 @@ export declare function removeUserFromOrganizationGroup(input: PrincipalMutation
121
123
  keyTargetHash: string;
122
124
  parentContainerKeyEpochId: string | null;
123
125
  };
126
+ bundleDigest: string;
124
127
  containerId: string;
125
128
  createdAt: string;
126
129
  eventHash: string;
@@ -153,6 +156,7 @@ export declare function revokeOrganizationGrant(input: PrincipalMutationRuntime
153
156
  keyTargetHash: string;
154
157
  parentContainerKeyEpochId: string | null;
155
158
  };
159
+ bundleDigest: string;
156
160
  containerId: string;
157
161
  createdAt: string;
158
162
  eventHash: string;
@@ -174,6 +178,7 @@ export declare function revokeOrganizationGrant(input: PrincipalMutationRuntime
174
178
  keyTargetHash: string;
175
179
  parentContainerKeyEpochId: string | null;
176
180
  };
181
+ bundleDigest: string;
177
182
  containerId: string;
178
183
  createdAt: string;
179
184
  eventHash: string;
@@ -1,6 +1,6 @@
1
1
  import { type AccessEvent, type AccessManifest, type ContainerAccessManifestState, type ContainerKeyEpoch, type ContainerKeyWrap } from "../../../internal/crypto/index.js";
2
2
  import type { ContainerMutationResponse } from "../../../internal/validators/response/index.js";
3
- import type { LocallyAcknowledgedAccessManifestHead } from "../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
3
+ import { type LocallyAcknowledgedAccessManifestHead } from "../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
4
4
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
5
5
  export interface AuthoredContainerMutationHead {
6
6
  readonly body: object;
@@ -1,6 +1,7 @@
1
- import { accessManifestCheckpointFromManifest, compareCanonicalStrings, computeContainerKekKeyringHash, computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, } from "../../../internal/crypto/index.js";
1
+ import { compareCanonicalStrings, computeContainerKekKeyringHash, computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, } from "../../../internal/crypto/index.js";
2
2
  import { canonicalKeyingJsonString } from "../../keying/canonicalJson.js";
3
3
  import { KeyingCheckpointRepository } from "../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
+ import { locallyAcknowledgedAuthoredHead, } from "../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
4
5
  function expectedRecipientTargets(wraps) {
5
6
  return [
6
7
  ...wraps.map((wrap) => ({
@@ -87,13 +88,7 @@ async function assertResponseCommitments(plan, response) {
87
88
  export async function locallyAcknowledgedContainerMutationHead(input) {
88
89
  assertResponseIdentity(input.plan, input.response);
89
90
  await assertResponseCommitments(input.plan, input.response);
90
- return {
91
- checkpoint: accessManifestCheckpointFromManifest({
92
- manifest: input.plan.manifest,
93
- manifestHash: input.plan.manifestHash,
94
- }),
95
- previousManifestHash: input.plan.manifest.previousManifestHash,
96
- };
91
+ return locallyAcknowledgedAuthoredHead(input.plan, input.response.bundleDigest);
97
92
  }
98
93
  /** Correlates an API acknowledgement to the locally signed plan before pinning. */
99
94
  export async function acknowledgeContainerM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AA0B,CACnC,KAAK,CAAC,OAAO,CACd,CAAC,uDAAuD,CAAC;QACxD,KAAK;QACL,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n type AccessEvent,\n type AccessManifest,\n accessManifestCheckpointFromManifest,\n type ContainerAccessManifestState,\n type ContainerKekRecipientTarget,\n type ContainerKeyEpoch,\n type ContainerKeyWrap,\n compareCanonicalStrings,\n computeContainerKekKeyringHash,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n} from \"@tearleads/crypto\";\nimport type { ContainerMutationResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport type { LocallyAcknowledgedAccessManifestHead } from \"../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nexport interface AuthoredContainerMutationHead {\n readonly body: object;\n readonly containerId: string;\n readonly event: AccessEvent;\n readonly eventHash: string;\n readonly keyEpoch: ContainerKeyEpoch;\n readonly manifest: AccessManifest;\n readonly manifestHash: string;\n /**\n * The keyring the epoch already had, for mutations that keep their epoch.\n * Its artifact is immutable, so the acknowledged keyring hash must be its.\n */\n readonly previousKeyring?: Record<string, unknown> | null | undefined;\n readonly state: ContainerAccessManifestState;\n readonly wraps: readonly ContainerKeyWrap[];\n}\n\nfunction expectedRecipientTargets(\n wraps: readonly ContainerKeyWrap[],\n): ContainerKekRecipientTarget[] {\n return [\n ...wraps.map((wrap) => ({\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n })),\n ].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, \"recipient target\"),\n canonicalKeyingJsonString(right, \"recipient target\"),\n ),\n );\n}\n\nfunction assertResponseIdentity(\n plan: AuthoredContainerMutationHead,\n response: ContainerMutationResponse,\n): void {\n if (\n response.containerId !== plan.containerId ||\n response.organizationId !== plan.state.organizationId ||\n response.parentId !== plan.state.parentContainerId\n ) {\n throw new Error(\"Container mutation response object identity mismatch\");\n }\n // The top-level slot column is what local system-container lookups key on,\n // so it must name the slot this client signed into the manifest state; an\n // omitted slot is the server's spelling of null.\n if ((response.systemSlot ?? null) !== plan.state.systemSlot) {\n throw new Error(\"Container mutation response system slot mismatch\");\n }\n // The manifest hash commits to the signed event (by hash), the derived\n // state, and the key target set, so equal hashes acknowledge exactly the\n // manifest this client signed.\n if (\n response.manifestHead.epoch !== plan.state.epoch ||\n response.manifestHead.manifestHash !== plan.manifestHash ||\n response.eventHash !== plan.eventHash\n ) {\n throw new Error(\"Container mutation response manifest head mismatch\");\n }\n if (\n response.containerKek.containerKeyEpochId !== plan.keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== plan.keyEpoch.keyEpoch\n ) {\n throw new Error(\"Container mutation response KEK identity mismatch\");\n }\n}\n\n/** A rotation body commits a keyring hash; other bodies do not. */\nfunction readOptionalKeyringHash(body: object): string | null {\n const value = Reflect.get(body, \"keyringHash\");\n return typeof value === \"string\" ? value : null;\n}\n\n/**\n * The keyring the server stored must be the one this client's own signed\n * event committed to, or, for a mutation that keeps its epoch, the immutable\n * artifact that epoch already had. The acknowledgement is the moment the\n * response becomes trusted, so the commitment is checked here.\n */\nasync function assertAcknowledgedKeyringHash(\n plan: AuthoredContainerMutationHead,\n keyringHash: string | null,\n): Promise<void> {\n const committedHash = readOptionalKeyringHash(plan.body);\n if (committedHash !== null) {\n if (keyringHash !== committedHash) {\n throw new Error(\n \"Container mutation response keyring does not match its signed event\",\n );\n }\n return;\n }\n const previous = plan.previousKeyring ?? null;\n if (previous === null) {\n // The epoch had no keyring, so the response must not invent one: an\n // injected snapshot would become the next writer projection's history.\n if (keyringHash !== null) {\n throw new Error(\n \"Container mutation response added a keyring to an unchanged epoch\",\n );\n }\n return;\n }\n if (keyringHash === null) {\n throw new Error(\n \"Container mutation response dropped its unchanged keyring\",\n );\n }\n if (keyringHash !== (await computeContainerKekKeyringHash(previous))) {\n throw new Error(\n \"Container mutation response replaced its unchanged keyring\",\n );\n }\n}\n\nasync function assertResponseCommitments(\n plan: AuthoredContainerMutationHead,\n response: ContainerMutationResponse,\n): Promise<void> {\n const kek = response.containerKek;\n await assertAcknowledgedKeyringHash(plan, kek.keyringHash);\n // The recipient target hash is how the #2158 wrong-recipient checks reach\n // the acknowledgement: it commits to every wrap's recipient, so a server\n // that stored a wrap for anyone else cannot match it.\n if (\n kek.keyEpochHash !== (await computeContainerKeyEpochHash(plan.keyEpoch)) ||\n kek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(\n expectedRecipientTargets(plan.wraps),\n )) ||\n kek.parentContainerKeyEpochId !== plan.keyEpoch.parentContainerKeyEpochId\n ) {\n throw new Error(\"Container mutation response KEK commitment mismatch\");\n }\n}\n\nexport async function locallyAcknowledgedContainerMutationHead(input: {\n readonly plan: AuthoredContainerMutationHead;\n readonly response: ContainerMutationResponse;\n}): Promise<LocallyAcknowledgedAccessManifestHead> {\n assertResponseIdentity(input.plan, input.response);\n await assertResponseCommitments(input.plan, input.response);\n return {\n checkpoint: accessManifestCheckpointFromManifest({\n manifest: input.plan.manifest,\n manifestHash: input.plan.manifestHash,\n }),\n previousManifestHash: input.plan.manifest.previousManifestHash,\n };\n}\n\n/** Correlates an API acknowledgement to the locally signed plan before pinning. */\nexport async function acknowledgeContainerMutation(input: {\n readonly execSql: ExecSql;\n readonly plan: AuthoredContainerMutationHead;\n readonly response: ContainerMutationResponse;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n return new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [\n await locallyAcknowledgedContainerMutationHead({\n plan: input.plan,\n response: input.response,\n }),\n ],\n stillCurrent: input.stillCurrent,\n });\n}\n\n/** Correlates and advances a complete authored mutation batch atomically. */\nexport async function acknowledgeContainerMutationBatch(input: {\n readonly execSql: ExecSql;\n readonly plans: readonly AuthoredContainerMutationHead[];\n readonly responses: readonly ContainerMutationResponse[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n if (input.plans.length !== input.responses.length) {\n throw new Error(\"Container mutation acknowledgement batch is incomplete\");\n }\n const heads = await Promise.all(\n input.plans.map(async (plan, index) => {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Container mutation acknowledgement batch is incomplete\",\n );\n }\n return locallyAcknowledgedContainerMutationHead({ plan, response });\n }),\n );\n return new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads,\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
1
+ {"version":3,"file":"mutationAcknowledgement.js","sourceRoot":"","sources":["mutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EAOL,uBAAuB,EACvB,8BAA8B,EAC9B,sCAAsC,EACtC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EAEL,+BAA+B,GAChC,MAAM,8EAA8E,CAAC;AAoBtF,SAAS,wBAAwB,CAC/B,KAAkC;IAElC,OAAO;QACL,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YACtB,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;YAC7C,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;YACrD,aAAa,EAAE,IAAI,CAAC,aAAa;SAClC,CAAC,CAAC;KACJ,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,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IACD,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,GAAG,CAC7B,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE;QACpC,MAAM,QAAQ,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACxC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,IAAI,KAAK,CACb,wDAAwD,CACzD,CAAC;QACJ,CAAC;QACD,OAAO,wCAAwC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;IACtE,CAAC,CAAC,CACH,CAAC;IACF,OAAO,IAAI,0BAA0B,CACnC,KAAK,CAAC,OAAO,CACd,CAAC,uDAAuD,CAAC;QACxD,KAAK;QACL,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n type AccessEvent,\n type AccessManifest,\n type ContainerAccessManifestState,\n type ContainerKekRecipientTarget,\n type ContainerKeyEpoch,\n type ContainerKeyWrap,\n compareCanonicalStrings,\n computeContainerKekKeyringHash,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n} from \"@tearleads/crypto\";\nimport type { ContainerMutationResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n type LocallyAcknowledgedAccessManifestHead,\n locallyAcknowledgedAuthoredHead,\n} from \"../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nexport interface AuthoredContainerMutationHead {\n readonly body: object;\n readonly containerId: string;\n readonly event: AccessEvent;\n readonly eventHash: string;\n readonly keyEpoch: ContainerKeyEpoch;\n readonly manifest: AccessManifest;\n readonly manifestHash: string;\n /**\n * The keyring the epoch already had, for mutations that keep their epoch.\n * Its artifact is immutable, so the acknowledged keyring hash must be its.\n */\n readonly previousKeyring?: Record<string, unknown> | null | undefined;\n readonly state: ContainerAccessManifestState;\n readonly wraps: readonly ContainerKeyWrap[];\n}\n\nfunction expectedRecipientTargets(\n wraps: readonly ContainerKeyWrap[],\n): ContainerKekRecipientTarget[] {\n return [\n ...wraps.map((wrap) => ({\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n })),\n ].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, \"recipient target\"),\n canonicalKeyingJsonString(right, \"recipient target\"),\n ),\n );\n}\n\nfunction assertResponseIdentity(\n plan: AuthoredContainerMutationHead,\n response: ContainerMutationResponse,\n): void {\n if (\n response.containerId !== plan.containerId ||\n response.organizationId !== plan.state.organizationId ||\n response.parentId !== plan.state.parentContainerId\n ) {\n throw new Error(\"Container mutation response object identity mismatch\");\n }\n // The top-level slot column is what local system-container lookups key on,\n // so it must name the slot this client signed into the manifest state; an\n // omitted slot is the server's spelling of null.\n if ((response.systemSlot ?? null) !== plan.state.systemSlot) {\n throw new Error(\"Container mutation response system slot mismatch\");\n }\n // The manifest hash commits to the signed event (by hash), the derived\n // state, and the key target set, so equal hashes acknowledge exactly the\n // manifest this client signed.\n if (\n response.manifestHead.epoch !== plan.state.epoch ||\n response.manifestHead.manifestHash !== plan.manifestHash ||\n response.eventHash !== plan.eventHash\n ) {\n throw new Error(\"Container mutation response manifest head mismatch\");\n }\n if (\n response.containerKek.containerKeyEpochId !== plan.keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== plan.keyEpoch.keyEpoch\n ) {\n throw new Error(\"Container mutation response KEK identity mismatch\");\n }\n}\n\n/** A rotation body commits a keyring hash; other bodies do not. */\nfunction readOptionalKeyringHash(body: object): string | null {\n const value = Reflect.get(body, \"keyringHash\");\n return typeof value === \"string\" ? value : null;\n}\n\n/**\n * The keyring the server stored must be the one this client's own signed\n * event committed to, or, for a mutation that keeps its epoch, the immutable\n * artifact that epoch already had. The acknowledgement is the moment the\n * response becomes trusted, so the commitment is checked here.\n */\nasync function assertAcknowledgedKeyringHash(\n plan: AuthoredContainerMutationHead,\n keyringHash: string | null,\n): Promise<void> {\n const committedHash = readOptionalKeyringHash(plan.body);\n if (committedHash !== null) {\n if (keyringHash !== committedHash) {\n throw new Error(\n \"Container mutation response keyring does not match its signed event\",\n );\n }\n return;\n }\n const previous = plan.previousKeyring ?? null;\n if (previous === null) {\n // The epoch had no keyring, so the response must not invent one: an\n // injected snapshot would become the next writer projection's history.\n if (keyringHash !== null) {\n throw new Error(\n \"Container mutation response added a keyring to an unchanged epoch\",\n );\n }\n return;\n }\n if (keyringHash === null) {\n throw new Error(\n \"Container mutation response dropped its unchanged keyring\",\n );\n }\n if (keyringHash !== (await computeContainerKekKeyringHash(previous))) {\n throw new Error(\n \"Container mutation response replaced its unchanged keyring\",\n );\n }\n}\n\nasync function assertResponseCommitments(\n plan: AuthoredContainerMutationHead,\n response: ContainerMutationResponse,\n): Promise<void> {\n const kek = response.containerKek;\n await assertAcknowledgedKeyringHash(plan, kek.keyringHash);\n // The recipient target hash is how the #2158 wrong-recipient checks reach\n // the acknowledgement: it commits to every wrap's recipient, so a server\n // that stored a wrap for anyone else cannot match it.\n if (\n kek.keyEpochHash !== (await computeContainerKeyEpochHash(plan.keyEpoch)) ||\n kek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(\n expectedRecipientTargets(plan.wraps),\n )) ||\n kek.parentContainerKeyEpochId !== plan.keyEpoch.parentContainerKeyEpochId\n ) {\n throw new Error(\"Container mutation response KEK commitment mismatch\");\n }\n}\n\nexport async function locallyAcknowledgedContainerMutationHead(input: {\n readonly plan: AuthoredContainerMutationHead;\n readonly response: ContainerMutationResponse;\n}): Promise<LocallyAcknowledgedAccessManifestHead> {\n assertResponseIdentity(input.plan, input.response);\n await assertResponseCommitments(input.plan, input.response);\n return locallyAcknowledgedAuthoredHead(\n input.plan,\n input.response.bundleDigest,\n );\n}\n\n/** Correlates an API acknowledgement to the locally signed plan before pinning. */\nexport async function acknowledgeContainerMutation(input: {\n readonly execSql: ExecSql;\n readonly plan: AuthoredContainerMutationHead;\n readonly response: ContainerMutationResponse;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n return new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [\n await locallyAcknowledgedContainerMutationHead({\n plan: input.plan,\n response: input.response,\n }),\n ],\n stillCurrent: input.stillCurrent,\n });\n}\n\n/** Correlates and advances a complete authored mutation batch atomically. */\nexport async function acknowledgeContainerMutationBatch(input: {\n readonly execSql: ExecSql;\n readonly plans: readonly AuthoredContainerMutationHead[];\n readonly responses: readonly ContainerMutationResponse[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n if (input.plans.length !== input.responses.length) {\n throw new Error(\"Container mutation acknowledgement batch is incomplete\");\n }\n const heads = await Promise.all(\n input.plans.map(async (plan, index) => {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Container mutation acknowledgement batch is incomplete\",\n );\n }\n return locallyAcknowledgedContainerMutationHead({ plan, response });\n }),\n );\n return new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads,\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
@@ -1,9 +1,18 @@
1
1
  import { KeyingCheckpointRepository } from "../../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
2
- import { locallyAuthoredAccessManifestHead } from "../../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
2
+ import { locallyAcknowledgedAuthoredHead, } from "../../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
3
+ /**
4
+ * A matched document head, carrying its authored bundle for citation when
5
+ * the acknowledgement's digest names exactly it.
6
+ */
7
+ export async function locallyAcknowledgedDocumentHead(plan, bundleDigest) {
8
+ return locallyAcknowledgedAuthoredHead(plan, bundleDigest);
9
+ }
3
10
  /** Advances a document head only after its response was matched to this plan. */
4
11
  export async function acknowledgeDocumentMutation(input) {
5
12
  await new KeyingCheckpointRepository(input.execSql).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({
6
- heads: [locallyAuthoredAccessManifestHead(input.plan)],
13
+ heads: [
14
+ await locallyAcknowledgedDocumentHead(input.plan, input.bundleDigest),
15
+ ],
7
16
  stillCurrent: input.stillCurrent,
8
17
  });
9
18
  }
@@ -1 +1 @@
1
- {"version":3,"file":"mutationAcknowledgement.js","sourceRoot":"","sources":["mutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,mEAAmE,CAAC;AAC/G,OAAO,EAAE,iCAAiC,EAAE,MAAM,iFAAiF,CAAC;AAGpI,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAIjD;IACC,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,uDAAuD,CAAC;QACxD,KAAK,EAAE,CAAC,iCAAiC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACtD,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingCheckpointRepository } from \"../../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { locallyAuthoredAccessManifestHead } from \"../../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\n\n/** Advances a document head only after its response was matched to this plan. */\nexport async function acknowledgeDocumentMutation(input: {\n readonly execSql: ExecSql;\n readonly plan: Parameters<typeof locallyAuthoredAccessManifestHead>[0];\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [locallyAuthoredAccessManifestHead(input.plan)],\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
1
+ {"version":3,"file":"mutationAcknowledgement.js","sourceRoot":"","sources":["mutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,mEAAmE,CAAC;AAC/G,OAAO,EAGL,+BAA+B,GAChC,MAAM,iFAAiF,CAAC;AAGzF;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,IAA4B,EAC5B,YAAoB;IAEpB,OAAO,+BAA+B,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;AAC7D,CAAC;AAED,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAKjD;IACC,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,uDAAuD,CAAC;QACxD,KAAK,EAAE;YACL,MAAM,+BAA+B,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC;SACtE;QACD,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingCheckpointRepository } from \"../../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n type AuthoredManifestBundle,\n type LocallyAcknowledgedAccessManifestHead,\n locallyAcknowledgedAuthoredHead,\n} from \"../../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\n\n/**\n * A matched document head, carrying its authored bundle for citation when\n * the acknowledgement's digest names exactly it.\n */\nexport async function locallyAcknowledgedDocumentHead(\n plan: AuthoredManifestBundle,\n bundleDigest: string,\n): Promise<LocallyAcknowledgedAccessManifestHead> {\n return locallyAcknowledgedAuthoredHead(plan, bundleDigest);\n}\n\n/** Advances a document head only after its response was matched to this plan. */\nexport async function acknowledgeDocumentMutation(input: {\n readonly bundleDigest: string;\n readonly execSql: ExecSql;\n readonly plan: AuthoredManifestBundle;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [\n await locallyAcknowledgedDocumentHead(input.plan, input.bundleDigest),\n ],\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
@@ -0,0 +1,26 @@
1
+ import type { ExecSql } from "../../sqlite/sqlSchema.js";
2
+ /**
3
+ * Runs a projection verification whose projection may have taken bundles
4
+ * from this device's citation store. A store row is never verifier trust
5
+ * input, but a wrong one (such as a seeded authored bundle) would otherwise
6
+ * fail every read that cites it. When such a projection fails to verify (or
7
+ * a dependency it names, such as its signer, is unavailable), the
8
+ * cited rows are dropped (only those still holding the exact bytes cited, and
9
+ * only while the request is current) and the projection is marked refused so
10
+ * no cache serves it again: the next read fetches those bundles from the
11
+ * server and its verification decides. The refusal itself is reported
12
+ * unchanged, so a failure in freshly served evidence keeps its meaning.
13
+ */
14
+ interface HeldBundleRecoveryInput {
15
+ readonly execSql: ExecSql;
16
+ readonly projection: object;
17
+ readonly stillCurrent?: (() => boolean) | undefined;
18
+ }
19
+ export declare function verifyWithHeldBundleRecovery<T>(input: HeldBundleRecoveryInput, verify: () => Promise<T>): Promise<T>;
20
+ /**
21
+ * The same recovery for a check of a projection's own consistency that runs
22
+ * before verification (such as a document head's hashes before a queued
23
+ * write): any refusal of a projection that took held bundles drops them.
24
+ */
25
+ export declare function checkWithHeldBundleRecovery<T>(input: HeldBundleRecoveryInput, check: () => Promise<T>): Promise<T>;
26
+ export {};
@@ -0,0 +1,46 @@
1
+ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
+ import { acceptDecodedProjection, heldBundlesUsedBy, rejectDecodedProjection, } from "../../../internal/validators/response/index.js";
3
+ import { dropHeldManifestBundles, suppressHeldCitations, } from "../../persistence/verifiedManifestBundlePersistence.js";
4
+ import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
5
+ export function verifyWithHeldBundleRecovery(input, verify) {
6
+ return runWithHeldBundleRecovery(input, verify, (error) => error instanceof KeyingVerificationError ||
7
+ error instanceof ProjectionDependencyUnavailableError, true);
8
+ }
9
+ /**
10
+ * The same recovery for a check of a projection's own consistency that runs
11
+ * before verification (such as a document head's hashes before a queued
12
+ * write): any refusal of a projection that took held bundles drops them.
13
+ */
14
+ export function checkWithHeldBundleRecovery(input, check) {
15
+ return runWithHeldBundleRecovery(input, check, () => true, false);
16
+ }
17
+ async function runWithHeldBundleRecovery(input, run, recovers, verifies) {
18
+ try {
19
+ const result = await run();
20
+ // Only a full, current verification vouches for every held byte it used;
21
+ // a consistency check covers one bundle and accepts nothing.
22
+ if (verifies && input.stillCurrent?.() !== false)
23
+ acceptDecodedProjection(input.projection);
24
+ return result;
25
+ }
26
+ catch (error) {
27
+ const held = heldBundlesUsedBy(input.projection);
28
+ // A superseded request changes no shared cache state.
29
+ if (held.length > 0 &&
30
+ input.stillCurrent?.() !== false &&
31
+ recovers(error)) {
32
+ // No read cites these rows while they are dropped, and no cache serves
33
+ // this projection again, so the next read fetches the bundles.
34
+ const release = suppressHeldCitations(held.map((bundle) => bundle.manifestHash));
35
+ rejectDecodedProjection(input.projection);
36
+ // Released only once the rows are gone: a drop that failed or was
37
+ // superseded keeps them out of this process's citations rather than
38
+ // citing the same bytes again.
39
+ const dropped = await dropHeldManifestBundles(input.execSql, held, input.stillCurrent).catch(() => false);
40
+ if (dropped)
41
+ release();
42
+ }
43
+ throw error;
44
+ }
45
+ }
46
+ //# sourceMappingURL=heldBundleRecovery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"heldBundleRecovery.js","sourceRoot":"","sources":["heldBundleRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,gCAAgC,CAAC;AACxC,OAAO,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,CAAC;YACF,uBAAuB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;YAC1C,kEAAkE;YAClE,oEAAoE;YACpE,+BAA+B;YAC/B,MAAM,OAAO,GAAG,MAAM,uBAAuB,CAC3C,KAAK,CAAC,OAAO,EACb,IAAI,EACJ,KAAK,CAAC,YAAY,CACnB,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;YACrB,IAAI,OAAO;gBAAE,OAAO,EAAE,CAAC;QACzB,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n acceptDecodedProjection,\n heldBundlesUsedBy,\n rejectDecodedProjection,\n} from \"@tearleads/validators/response\";\nimport {\n dropHeldManifestBundles,\n suppressHeldCitations,\n} from \"../../persistence/verifiedManifestBundlePersistence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\n/**\n * Runs a projection verification whose projection may have taken bundles\n * from this device's citation store. A store row is never verifier trust\n * input, but a wrong one (such as a seeded authored bundle) would otherwise\n * fail every read that cites it. When such a projection fails to verify (or\n * a dependency it names, such as its signer, is unavailable), the\n * cited rows are dropped (only those still holding the exact bytes cited, and\n * only while the request is current) and the projection is marked refused so\n * no cache serves it again: the next read fetches those bundles from the\n * server and its verification decides. The refusal itself is reported\n * unchanged, so a failure in freshly served evidence keeps its meaning.\n */\ninterface HeldBundleRecoveryInput {\n readonly execSql: ExecSql;\n readonly projection: object;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport function verifyWithHeldBundleRecovery<T>(\n input: HeldBundleRecoveryInput,\n verify: () => Promise<T>,\n): Promise<T> {\n return runWithHeldBundleRecovery(\n input,\n verify,\n (error) =>\n error instanceof KeyingVerificationError ||\n error instanceof ProjectionDependencyUnavailableError,\n true,\n );\n}\n\n/**\n * The same recovery for a check of a projection's own consistency that runs\n * before verification (such as a document head's hashes before a queued\n * write): any refusal of a projection that took held bundles drops them.\n */\nexport function checkWithHeldBundleRecovery<T>(\n input: HeldBundleRecoveryInput,\n check: () => Promise<T>,\n): Promise<T> {\n return runWithHeldBundleRecovery(input, check, () => true, false);\n}\n\nasync function runWithHeldBundleRecovery<T>(\n input: HeldBundleRecoveryInput,\n run: () => Promise<T>,\n recovers: (error: unknown) => boolean,\n verifies: boolean,\n): Promise<T> {\n try {\n const result = await run();\n // Only a full, current verification vouches for every held byte it used;\n // a consistency check covers one bundle and accepts nothing.\n if (verifies && input.stillCurrent?.() !== false)\n acceptDecodedProjection(input.projection);\n return result;\n } catch (error) {\n const held = heldBundlesUsedBy(input.projection);\n // A superseded request changes no shared cache state.\n if (\n held.length > 0 &&\n input.stillCurrent?.() !== false &&\n recovers(error)\n ) {\n // No read cites these rows while they are dropped, and no cache serves\n // this projection again, so the next read fetches the bundles.\n const release = suppressHeldCitations(\n held.map((bundle) => bundle.manifestHash),\n );\n rejectDecodedProjection(input.projection);\n // Released only once the rows are gone: a drop that failed or was\n // superseded keeps them out of this process's citations rather than\n // citing the same bytes again.\n const dropped = await dropHeldManifestBundles(\n input.execSql,\n held,\n input.stillCurrent,\n ).catch(() => false);\n if (dropped) release();\n }\n throw error;\n }\n}\n"]}
@@ -2,16 +2,19 @@ import type { VerifiedContainerAccessManifest } from "../../../internal/crypto/i
2
2
  import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
3
3
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
4
4
  import type { OpenPrincipalPolicyBundleReader, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";
5
- /** Authenticate immutable destination roles without advancing write-authority pins. */
6
- export declare function verifyContainerDestinationProjection(input: {
5
+ interface ContainerDestinationProjectionInput {
7
6
  readonly execSql: ExecSql;
8
7
  readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;
9
8
  readonly projection: ContainerWriterProjectionResponse;
10
9
  readonly resolveUserKey: ProjectionUserKeyResolver;
11
10
  readonly stillCurrent?: (() => boolean) | undefined;
12
11
  readonly warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
13
- }): Promise<{
12
+ }
13
+ interface VerifiedContainerDestination {
14
14
  readonly path: VerifiedContainerAccessManifest[];
15
15
  /** Every manifest verified on the way, including each head's lineage. */
16
16
  readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;
17
- }>;
17
+ }
18
+ /** Authenticate immutable destination roles without advancing write-authority pins. */
19
+ export declare function verifyContainerDestinationProjection(input: ContainerDestinationProjectionInput): Promise<VerifiedContainerDestination>;
20
+ export {};
@@ -1,11 +1,15 @@
1
1
  import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeVerifiedKekLevels, observeVerifiedProjectionBundles, } from "../checkpoints/checkpointContext.js";
2
+ import { verifyWithHeldBundleRecovery } from "../checkpoints/heldBundleRecovery.js";
2
3
  import { verifyProjectionAuthorizationEvidence } from "../principalPolicy/projectionAuthorizationEvidence.js";
3
4
  import { projectionLifetimeGuard } from "../projectionLifetimes.js";
4
5
  import { assertProjectionVerificationCurrent } from "../types.js";
5
6
  import { verifyContainerManifestPath } from "./containerPathVerification.js";
6
7
  import { addContainerWriterProjectionBundles } from "./containerProjectionVerification.js";
7
8
  /** Authenticate immutable destination roles without advancing write-authority pins. */
8
- export async function verifyContainerDestinationProjection(input) {
9
+ export function verifyContainerDestinationProjection(input) {
10
+ return verifyWithHeldBundleRecovery(input, () => verifyContainerDestinationProjectionOnce(input));
11
+ }
12
+ async function verifyContainerDestinationProjectionOnce(input) {
9
13
  const bundlesByHash = new Map();
10
14
  addContainerWriterProjectionBundles(bundlesByHash, input.projection, "Container destination");
11
15
  const verifiedByHash = new Map();
@@ -1 +1 @@
1
- {"version":3,"file":"containerDestinationVerification.js","sourceRoot":"","sources":["containerDestinationVerification.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,iCAAiC,EACjC,6B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QACrB,4BAA4B,EAAE,IAAI;QAClC,uBAAuB,EAAE,YAAY;QACrC,aAAa;QACb,iBAAiB;QACjB,uBAAuB,EAAE,KAAK;QAC9B,eAAe,EAAE,KAAK;QACtB,KAAK,EAAE,uBAAuB;QAC9B,IAAI,EAAE,KAAK,CAAC,UAAU,CAAC,IAAI;QAC3B,oBAAoB;QACpB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,cAAc;KACf,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,uBAAuB,CACrC,iBAAiB,EACjB,KAAK,CAAC,YAAY,CACnB,CAAC;IACF,kEAAkE;IAClE,gCAAgC,CAC9B,iBAAiB,EACjB,aAAa,EACb,cAAc,CACf,CAAC;IACF,4EAA4E;IAC5E,qEAAqE;IACrE,mDAAmD;IACnD,wBAAwB,CAAC,iBAAiB,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;IAChE,MAAM,6BAA6B,CAAC,iBAAiB,EAAE;QACrD,YAAY,EAAE,OAAO;QACrB,8BAA8B,EAAE,KAAK;KACtC,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAClC,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\nimport { addContainerWriterProjectionBundles } from \"./containerProjectionVerification\";\n\n/** Authenticate immutable destination roles without advancing write-authority pins. */\nexport async function verifyContainerDestinationProjection(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<{\n readonly path: VerifiedContainerAccessManifest[];\n /** Every manifest verified on the way, including each head's lineage. */\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n input.projection,\n \"Container destination\",\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const principalPolicyCache = new Map();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [...bundlesByHash.values()],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const path = await verifyContainerManifestPath({\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext,\n enforceLocalCheckpoints: false,\n servedAsCurrent: false,\n label: \"Container destination\",\n path: input.projection.path,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n });\n const current = projectionLifetimeGuard(\n checkpointContext,\n input.stillCurrent,\n );\n // Authenticated bytes, not authority: a later read may cite them.\n observeVerifiedProjectionBundles(\n checkpointContext,\n bundlesByHash,\n verifiedByHash,\n );\n // Destination roles never unwrap these levels; a citation refills them only\n // where the API's current level has the same digest, and the reading\n // verification then checks them like served bytes.\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, {\n stillCurrent: current,\n persistVerificationCheckpoints: false,\n });\n assertProjectionVerificationCurrent(current);\n return { path, verifiedByHash };\n}\n"]}
1
+ {"version":3,"file":"containerDestinationVerification.js","sourceRoot":"","sources":["containerDestinationVerification.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAMjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AAmBxF,uFAAuF;AACvF,MAAM,UAAU,oCAAoC,CAClD,KAA0C;IAE1C,OAAO,4BAA4B,CAAC,KAAK,EAAE,GAAG,EAAE,CAC9C,wCAAwC,CAAC,KAAK,CAAC,CAChD,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,wCAAwC,CACrD,KAA0C;IAE1C,MAAM,aAAa,GAAG,IAAI,GAAG,EAA4C,CAAC;IAC1E,mCAAmC,CACjC,aAAa,EACb,KAAK,CAAC,UAAU,EAChB,uBAAuB,CACxB,CAAC;IACF,MAAM,cAAc,GAAG,IAAI,GAAG,EAA2C,CAAC;IAC1E,MAAM,iBAAiB,GAAG,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,EAAE;QACrD,YAAY,EAAE,OAAO;QACrB,8BAA8B,EAAE,KAAK;KACtC,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAClC,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyWithHeldBundleRecovery } from \"../checkpoints/heldBundleRecovery\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\nimport { addContainerWriterProjectionBundles } from \"./containerProjectionVerification\";\n\ninterface ContainerDestinationProjectionInput {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\ninterface VerifiedContainerDestination {\n readonly path: VerifiedContainerAccessManifest[];\n /** Every manifest verified on the way, including each head's lineage. */\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}\n\n/** Authenticate immutable destination roles without advancing write-authority pins. */\nexport function verifyContainerDestinationProjection(\n input: ContainerDestinationProjectionInput,\n): Promise<VerifiedContainerDestination> {\n return verifyWithHeldBundleRecovery(input, () =>\n verifyContainerDestinationProjectionOnce(input),\n );\n}\n\nasync function verifyContainerDestinationProjectionOnce(\n input: ContainerDestinationProjectionInput,\n): Promise<VerifiedContainerDestination> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n input.projection,\n \"Container destination\",\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const principalPolicyCache = new Map();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [...bundlesByHash.values()],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const path = await verifyContainerManifestPath({\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext,\n enforceLocalCheckpoints: false,\n servedAsCurrent: false,\n label: \"Container destination\",\n path: input.projection.path,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n });\n const current = projectionLifetimeGuard(\n checkpointContext,\n input.stillCurrent,\n );\n // Authenticated bytes, not authority: a later read may cite them.\n observeVerifiedProjectionBundles(\n checkpointContext,\n bundlesByHash,\n verifiedByHash,\n );\n // Destination roles never unwrap these levels; a citation refills them only\n // where the API's current level has the same digest, and the reading\n // verification then checks them like served bytes.\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, {\n stillCurrent: current,\n persistVerificationCheckpoints: false,\n });\n assertProjectionVerificationCurrent(current);\n return { path, verifiedByHash };\n}\n"]}
@@ -2,6 +2,7 @@ import { computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, t
2
2
  import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
3
3
  import { addBundleByHash } from "../checkpoints/bundleVerification.js";
4
4
  import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeAccessManifestCheckpoints, observeVerifiedKekLevels, observeVerifiedProjectionBundles, } from "../checkpoints/checkpointContext.js";
5
+ import { verifyWithHeldBundleRecovery } from "../checkpoints/heldBundleRecovery.js";
5
6
  import { throwKeyingVerificationShapeFailure } from "../error.js";
6
7
  import { collectReferencedPrincipalPolicies } from "../principalPolicy/principalPolicyVerification.js";
7
8
  import { verifyProjectionAuthorizationEvidence } from "../principalPolicy/projectionAuthorizationEvidence.js";
@@ -169,7 +170,10 @@ export async function verifyContainerWriterProjectionWithContext(input, checkpoi
169
170
  checkpointContext.heldContainerHeads.push(...verifiedPath);
170
171
  return verifiedPath;
171
172
  }
172
- export async function verifyContainerWriterProjection(input) {
173
+ export function verifyContainerWriterProjection(input) {
174
+ return verifyWithHeldBundleRecovery(input, () => verifyContainerWriterProjectionOnce(input));
175
+ }
176
+ async function verifyContainerWriterProjectionOnce(input) {
173
177
  try {
174
178
  assertProjectionVerificationCurrent(input.stillCurrent);
175
179
  const verifiedByHash = input.verifiedByHash ??
@@ -195,7 +199,10 @@ export async function verifyContainerWriterProjection(input) {
195
199
  throwKeyingVerificationShapeFailure(error);
196
200
  }
197
201
  }
198
- export async function collectContainerWriterProjectionPrincipalPolicies(input) {
202
+ export function collectContainerWriterProjectionPrincipalPolicies(input) {
203
+ return verifyWithHeldBundleRecovery(input, () => collectContainerWriterProjectionPrincipalPoliciesOnce(input));
204
+ }
205
+ async function collectContainerWriterProjectionPrincipalPoliciesOnce(input) {
199
206
  try {
200
207
  assertProjectionVerificationCurrent(input.stillCurrent);
201
208
  const warmReferencedPrincipalPolicies = generationGuardedPrincipalPolicyWarmer(input.warmReferencedPrincipalPolicies, input.stillCurrent);
@@ -1 +1 @@
1
- {"version":3,"file":"containerProjectionVerification.js","sourceRoot":"","sources":["containerProjectionVerification.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,sCAAsC,EACtC,4BAA4B,EAC5B,aAAa,EAGb,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AACpG,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EACL,+BAA+B,EAC/B,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAOpB,OAAO,EACL,mCAAmC,EACnC,sCAAsC,EACtC,iCAAiC,GAClC,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAE1E,KAAK,UAAU,iCAAiC,CAAC,KAGhD;IACC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,GAAG,CACR,KAAK,CAAC,iBAAiB,CAAC,KAAK,CAAC,YAAY;aACvC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC;aAC/C,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,CACnC;KACF,CAAC,IAAI,EAAE,CAAC;IACT,MAAM,iBAAiB,GAAgC,EAAE,CAAC;IAE1D,KAAK,MAAM,MAAM,IAAI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AAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAC5E,CAAC;IAEF,OAAO,kCAAkC,CAAC;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,wBAAwB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyAuthorization } from \"@tearleads/crypto\";\nimport {\n type ContainerUserRecipientKey,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n toFingerprint,\n type VerifiedContainerAccessManifest,\n type VerifiedContainerKekState,\n verifyContainerKekState,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { collectReferencedPrincipalPolicies } from \"../principalPolicy/principalPolicyVerification\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport {\n readContainerKekRecipientTarget,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../readers\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n withGenerationGuardedPolicyWarmer,\n} from \"../types\";\nimport { verifyContainerManifestBundle } from \"./containerManifestVerification\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\n\nasync function collectContainerUserRecipientKeys(input: {\n readonly containerManifest: VerifiedContainerAccessManifest;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<ContainerUserRecipientKey[]> {\n const userIds = [\n ...new Set(\n input.containerManifest.state.directGrants\n .filter((grant) => grant.subjectType === \"user\")\n .map((grant) => grant.subjectId),\n ),\n ].sort();\n const userRecipientKeys: ContainerUserRecipientKey[] = [];\n\n for (const userId of userIds) {\n const userKey = await input.resolveUserKey(userId);\n if (!userKey) {\n throw new ProjectionDependencyUnavailableError(\n `Container writer projection recipient key could not be resolved for ${userId}`,\n );\n }\n const recipientKeyFingerprint = await toFingerprint(\n userKey.encapsulationPublicKey,\n );\n userRecipientKeys.push({\n userId,\n recipientKeyEpochId: `user:${userId}:encapsulation:${recipientKeyFingerprint}`,\n recipientKeyFingerprint,\n });\n }\n\n return userRecipientKeys;\n}\n\nfunction containerKekManifestHistory(input: {\n readonly history: readonly VerifiedContainerAccessManifest[];\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n}): VerifiedContainerAccessManifest[] {\n const historyByHash = new Map<string, VerifiedContainerAccessManifest>();\n\n for (const manifest of input.history) {\n if (\n manifest.state.containerId === input.verifiedManifest.state.containerId &&\n manifest.manifestHash !== input.verifiedManifest.manifestHash\n ) {\n historyByHash.set(manifest.manifestHash, manifest);\n }\n }\n\n return [...historyByHash.values()];\n}\n\nasync function verifyContainerKekProjection(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly kek: ContainerWriterProjectionResponse[\"containerKeks\"][number];\n readonly label: string;\n readonly parentKekState: VerifiedContainerKekState | null;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n readonly verifiedManifestHistory: readonly VerifiedContainerAccessManifest[];\n readonly parentManifestHistory: readonly VerifiedContainerAccessManifest[];\n}): Promise<VerifiedContainerKekState> {\n if (input.verifiedManifest.state.parentContainerId && !input.parentKekState) {\n throw new Error(`${input.label} requires verified parent KEK state`);\n }\n\n const keyEpoch = readContainerKeyEpoch(\n input.kek.keyEpoch,\n `${input.label} key epoch`,\n );\n const wraps = input.kek.wraps.map((wrap, index) =>\n readContainerKeyWrap(wrap, `${input.label} wrap[${index}]`),\n );\n const userRecipientKeys = await collectContainerUserRecipientKeys({\n containerManifest: input.verifiedManifest,\n resolveUserKey: input.resolveUserKey,\n });\n const verifiedKekManifestHistory = containerKekManifestHistory({\n history: input.verifiedManifestHistory,\n verifiedManifest: input.verifiedManifest,\n });\n const verified = await verifyContainerKekState({\n allowHistoricalParentEpoch: true,\n containerManifest: input.verifiedManifest,\n containerManifestHistory: verifiedKekManifestHistory,\n parentManifestHistory: input.parentManifestHistory,\n keyEpoch,\n parentKekState: input.parentKekState,\n principalPolicies: input.authorizationEvidence,\n userRecipientKeys,\n wraps,\n });\n if (!verified.ok) {\n throw new Error(`${input.label} KEK verification failed`);\n }\n\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n if (keyEpochHash !== input.kek.keyEpochHash) {\n throw new Error(`${input.label} key epoch hash mismatch`);\n }\n const recipientTargets = input.kek.recipientTargets.map((target, index) =>\n readContainerKekRecipientTarget(\n target,\n `${input.label} recipient target[${index}]`,\n ),\n );\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n if (\n keyTargetHash !== input.kek.keyTargetHash ||\n keyTargetHash !== verified.value.keyTargetHash\n ) {\n throw new Error(`${input.label} target hash mismatch`);\n }\n if (\n verified.value.containerKeyEpochId !== input.kek.containerKeyEpochId ||\n verified.value.containerKeyEpoch !== input.kek.containerKeyEpoch ||\n verified.value.accessManifestHash !== input.kek.accessManifestHash ||\n verified.value.parentContainerKeyEpochId !==\n input.kek.parentContainerKeyEpochId\n ) {\n throw new Error(`${input.label} identity mismatch`);\n }\n\n return verified.value;\n}\n\ninterface ContainerWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nexport function verifiedContainerManifestsForBundles(\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n): VerifiedContainerAccessManifest[] {\n return [...bundlesByHash.keys()].flatMap((manifestHash) => {\n const verified = verifiedByHash.get(manifestHash);\n return verified ? [verified] : [];\n });\n}\n\nfunction collectContainerProjectionBundles(\n projection: ContainerWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n projection,\n \"Container writer projection\",\n );\n return bundlesByHash;\n}\n\nexport async function verifyContainerWriterProjectionWithContext(\n input: Omit<\n ContainerWriterProjectionVerificationInput,\n \"execSql\" | \"openPrincipalPolicyBundleReader\"\n > & {\n readonly authorizationEvidence?: readonly PrincipalPolicyAuthorization[];\n },\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedContainerAccessManifest[]> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n\n const bundlesByHash = collectContainerProjectionBundles(input.projection);\n\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verification = {\n checkpointContext,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n };\n const authorizationEvidence =\n input.authorizationEvidence ??\n (await verifyProjectionAuthorizationEvidence({\n ...verification,\n bundles: [...bundlesByHash.values()],\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n stillCurrent: input.stillCurrent,\n }));\n const verifiedPath = await verifyContainerManifestPath({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: true,\n bundlesByHash,\n enforceLocalCheckpoints: true,\n label: \"Container writer projection path\",\n path: input.projection.path,\n verifiedByHash,\n });\n\n const verifiedKekStates: VerifiedContainerKekState[] = [];\n for (const [index, kek] of input.projection.containerKeks.entries()) {\n const verifiedManifest = verifiedPath[index];\n if (!verifiedManifest) {\n throw new Error(`Container writer projection KEK[${index}] is missing`);\n }\n const verifiedManifestHistory: VerifiedContainerAccessManifest[] = [];\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n verifiedManifestHistory.push(\n await verifyContainerManifestBundle({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle,\n bundlesByHash,\n enforceLocalCheckpoint: false,\n label: `Container writer projection KEK[${index}] history[${historyIndex}]`,\n parentPath: verifiedPath.slice(0, index),\n verifiedByHash,\n }),\n );\n }\n\n const verifiedKekState = await verifyContainerKekProjection({\n authorizationEvidence,\n kek,\n label: `Container writer projection KEK[${index}]`,\n parentKekState: index > 0 ? (verifiedKekStates[index - 1] ?? null) : null,\n resolveUserKey: input.resolveUserKey,\n verifiedManifest,\n verifiedManifestHistory,\n parentManifestHistory: [...verifiedByHash.values()],\n });\n verifiedKekStates.push(verifiedKekState);\n }\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: verifiedPath,\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n checkpointContext.heldContainerHeads.push(...verifiedPath);\n return verifiedPath;\n}\n\nexport async function verifyContainerWriterProjection(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<VerifiedContainerAccessManifest[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const guardedInput = {\n ...withGenerationGuardedPolicyWarmer(input),\n verifiedByHash,\n };\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n guardedInput,\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return verifiedPath;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport async function collectContainerWriterProjectionPrincipalPolicies(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<PrincipalPolicyCurrentEvidence[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n {\n principalPolicyCache,\n projection: input.projection,\n verifiedByHash,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n },\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n\n const policies = await collectPrincipalPoliciesForContainerPaths({\n checkpointContext,\n organizationId: input.projection.organizationId,\n paths: [verifiedPath],\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function addContainerWriterProjectionBundles(\n bundlesByHash: Map<string, AccessManifestBundleWireResponse>,\n projection: ContainerWriterProjectionResponse,\n label: string,\n): void {\n for (const [index, bundle] of projection.path.entries()) {\n addBundleByHash(bundlesByHash, bundle, `${label} path[${index}]`);\n }\n for (const [kekIndex, kek] of projection.containerKeks.entries()) {\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `${label} KEK[${kekIndex}] history[${historyIndex}]`,\n );\n }\n }\n}\n\nasync function collectPrincipalPoliciesForContainerPaths(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n paths: readonly (readonly VerifiedContainerAccessManifest[] | undefined)[];\n principalPolicyCache: PrincipalPolicyCache;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const referencedPrincipalHeads = input.paths.flatMap((path) =>\n (path ?? []).flatMap((manifest) => manifest.state.referencedPrincipalHeads),\n );\n\n return collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references: referencedPrincipalHeads,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
1
+ {"version":3,"file":"containerProjectionVerification.js","sourceRoot":"","sources":["containerProjectionVerification.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,sCAAsC,EACtC,4BAA4B,EAC5B,aAAa,EAGb,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AACpG,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EACL,+BAA+B,EAC/B,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAOpB,OAAO,EACL,mCAAmC,EACnC,sCAAsC,EACtC,iCAAiC,GAClC,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAE1E,KAAK,UAAU,iCAAiC,CAAC,KAGhD;IACC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,GAAG,CACR,KAAK,CAAC,iBAAiB,CAAC,KAAK,CAAC,YAAY;aAC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C,CAAC;IACpE,CAAC;IACD,KAAK,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,IAAI,UAAU,CAAC,aAAa,CAAC,OAAO,EAAE,EAAE,CAAC;QACjE,KAAK,MAAM,CACT,YAAY,EACZ,MAAM,EACP,IAAI,GAAG,CAAC,wBAAwB,CAAC,OAAO,EAAE,EAAE,CAAC;YAC5C,eAAe,CACb,aAAa,EACb,MAAM,EACN,GAAG,KAAK,QAAQ,QAAQ,aAAa,YAAY,GAAG,CACrD,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC;AAED,KAAK,UAAU,yCAAyC,CAAC,KAOxD;IACC,MAAM,wBAAwB,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAC5D,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAC5E,CAAC;IAEF,OAAO,kCAAkC,CAAC;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,wBAAwB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyAuthorization } from \"@tearleads/crypto\";\nimport {\n type ContainerUserRecipientKey,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n toFingerprint,\n type VerifiedContainerAccessManifest,\n type VerifiedContainerKekState,\n verifyContainerKekState,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyWithHeldBundleRecovery } from \"../checkpoints/heldBundleRecovery\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { collectReferencedPrincipalPolicies } from \"../principalPolicy/principalPolicyVerification\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport {\n readContainerKekRecipientTarget,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../readers\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n withGenerationGuardedPolicyWarmer,\n} from \"../types\";\nimport { verifyContainerManifestBundle } from \"./containerManifestVerification\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\n\nasync function collectContainerUserRecipientKeys(input: {\n readonly containerManifest: VerifiedContainerAccessManifest;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<ContainerUserRecipientKey[]> {\n const userIds = [\n ...new Set(\n input.containerManifest.state.directGrants\n .filter((grant) => grant.subjectType === \"user\")\n .map((grant) => grant.subjectId),\n ),\n ].sort();\n const userRecipientKeys: ContainerUserRecipientKey[] = [];\n\n for (const userId of userIds) {\n const userKey = await input.resolveUserKey(userId);\n if (!userKey) {\n throw new ProjectionDependencyUnavailableError(\n `Container writer projection recipient key could not be resolved for ${userId}`,\n );\n }\n const recipientKeyFingerprint = await toFingerprint(\n userKey.encapsulationPublicKey,\n );\n userRecipientKeys.push({\n userId,\n recipientKeyEpochId: `user:${userId}:encapsulation:${recipientKeyFingerprint}`,\n recipientKeyFingerprint,\n });\n }\n\n return userRecipientKeys;\n}\n\nfunction containerKekManifestHistory(input: {\n readonly history: readonly VerifiedContainerAccessManifest[];\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n}): VerifiedContainerAccessManifest[] {\n const historyByHash = new Map<string, VerifiedContainerAccessManifest>();\n\n for (const manifest of input.history) {\n if (\n manifest.state.containerId === input.verifiedManifest.state.containerId &&\n manifest.manifestHash !== input.verifiedManifest.manifestHash\n ) {\n historyByHash.set(manifest.manifestHash, manifest);\n }\n }\n\n return [...historyByHash.values()];\n}\n\nasync function verifyContainerKekProjection(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly kek: ContainerWriterProjectionResponse[\"containerKeks\"][number];\n readonly label: string;\n readonly parentKekState: VerifiedContainerKekState | null;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n readonly verifiedManifestHistory: readonly VerifiedContainerAccessManifest[];\n readonly parentManifestHistory: readonly VerifiedContainerAccessManifest[];\n}): Promise<VerifiedContainerKekState> {\n if (input.verifiedManifest.state.parentContainerId && !input.parentKekState) {\n throw new Error(`${input.label} requires verified parent KEK state`);\n }\n\n const keyEpoch = readContainerKeyEpoch(\n input.kek.keyEpoch,\n `${input.label} key epoch`,\n );\n const wraps = input.kek.wraps.map((wrap, index) =>\n readContainerKeyWrap(wrap, `${input.label} wrap[${index}]`),\n );\n const userRecipientKeys = await collectContainerUserRecipientKeys({\n containerManifest: input.verifiedManifest,\n resolveUserKey: input.resolveUserKey,\n });\n const verifiedKekManifestHistory = containerKekManifestHistory({\n history: input.verifiedManifestHistory,\n verifiedManifest: input.verifiedManifest,\n });\n const verified = await verifyContainerKekState({\n allowHistoricalParentEpoch: true,\n containerManifest: input.verifiedManifest,\n containerManifestHistory: verifiedKekManifestHistory,\n parentManifestHistory: input.parentManifestHistory,\n keyEpoch,\n parentKekState: input.parentKekState,\n principalPolicies: input.authorizationEvidence,\n userRecipientKeys,\n wraps,\n });\n if (!verified.ok) {\n throw new Error(`${input.label} KEK verification failed`);\n }\n\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n if (keyEpochHash !== input.kek.keyEpochHash) {\n throw new Error(`${input.label} key epoch hash mismatch`);\n }\n const recipientTargets = input.kek.recipientTargets.map((target, index) =>\n readContainerKekRecipientTarget(\n target,\n `${input.label} recipient target[${index}]`,\n ),\n );\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n if (\n keyTargetHash !== input.kek.keyTargetHash ||\n keyTargetHash !== verified.value.keyTargetHash\n ) {\n throw new Error(`${input.label} target hash mismatch`);\n }\n if (\n verified.value.containerKeyEpochId !== input.kek.containerKeyEpochId ||\n verified.value.containerKeyEpoch !== input.kek.containerKeyEpoch ||\n verified.value.accessManifestHash !== input.kek.accessManifestHash ||\n verified.value.parentContainerKeyEpochId !==\n input.kek.parentContainerKeyEpochId\n ) {\n throw new Error(`${input.label} identity mismatch`);\n }\n\n return verified.value;\n}\n\ninterface ContainerWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nexport function verifiedContainerManifestsForBundles(\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n): VerifiedContainerAccessManifest[] {\n return [...bundlesByHash.keys()].flatMap((manifestHash) => {\n const verified = verifiedByHash.get(manifestHash);\n return verified ? [verified] : [];\n });\n}\n\nfunction collectContainerProjectionBundles(\n projection: ContainerWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n projection,\n \"Container writer projection\",\n );\n return bundlesByHash;\n}\n\nexport async function verifyContainerWriterProjectionWithContext(\n input: Omit<\n ContainerWriterProjectionVerificationInput,\n \"execSql\" | \"openPrincipalPolicyBundleReader\"\n > & {\n readonly authorizationEvidence?: readonly PrincipalPolicyAuthorization[];\n },\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedContainerAccessManifest[]> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n\n const bundlesByHash = collectContainerProjectionBundles(input.projection);\n\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verification = {\n checkpointContext,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n };\n const authorizationEvidence =\n input.authorizationEvidence ??\n (await verifyProjectionAuthorizationEvidence({\n ...verification,\n bundles: [...bundlesByHash.values()],\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n stillCurrent: input.stillCurrent,\n }));\n const verifiedPath = await verifyContainerManifestPath({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: true,\n bundlesByHash,\n enforceLocalCheckpoints: true,\n label: \"Container writer projection path\",\n path: input.projection.path,\n verifiedByHash,\n });\n\n const verifiedKekStates: VerifiedContainerKekState[] = [];\n for (const [index, kek] of input.projection.containerKeks.entries()) {\n const verifiedManifest = verifiedPath[index];\n if (!verifiedManifest) {\n throw new Error(`Container writer projection KEK[${index}] is missing`);\n }\n const verifiedManifestHistory: VerifiedContainerAccessManifest[] = [];\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n verifiedManifestHistory.push(\n await verifyContainerManifestBundle({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle,\n bundlesByHash,\n enforceLocalCheckpoint: false,\n label: `Container writer projection KEK[${index}] history[${historyIndex}]`,\n parentPath: verifiedPath.slice(0, index),\n verifiedByHash,\n }),\n );\n }\n\n const verifiedKekState = await verifyContainerKekProjection({\n authorizationEvidence,\n kek,\n label: `Container writer projection KEK[${index}]`,\n parentKekState: index > 0 ? (verifiedKekStates[index - 1] ?? null) : null,\n resolveUserKey: input.resolveUserKey,\n verifiedManifest,\n verifiedManifestHistory,\n parentManifestHistory: [...verifiedByHash.values()],\n });\n verifiedKekStates.push(verifiedKekState);\n }\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: verifiedPath,\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n checkpointContext.heldContainerHeads.push(...verifiedPath);\n return verifiedPath;\n}\n\nexport function verifyContainerWriterProjection(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<VerifiedContainerAccessManifest[]> {\n return verifyWithHeldBundleRecovery(input, () =>\n verifyContainerWriterProjectionOnce(input),\n );\n}\n\nasync function verifyContainerWriterProjectionOnce(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<VerifiedContainerAccessManifest[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const guardedInput = {\n ...withGenerationGuardedPolicyWarmer(input),\n verifiedByHash,\n };\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n guardedInput,\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return verifiedPath;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function collectContainerWriterProjectionPrincipalPolicies(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<PrincipalPolicyCurrentEvidence[]> {\n return verifyWithHeldBundleRecovery(input, () =>\n collectContainerWriterProjectionPrincipalPoliciesOnce(input),\n );\n}\n\nasync function collectContainerWriterProjectionPrincipalPoliciesOnce(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<PrincipalPolicyCurrentEvidence[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n {\n principalPolicyCache,\n projection: input.projection,\n verifiedByHash,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n },\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n\n const policies = await collectPrincipalPoliciesForContainerPaths({\n checkpointContext,\n organizationId: input.projection.organizationId,\n paths: [verifiedPath],\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function addContainerWriterProjectionBundles(\n bundlesByHash: Map<string, AccessManifestBundleWireResponse>,\n projection: ContainerWriterProjectionResponse,\n label: string,\n): void {\n for (const [index, bundle] of projection.path.entries()) {\n addBundleByHash(bundlesByHash, bundle, `${label} path[${index}]`);\n }\n for (const [kekIndex, kek] of projection.containerKeks.entries()) {\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `${label} KEK[${kekIndex}] history[${historyIndex}]`,\n );\n }\n }\n}\n\nasync function collectPrincipalPoliciesForContainerPaths(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n paths: readonly (readonly VerifiedContainerAccessManifest[] | undefined)[];\n principalPolicyCache: PrincipalPolicyCache;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const referencedPrincipalHeads = input.paths.flatMap((path) =>\n (path ?? []).flatMap((manifest) => manifest.state.referencedPrincipalHeads),\n );\n\n return collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references: referencedPrincipalHeads,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
@@ -1,6 +1,7 @@
1
+ import { deriveDecodedProjection, } from "../../../internal/validators/response/index.js";
1
2
  /** Document paths share the one proof carried by their enclosing projection. */
2
3
  export function documentContainerProjections(document) {
3
- return document.authorizingContainerPaths.map((path) => ({
4
+ return document.authorizingContainerPaths.map((path) => deriveDecodedProjection(document, {
4
5
  ...path,
5
6
  policyEvidence: document.policyEvidence,
6
7
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"documentContainerProjections.js","sourceRoot":"","sources":["documentContainerProjections.ts"],"names":[],"mappings":"AAKA,gFAAgF;AAChF,MAAM,UAAU,4BAA4B,CAC1C,QAA0C;IAE1C,OAAO,QAAQ,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACvD,GAAG,IAAI;QACP,cAAc,EAAE,QAAQ,CAAC,cAAc;KACxC,CAAC,CAAC,CAAC;AACN,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\n\n/** Document paths share the one proof carried by their enclosing projection. */\nexport function documentContainerProjections(\n document: DocumentWriterProjectionResponse,\n): ContainerWriterProjectionResponse[] {\n return document.authorizingContainerPaths.map((path) => ({\n ...path,\n policyEvidence: document.policyEvidence,\n }));\n}\n"]}
1
+ {"version":3,"file":"documentContainerProjections.js","sourceRoot":"","sources":["documentContainerProjections.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,GACxB,MAAM,gCAAgC,CAAC;AAExC,gFAAgF;AAChF,MAAM,UAAU,4BAA4B,CAC1C,QAA0C;IAE1C,OAAO,QAAQ,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,uBAAuB,CAAC,QAAQ,EAAE;QAChC,GAAG,IAAI;QACP,cAAc,EAAE,QAAQ,CAAC,cAAc;KACxC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerWriterProjectionResponse,\n type DocumentWriterProjectionResponse,\n deriveDecodedProjection,\n} from \"@tearleads/validators/response\";\n\n/** Document paths share the one proof carried by their enclosing projection. */\nexport function documentContainerProjections(\n document: DocumentWriterProjectionResponse,\n): ContainerWriterProjectionResponse[] {\n return document.authorizingContainerPaths.map((path) =>\n deriveDecodedProjection(document, {\n ...path,\n policyEvidence: document.policyEvidence,\n }),\n );\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { addBundleByHash } from "../checkpoints/bundleVerification.js";
2
2
  import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeAccessManifestCheckpoints, observeVerifiedKekLevels, observeVerifiedProjectionBundles, } from "../checkpoints/checkpointContext.js";
3
+ import { verifyWithHeldBundleRecovery } from "../checkpoints/heldBundleRecovery.js";
3
4
  import { verifyContainerManifestPath } from "../container/containerPathVerification.js";
4
5
  import { addContainerWriterProjectionBundles, verifiedContainerManifestsForBundles, verifyContainerWriterProjectionWithContext, } from "../container/containerProjectionVerification.js";
5
6
  import { rejectPurgedDocumentProjection } from "../documentPurge/documentPurgeCheckpointEnforcement.js";
@@ -147,7 +148,10 @@ function observeVerifiedDocumentProjectionBundles(checkpointContext, projection,
147
148
  .map((manifest) => [manifest.manifestHash, manifest])));
148
149
  observeVerifiedKekLevels(checkpointContext, projection.authorizingContainerPaths);
149
150
  }
150
- export async function verifyDocumentWriterProjection(input) {
151
+ export function verifyDocumentWriterProjection(input) {
152
+ return verifyWithHeldBundleRecovery(input, () => verifyDocumentWriterProjectionOnce(input));
153
+ }
154
+ async function verifyDocumentWriterProjectionOnce(input) {
151
155
  const checkpointContext = createProjectionCheckpointContext({
152
156
  execSql: input.execSql,
153
157
  openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,
@@ -157,7 +161,10 @@ export async function verifyDocumentWriterProjection(input) {
157
161
  await finalizeProjectionCheckpoints(checkpointContext, input);
158
162
  return verified.headManifest;
159
163
  }
160
- export async function verifyDocumentWriterProjectionAuthorization(input) {
164
+ export function verifyDocumentWriterProjectionAuthorization(input) {
165
+ return verifyWithHeldBundleRecovery(input, () => verifyDocumentWriterProjectionAuthorizationOnce(input));
166
+ }
167
+ async function verifyDocumentWriterProjectionAuthorizationOnce(input) {
161
168
  try {
162
169
  const checkpointContext = createProjectionCheckpointContext({
163
170
  execSql: input.execSql,