@tearleads/client-sdk 0.1.14 → 0.1.15

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/containerContents.js +2 -1
  2. package/client/containerContents.js.map +1 -1
  3. package/data/documents/blob/shared/types.d.ts +4 -0
  4. package/data/documents/blob/shared/types.js.map +1 -1
  5. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js +2 -0
  6. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
  7. package/data/keyingProjectionVerification/checkpointContext.d.ts +2 -1
  8. package/data/keyingProjectionVerification/checkpointContext.js +22 -0
  9. package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
  10. package/data/keyingProjectionVerification/containerDestinationVerification.js +11 -1
  11. package/data/keyingProjectionVerification/containerDestinationVerification.js.map +1 -1
  12. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  13. package/data/keyingProjectionVerification/containerPathVerification.js.map +1 -1
  14. package/data/keyingProjectionVerification/containerProjectionVerification.d.ts +3 -2
  15. package/data/keyingProjectionVerification/containerProjectionVerification.js +10 -11
  16. package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
  17. package/data/keyingProjectionVerification/documentManifestPolicies.js.map +1 -1
  18. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  19. package/data/keyingProjectionVerification/documentProjectionVerification.d.ts +2 -3
  20. package/data/keyingProjectionVerification/documentProjectionVerification.js +4 -0
  21. package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
  22. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js +14 -12
  23. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js.map +1 -1
  24. package/data/keyingProjectionVerification/organizationFounderBinding.js.map +1 -1
  25. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js +33 -6
  26. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +1 -1
  27. package/data/keyingProjectionVerification/projectionLifetimes.js +13 -0
  28. package/data/keyingProjectionVerification/projectionLifetimes.js.map +1 -0
  29. package/data/keyingProjectionVerification/projectionPolicyEvidence.js +19 -66
  30. package/data/keyingProjectionVerification/projectionPolicyEvidence.js.map +1 -1
  31. package/data/keyingProjectionVerification/types.d.ts +13 -2
  32. package/data/keyingProjectionVerification/types.js +15 -0
  33. package/data/keyingProjectionVerification/types.js.map +1 -1
  34. package/data/persistence/keyingCheckpointAdvancePersistence.js +4 -1
  35. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +1 -1
  36. package/data/persistence/organizationFounderPersistence.js +2 -2
  37. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  38. package/data/persistence/principalAuthorizationCheckpoints.js +29 -0
  39. package/data/persistence/principalAuthorizationCheckpoints.js.map +1 -0
  40. package/data/persistence/principalHistoryEvidencePersistence.d.ts +30 -0
  41. package/data/persistence/principalHistoryPrefixPersistence.d.ts +24 -0
  42. package/data/persistence/principalHistoryPrefixPersistence.js +6 -2
  43. package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -1
  44. package/data/persistence/principalHistoryStagePersistence.d.ts +21 -0
  45. package/data/principals/principalHistoryRuntime.js +12 -0
  46. package/data/principals/principalHistoryRuntime.js.map +1 -0
  47. package/data/principals/principalHistoryStageProtection.js +2 -12
  48. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  49. package/data/principals/principalPolicyEvidence.d.ts +2 -2
  50. package/data/principals/principalPolicyEvidence.js.map +1 -1
  51. package/data/sqlite/principalHistoryEvidenceSchema.d.ts +308 -0
  52. package/data/sqlite/principalHistoryStageSchema.d.ts +119 -0
  53. package/index.d.ts +2 -2
  54. package/index.js +1 -1
  55. package/index.js.map +1 -1
  56. package/internal/api-client/ApiCache.d.ts +54 -0
  57. package/internal/api-client/ApiClient.d.ts +255 -309
  58. package/internal/api-client/ApiClient.js +15 -6
  59. package/internal/api-client/ApiClient.js.map +1 -1
  60. package/internal/api-client/index.d.ts +1 -0
  61. package/internal/api-client/index.js.map +1 -1
  62. package/internal/api-client/principalHistoryDeadline.js +20 -0
  63. package/internal/api-client/principalHistoryDeadline.js.map +1 -0
  64. package/internal/api-client/principalHistoryRequest.js +59 -22
  65. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  66. package/internal/api-client/principalHistoryRequestContext.js +18 -5
  67. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  68. package/internal/api-client/principalPolicyRequests.d.ts +799 -0
  69. package/internal/api-client/principalPolicyRequests.js +9 -4
  70. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  71. package/internal/api-client/projectionPolicyHistoryPages.d.ts +9 -0
  72. package/internal/api-client/projectionPolicyHistoryPages.js +88 -0
  73. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -0
  74. package/internal/api-client/writerProjectionRequests.js +26 -0
  75. package/internal/api-client/writerProjectionRequests.js.map +1 -0
  76. package/internal/crypto/keying/principalPolicyHistory.js +4 -0
  77. package/internal/crypto/keying/principalPolicyHistory.js.map +1 -1
  78. package/internal/crypto/keying/principalPolicyHistoryTypes.d.ts +2 -0
  79. package/internal/crypto/keying/principalPolicyHistoryTypes.js.map +1 -1
  80. package/internal/crypto/projectionHistorySlots.js +0 -4
  81. package/internal/crypto/projectionHistorySlots.js.map +1 -1
  82. package/internal/validators/operation/index.d.ts +1 -0
  83. package/internal/validators/operation/index.js +1 -0
  84. package/internal/validators/operation/index.js.map +1 -1
  85. package/internal/validators/operation/principals.d.ts +38 -16
  86. package/internal/validators/operation/principals.js +11 -5
  87. package/internal/validators/operation/principals.js.map +1 -1
  88. package/internal/validators/operation/projectionPolicyHistory.d.ts +512 -0
  89. package/internal/validators/operation/projectionPolicyHistory.js +37 -0
  90. package/internal/validators/operation/projectionPolicyHistory.js.map +1 -0
  91. package/internal/validators/operation/registry.d.ts +2 -0
  92. package/internal/validators/operation/registry.js +2 -0
  93. package/internal/validators/operation/registry.js.map +1 -1
  94. package/internal/validators/operation/writerProjections.d.ts +178 -1224
  95. package/internal/validators/operation/writerProjections.js +9 -2
  96. package/internal/validators/operation/writerProjections.js.map +1 -1
  97. package/internal/validators/response/container.d.ts +84 -612
  98. package/internal/validators/response/documentMutation.d.ts +84 -612
  99. package/internal/validators/response/index.d.ts +1 -0
  100. package/internal/validators/response/index.js +1 -0
  101. package/internal/validators/response/index.js.map +1 -1
  102. package/internal/validators/response/organizationBilling.d.ts +1 -0
  103. package/internal/validators/response/organizationBilling.js +1 -1
  104. package/internal/validators/response/organizationBilling.js.map +1 -1
  105. package/internal/validators/response/principalHistoryPreparation.js +28 -1
  106. package/internal/validators/response/principalHistoryPreparation.js.map +1 -1
  107. package/internal/validators/response/principalPolicySnapshotPage.d.ts +388 -0
  108. package/internal/validators/response/principalPolicySnapshotPage.js +24 -0
  109. package/internal/validators/response/principalPolicySnapshotPage.js.map +1 -0
  110. package/internal/validators/response/projectionPolicyEvidence.d.ts +85 -613
  111. package/internal/validators/response/projectionPolicyEvidence.js +10 -5
  112. package/internal/validators/response/projectionPolicyEvidence.js.map +1 -1
  113. package/package.json +1 -1
  114. package/stores/documents/documentStore/attachmentHydration.js +3 -0
  115. package/stores/documents/documentStore/attachmentHydration.js.map +1 -1
  116. package/stores/documents/documentStore/syncDetachedAttachments.js +3 -0
  117. package/stores/documents/documentStore/syncDetachedAttachments.js.map +1 -1
  118. package/workflows/blobs/decrypt.d.ts +1 -1
  119. package/workflows/blobs/decrypt.js +3 -1
  120. package/workflows/blobs/decrypt.js.map +1 -1
  121. package/workflows/blobs/detach.js +6 -1
  122. package/workflows/blobs/detach.js.map +1 -1
  123. package/workflows/blobs/hydrate.d.ts +3 -1
  124. package/workflows/blobs/hydrate.js +2 -0
  125. package/workflows/blobs/hydrate.js.map +1 -1
  126. package/workflows/blobs/retainedAttachmentVerification.js +2 -0
  127. package/workflows/blobs/retainedAttachmentVerification.js.map +1 -1
  128. package/workflows/container-contents/container-state/createAdoption.js +2 -0
  129. package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
  130. package/workflows/container-contents/container-state/createWithMetadata.js +7 -39
  131. package/workflows/container-contents/container-state/createWithMetadata.js.map +1 -1
  132. package/workflows/container-contents/container-state/createWithMetadataPlan.js +68 -0
  133. package/workflows/container-contents/container-state/createWithMetadataPlan.js.map +1 -0
  134. package/workflows/container-contents/remoteContainerState.js +3 -1
  135. package/workflows/container-contents/remoteContainerState.js.map +1 -1
  136. package/workflows/container-contents/remoteHydration/verifiedDestination.js +3 -0
  137. package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +1 -1
  138. package/workflows/container-contents/runtime.d.ts +3 -0
  139. package/workflows/container-contents/runtime.js +7 -6
  140. package/workflows/container-contents/runtime.js.map +1 -1
  141. package/workflows/documents/create.d.ts +2 -15
  142. package/workflows/documents/create.js +9 -64
  143. package/workflows/documents/create.js.map +1 -1
  144. package/workflows/documents/createProjection.d.ts +14 -0
  145. package/workflows/documents/createProjection.js +26 -0
  146. package/workflows/documents/createProjection.js.map +1 -0
  147. package/workflows/documents/createResponse.js +49 -0
  148. package/workflows/documents/createResponse.js.map +1 -0
  149. package/workflows/documents/linkSetBlobRewraps.js +2 -0
  150. package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
  151. package/workflows/documents/runtime.d.ts +3 -0
  152. package/workflows/documents/runtime.js +3 -2
  153. package/workflows/documents/runtime.js.map +1 -1
  154. package/workflows/documents/syncFailureClassification.js +3 -1
  155. package/workflows/documents/syncFailureClassification.js.map +1 -1
  156. package/workflows/principals/index.d.ts +2 -0
  157. package/workflows/principals/index.js +1 -0
  158. package/workflows/principals/index.js.map +1 -1
  159. package/workflows/principals/policyVerification.js.map +1 -1
  160. package/workflows/principals/principalHistoryRecoveryAuthority.js +20 -0
  161. package/workflows/principals/principalHistoryRecoveryAuthority.js.map +1 -0
  162. package/workflows/principals/principalHistoryRecoveryStage.js +1 -1
  163. package/workflows/principals/principalHistoryRecoveryStage.js.map +1 -1
  164. package/workflows/principals/principalHistoryRecoveryTypes.d.ts +3 -3
  165. package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
  166. package/workflows/principals/principalHistoryRecoveryVerification.js +6 -1
  167. package/workflows/principals/principalHistoryRecoveryVerification.js.map +1 -1
  168. package/workflows/principals/principalRecoveryOutage.js +1 -1
  169. package/workflows/principals/principalRecoveryOutage.js.map +1 -1
  170. package/workflows/principals/publicPrincipalHistoryAuthority.js +60 -0
  171. package/workflows/principals/publicPrincipalHistoryAuthority.js.map +1 -0
  172. package/workflows/principals/publicPrincipalHistoryPage.js +87 -0
  173. package/workflows/principals/publicPrincipalHistoryPage.js.map +1 -0
  174. package/workflows/principals/publicPrincipalHistoryProgress.js +178 -0
  175. package/workflows/principals/publicPrincipalHistoryProgress.js.map +1 -0
  176. package/workflows/principals/publicPrincipalHistoryTypes.d.ts +39 -0
  177. package/workflows/principals/publicPrincipalHistoryTypes.js +2 -0
  178. package/workflows/principals/publicPrincipalHistoryTypes.js.map +1 -0
  179. package/workflows/principals/publicProjectionDirectory.js +40 -0
  180. package/workflows/principals/publicProjectionDirectory.js.map +1 -0
  181. package/workflows/principals/publicProjectionPrincipal.js +53 -0
  182. package/workflows/principals/publicProjectionPrincipal.js.map +1 -0
  183. package/workflows/principals/recoverPrincipalPolicyHistory.js +4 -1
  184. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
  185. package/workflows/principals/recoverProjectionPolicyHistory.d.ts +9 -0
  186. package/workflows/principals/recoverProjectionPolicyHistory.js +98 -0
  187. package/workflows/principals/recoverProjectionPolicyHistory.js.map +1 -0
  188. package/workflows/principals/recoverPublicPrincipalHistory.js +176 -0
  189. package/workflows/principals/recoverPublicPrincipalHistory.js.map +1 -0
  190. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +2 -5
  191. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  192. package/workflows/principals/runtimePolicyRecovery.js +2 -1
  193. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  194. package/workflows/principals/runtimePolicyWarmer.js +2 -0
  195. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  196. package/workflows/principals/runtimeProjectionPolicyRecovery.js +56 -0
  197. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -0
  198. package/workflows/principals/selectPublicPrincipalHistory.js +90 -0
  199. package/workflows/principals/selectPublicPrincipalHistory.js.map +1 -0
  200. package/workflows/registration/provisioningBootstrapBuilders.d.ts +21 -153
@@ -35,6 +35,8 @@ export async function prepareDocumentLinkBlobRewraps(input) {
35
35
  execSql: input.execSql,
36
36
  resolveProjectionUserKey: requireProjectionUserKeyResolver(input.resolveProjectionUserKey, "Attachment relink"),
37
37
  targetSecretKey: input.targetSecretKey,
38
+ stillCurrent: input.stillCurrent,
39
+ warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,
38
40
  writerProjection: input.writerProjection,
39
41
  };
40
42
  const needsKey = input.targets.some((target) => !retainedTarget(binding, target, documentId));
@@ -1 +1 @@
1
- {"version":3,"file":"linkSetBlobRewraps.js","sourceRoot":"","sources":["linkSetBlobRewraps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAG3B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EACL,kCAAkC,EAClC,sBAAsB,GACvB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,gBAAgB,EAChB,SAAS,GACV,MAAM,qCAAqC,CAAC;AAK7C,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,gCAAgC,EAAE,MAAM,yCAAyC,CAAC;AAC3F,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,4BAA4B,EAAE,MAAM,sEAAsE,CAAC;AACpH,OAAO,EAAE,mCAAmC,EAAE,MA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,IAAI,CAAC,GAAG;gBAAE,SAAS;YACnB,MAAM,EAAE,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;YAC7B,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC9B,IAAI,QAAQ;gBACV,gBAAgB,CACd,QAAQ,EACR,GAAG,EACH,sDAAsD,CACvD,CAAC;YACJ,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,cAAc,CAAC,CAAqB,EAAE,CAAqB;IAClE,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n BLOB_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkAccessEventBody,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n BlobAttachmentSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n deriveDocumentTargetFromProjection,\n unwrapContainerKekPath,\n} from \"../../data/documents/shared/projection\";\nimport {\n assertEqualBytes,\n targetKey,\n} from \"../../data/documents/shared/readers\";\nimport type {\n DocumentLinkSetMutationApi,\n ProjectionVerificationOptions,\n} from \"../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../data/documents/shared/types\";\nimport { readCanonicalJson } from \"../../data/keyingCanonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { documentContainerProjections } from \"../../data/keyingProjectionVerification/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { createAttachmentProofReader } from \"../blobs/attachmentDecryptor\";\nimport { createAttachmentKeyAuthenticator } from \"../blobs/attachmentKeyAuthenticator\";\nimport { verifyRetainedAttachment } from \"../blobs/retainedAttachmentVerification\";\n\ninterface BlobRewrap {\n blobId: string;\n contentKeyEpoch: number;\n targets: DocumentLinkAccessEventBody[\"blobRewraps\"][number][\"targets\"][number][];\n}\n\n/** Authenticate the existing bytes before propagating their DEK to a new scope. */\nexport async function prepareDocumentLinkBlobRewraps(\n input: {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<DocumentLinkAccessEventBody[\"blobRewraps\"]> {\n const documentId = input.writerProjection.documentId;\n const bindings = await input.apiClient.listDocumentAttachments(documentId);\n // The API refuses the link unless every active binding is rewrapped, so an\n // unavailable listing (offline, or a 409 while a bind is mid-flight) is a\n // retryable availability failure of this mutation, not integrity evidence.\n if (!bindings)\n throw new ProjectionDependencyUnavailableError(\n \"Document attachments are unavailable for relinking\",\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (bindings.length === 0) return [];\n const keks = await collectRelinkKeks(input);\n const authenticateKey = createAttachmentKeyAuthenticator(\n input.apiClient,\n documentId,\n );\n const verifyRetained = createAttachmentProofReader(\n input.apiClient,\n documentId,\n verifyRetainedAttachment,\n );\n const rewrapByBlob = new Map<string, BlobRewrap>();\n for (const binding of bindings) {\n const verification = {\n binding,\n expectedDocumentId: documentId,\n expectedSlotId: binding.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Attachment relink\",\n ),\n targetSecretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n };\n const needsKey = input.targets.some(\n (target) => !retainedTarget(binding, target, documentId),\n );\n const contentKey = needsKey ? await authenticateKey(verification) : null;\n if (!needsKey) await verifyRetained(verification);\n const targets = await Promise.all(\n input.targets.map(async (target) => {\n const previous = retainedTarget(binding, target, documentId);\n if (previous)\n return {\n ...previous,\n ...target,\n wrappingMetadata: readCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n };\n const kek = keks.get(targetKey(target));\n if (!kek)\n throw new Error(\n \"Attachment destination is not a verified current container head\",\n );\n if (!contentKey)\n throw new Error(\"Attachment content key is unavailable\");\n return wrapBlobKeyForTarget({\n binding,\n contentKey,\n documentId,\n kek,\n target,\n });\n }),\n );\n const rewrap = rewrapByBlob.get(binding.blobId) ?? {\n blobId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n targets: [],\n };\n if (rewrap.contentKeyEpoch !== binding.contentKeyBundle.contentKeyEpoch)\n throw new Error(\"Attachment content epoch changed during relinking\");\n rewrap.targets.push(...targets);\n rewrapByBlob.set(binding.blobId, rewrap);\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n return [...rewrapByBlob.values()].sort(compareBlobIds);\n}\n\nasync function wrapBlobKeyForTarget(input: {\n binding: BlobAttachmentSummary;\n contentKey: Uint8Array;\n documentId: string;\n kek: Uint8Array;\n target: DocumentContentKeyTarget;\n}) {\n const { binding, target } = input;\n const wrapped = await wrapContentKey(input.contentKey, input.kek, {\n kind: \"Blob\",\n objectId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n bindingId: binding.bindingId,\n documentId: input.documentId,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n}\n\nfunction retainedTarget(\n binding: BlobAttachmentSummary,\n target: DocumentContentKeyTarget,\n documentId: string,\n) {\n return binding.contentKeyBundle.targets.find(\n (candidate) =>\n candidate.bindingId === binding.bindingId &&\n candidate.documentId === documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n}\n\nasync function collectRelinkKeks(\n input: Parameters<typeof prepareDocumentLinkBlobRewraps>[0],\n): Promise<Map<string, Uint8Array>> {\n const keks = new Map<string, Uint8Array>();\n for (const projection of [\n ...documentContainerProjections(input.writerProjection),\n input.targetContainerProjection,\n ]) {\n const keys = await unwrapContainerKekPath({\n projection,\n secretKey: input.targetSecretKey,\n execSql: input.execSql,\n ...projectionVerificationOptions(input),\n });\n // Every node of this verified path has a current signed head. Historical\n // keyring entries may open source bytes, but never enter the destination map.\n for (const [index, head] of projection.containerKeks.entries()) {\n const target = deriveDocumentTargetFromProjection({\n ...projection,\n containerId: head.containerId,\n path: projection.path.slice(0, index + 1),\n containerKeks: projection.containerKeks.slice(0, index + 1),\n });\n const key = keys.get(target.containerKeyEpochId);\n // A direct child grantee need not possess any ancestor secret.\n if (!key) continue;\n const id = targetKey(target);\n const previous = keks.get(id);\n if (previous)\n assertEqualBytes(\n previous,\n key,\n \"Attachment link projections contain conflicting KEKs\",\n );\n keks.set(id, key);\n }\n }\n return keks;\n}\n\nfunction compareBlobIds(a: { blobId: string }, b: { blobId: string }): number {\n return a.blobId < b.blobId ? -1 : a.blobId > b.blobId ? 1 : 0;\n}\n"]}
1
+ {"version":3,"file":"linkSetBlobRewraps.js","sourceRoot":"","sources":["linkSetBlobRewraps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAG3B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EACL,kCAAkC,EAClC,sBAAsB,GACvB,MAAM,wC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,IAAI,UAAU,CAAC,aAAa,CAAC,OAAO,EAAE,EAAE,CAAC;YAC/D,MAAM,MAAM,GAAG,kCAAkC,CAAC;gBAChD,GAAG,UAAU;gBACb,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,IAAI,EAAE,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC;gBACzC,aAAa,EAAE,UAAU,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC;aAC5D,CAAC,CAAC;YACH,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;YACjD,+DAA+D;YAC/D,IAAI,CAAC,GAAG;gBAAE,SAAS;YACnB,MAAM,EAAE,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;YAC7B,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC9B,IAAI,QAAQ;gBACV,gBAAgB,CACd,QAAQ,EACR,GAAG,EACH,sDAAsD,CACvD,CAAC;YACJ,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,cAAc,CAAC,CAAqB,EAAE,CAAqB;IAClE,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n BLOB_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkAccessEventBody,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n BlobAttachmentSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n deriveDocumentTargetFromProjection,\n unwrapContainerKekPath,\n} from \"../../data/documents/shared/projection\";\nimport {\n assertEqualBytes,\n targetKey,\n} from \"../../data/documents/shared/readers\";\nimport type {\n DocumentLinkSetMutationApi,\n ProjectionVerificationOptions,\n} from \"../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../data/documents/shared/types\";\nimport { readCanonicalJson } from \"../../data/keyingCanonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { documentContainerProjections } from \"../../data/keyingProjectionVerification/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { createAttachmentProofReader } from \"../blobs/attachmentDecryptor\";\nimport { createAttachmentKeyAuthenticator } from \"../blobs/attachmentKeyAuthenticator\";\nimport { verifyRetainedAttachment } from \"../blobs/retainedAttachmentVerification\";\n\ninterface BlobRewrap {\n blobId: string;\n contentKeyEpoch: number;\n targets: DocumentLinkAccessEventBody[\"blobRewraps\"][number][\"targets\"][number][];\n}\n\n/** Authenticate the existing bytes before propagating their DEK to a new scope. */\nexport async function prepareDocumentLinkBlobRewraps(\n input: {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<DocumentLinkAccessEventBody[\"blobRewraps\"]> {\n const documentId = input.writerProjection.documentId;\n const bindings = await input.apiClient.listDocumentAttachments(documentId);\n // The API refuses the link unless every active binding is rewrapped, so an\n // unavailable listing (offline, or a 409 while a bind is mid-flight) is a\n // retryable availability failure of this mutation, not integrity evidence.\n if (!bindings)\n throw new ProjectionDependencyUnavailableError(\n \"Document attachments are unavailable for relinking\",\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (bindings.length === 0) return [];\n const keks = await collectRelinkKeks(input);\n const authenticateKey = createAttachmentKeyAuthenticator(\n input.apiClient,\n documentId,\n );\n const verifyRetained = createAttachmentProofReader(\n input.apiClient,\n documentId,\n verifyRetainedAttachment,\n );\n const rewrapByBlob = new Map<string, BlobRewrap>();\n for (const binding of bindings) {\n const verification = {\n binding,\n expectedDocumentId: documentId,\n expectedSlotId: binding.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Attachment relink\",\n ),\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n };\n const needsKey = input.targets.some(\n (target) => !retainedTarget(binding, target, documentId),\n );\n const contentKey = needsKey ? await authenticateKey(verification) : null;\n if (!needsKey) await verifyRetained(verification);\n const targets = await Promise.all(\n input.targets.map(async (target) => {\n const previous = retainedTarget(binding, target, documentId);\n if (previous)\n return {\n ...previous,\n ...target,\n wrappingMetadata: readCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n };\n const kek = keks.get(targetKey(target));\n if (!kek)\n throw new Error(\n \"Attachment destination is not a verified current container head\",\n );\n if (!contentKey)\n throw new Error(\"Attachment content key is unavailable\");\n return wrapBlobKeyForTarget({\n binding,\n contentKey,\n documentId,\n kek,\n target,\n });\n }),\n );\n const rewrap = rewrapByBlob.get(binding.blobId) ?? {\n blobId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n targets: [],\n };\n if (rewrap.contentKeyEpoch !== binding.contentKeyBundle.contentKeyEpoch)\n throw new Error(\"Attachment content epoch changed during relinking\");\n rewrap.targets.push(...targets);\n rewrapByBlob.set(binding.blobId, rewrap);\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n return [...rewrapByBlob.values()].sort(compareBlobIds);\n}\n\nasync function wrapBlobKeyForTarget(input: {\n binding: BlobAttachmentSummary;\n contentKey: Uint8Array;\n documentId: string;\n kek: Uint8Array;\n target: DocumentContentKeyTarget;\n}) {\n const { binding, target } = input;\n const wrapped = await wrapContentKey(input.contentKey, input.kek, {\n kind: \"Blob\",\n objectId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n bindingId: binding.bindingId,\n documentId: input.documentId,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n}\n\nfunction retainedTarget(\n binding: BlobAttachmentSummary,\n target: DocumentContentKeyTarget,\n documentId: string,\n) {\n return binding.contentKeyBundle.targets.find(\n (candidate) =>\n candidate.bindingId === binding.bindingId &&\n candidate.documentId === documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n}\n\nasync function collectRelinkKeks(\n input: Parameters<typeof prepareDocumentLinkBlobRewraps>[0],\n): Promise<Map<string, Uint8Array>> {\n const keks = new Map<string, Uint8Array>();\n for (const projection of [\n ...documentContainerProjections(input.writerProjection),\n input.targetContainerProjection,\n ]) {\n const keys = await unwrapContainerKekPath({\n projection,\n secretKey: input.targetSecretKey,\n execSql: input.execSql,\n ...projectionVerificationOptions(input),\n });\n // Every node of this verified path has a current signed head. Historical\n // keyring entries may open source bytes, but never enter the destination map.\n for (const [index, head] of projection.containerKeks.entries()) {\n const target = deriveDocumentTargetFromProjection({\n ...projection,\n containerId: head.containerId,\n path: projection.path.slice(0, index + 1),\n containerKeks: projection.containerKeks.slice(0, index + 1),\n });\n const key = keys.get(target.containerKeyEpochId);\n // A direct child grantee need not possess any ancestor secret.\n if (!key) continue;\n const id = targetKey(target);\n const previous = keks.get(id);\n if (previous)\n assertEqualBytes(\n previous,\n key,\n \"Attachment link projections contain conflicting KEKs\",\n );\n keks.set(id, key);\n }\n }\n return keks;\n}\n\nfunction compareBlobIds(a: { blobId: string }, b: { blobId: string }): number {\n return a.blobId < b.blobId ? -1 : a.blobId > b.blobId ? 1 : 0;\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { ApiClient } from "../../internal/api-client/index.js";
2
2
  import { type DocumentProjectorRegistryInput } from "../../data/documents/documentKinds.js";
3
+ import type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
3
4
  import { type TrustedUserIdentityResolver } from "../../data/trustedUserIdentity/index.js";
4
5
  import type { WorkflowRuntimeAuthInput, WorkflowRuntimeCryptoInput, WorkflowRuntimeInfraInput, WorkflowRuntimeStateInput, WorkflowRuntimeUtilInput } from "../runtimeInput.js";
5
6
  interface DocumentsWorkflowRuntimeUtilInput extends Omit<WorkflowRuntimeUtilInput, "logError"> {
@@ -27,6 +28,8 @@ export interface DocumentsWorkflowRuntimeInputGroups {
27
28
  readonly util: DocumentsWorkflowRuntimeUtilInput;
28
29
  }
29
30
  export interface DocumentsWorkflowRuntimeInput extends DocumentsWorkflowRuntimeInputGroups {
31
+ /** Private host custody, inherited without exposing it on runtime views. */
32
+ readonly withPrincipalHistoryProtection?: PrincipalHistoryProtectionLease | undefined;
30
33
  readonly apiClient: ApiClient;
31
34
  readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
32
35
  }
@@ -1,4 +1,5 @@
1
1
  import { resolveDocumentProjectorRegistry, } from "../../data/documents/documentKinds.js";
2
+ import { inheritPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
2
3
  import { requireTrustedUserIdentityResolver, } from "../../data/trustedUserIdentity/index.js";
3
4
  export function createDocumentsWorkflowRuntime(input) {
4
5
  const documentProjectors = resolveDocumentProjectorRegistry(input.infra.documentProjectors);
@@ -6,7 +7,7 @@ export function createDocumentsWorkflowRuntime(input) {
6
7
  ...input.infra,
7
8
  documentProjectors,
8
9
  };
9
- return {
10
+ return inheritPrincipalHistoryProtection(input, {
10
11
  apiClient: input.apiClient,
11
12
  auth: input.auth,
12
13
  crypto: input.crypto,
@@ -14,6 +15,6 @@ export function createDocumentsWorkflowRuntime(input) {
14
15
  resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(input.resolveTrustedUserIdentity),
15
16
  state: input.state,
16
17
  util: input.util,
17
- };
18
+ });
18
19
  }
19
20
  //# sourceMappingURL=runtime.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,gCAAgC,GACjC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,kCAAkC,GAEnC,MAAM,gCAAgC,CAAC;AAqDxC,MAAM,UAAU,8BAA8B,CAC5C,KAAoC;IAEpC,MAAM,kBAAkB,GAAG,gCAAgC,CACzD,KAAK,CAAC,KAAK,CAAC,kBAAkB,CAC/B,CAAC;IACF,MAAM,KAAK,GAAG;QACZ,GAAG,KAAK,CAAC,KAAK;QACd,kBAAkB;KACnB,CAAC;IAEF,OAAO;QACL,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,KAAK;QACL,0BAA0B,EAAE,kCAAkC,CAC5D,KAAK,CAAC,0BAA0B,CACjC;QACD,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,IAAI,EAAE,KAAK,CAAC,IAAI;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../data/documents/documentKinds\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../runtimeInput\";\n\ninterface DocumentsWorkflowRuntimeUtilInput\n extends Omit<WorkflowRuntimeUtilInput, \"logError\"> {\n /** Receives handled quarantine errors without converting them to strings. */\n readonly logError?: WorkflowRuntimeUtilInput[\"logError\"] | undefined;\n}\n\nexport interface DocumentsWorkflowRuntimeInfra\n extends Omit<WorkflowRuntimeInfraInput, \"dbStatus\"> {\n readonly dbStatus: string;\n}\n\ninterface DocumentsWorkflowRuntimeInputInfra\n extends Omit<DocumentsWorkflowRuntimeInfra, \"documentProjectors\"> {\n readonly documentProjectors: DocumentProjectorRegistryInput;\n}\n\nexport interface DocumentsWorkflowRuntimeGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: DocumentsWorkflowRuntimeInfra;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: DocumentsWorkflowRuntimeUtilInput;\n}\n\nexport interface DocumentsWorkflowRuntimeInputGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: DocumentsWorkflowRuntimeInputInfra;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: DocumentsWorkflowRuntimeUtilInput;\n}\n\nexport interface DocumentsWorkflowRuntimeInput\n extends DocumentsWorkflowRuntimeInputGroups {\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport interface DocumentsWorkflowRuntime\n extends DocumentsWorkflowRuntimeGroups {\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport function createDocumentsWorkflowRuntime(\n input: DocumentsWorkflowRuntimeInput,\n): DocumentsWorkflowRuntime {\n const documentProjectors = resolveDocumentProjectorRegistry(\n input.infra.documentProjectors,\n );\n const infra = {\n ...input.infra,\n documentProjectors,\n };\n\n return {\n apiClient: input.apiClient,\n auth: input.auth,\n crypto: input.crypto,\n infra,\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n ),\n state: input.state,\n util: input.util,\n };\n}\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,gCAAgC,GACjC,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EACL,kCAAkC,GAEnC,MAAM,gCAAgC,CAAC;AAyDxC,MAAM,UAAU,8BAA8B,CAC5C,KAAoC;IAEpC,MAAM,kBAAkB,GAAG,gCAAgC,CACzD,KAAK,CAAC,KAAK,CAAC,kBAAkB,CAC/B,CAAC;IACF,MAAM,KAAK,GAAG;QACZ,GAAG,KAAK,CAAC,KAAK;QACd,kBAAkB;KACnB,CAAC;IAEF,OAAO,iCAAiC,CAAC,KAAK,EAAE;QAC9C,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,KAAK;QACL,0BAA0B,EAAE,kCAAkC,CAC5D,KAAK,CAAC,0BAA0B,CACjC;QACD,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,IAAI,EAAE,KAAK,CAAC,IAAI;KACjB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../data/documents/documentKinds\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { inheritPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../runtimeInput\";\n\ninterface DocumentsWorkflowRuntimeUtilInput\n extends Omit<WorkflowRuntimeUtilInput, \"logError\"> {\n /** Receives handled quarantine errors without converting them to strings. */\n readonly logError?: WorkflowRuntimeUtilInput[\"logError\"] | undefined;\n}\n\nexport interface DocumentsWorkflowRuntimeInfra\n extends Omit<WorkflowRuntimeInfraInput, \"dbStatus\"> {\n readonly dbStatus: string;\n}\n\ninterface DocumentsWorkflowRuntimeInputInfra\n extends Omit<DocumentsWorkflowRuntimeInfra, \"documentProjectors\"> {\n readonly documentProjectors: DocumentProjectorRegistryInput;\n}\n\nexport interface DocumentsWorkflowRuntimeGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: DocumentsWorkflowRuntimeInfra;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: DocumentsWorkflowRuntimeUtilInput;\n}\n\nexport interface DocumentsWorkflowRuntimeInputGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: DocumentsWorkflowRuntimeInputInfra;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: DocumentsWorkflowRuntimeUtilInput;\n}\n\nexport interface DocumentsWorkflowRuntimeInput\n extends DocumentsWorkflowRuntimeInputGroups {\n /** Private host custody, inherited without exposing it on runtime views. */\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport interface DocumentsWorkflowRuntime\n extends DocumentsWorkflowRuntimeGroups {\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport function createDocumentsWorkflowRuntime(\n input: DocumentsWorkflowRuntimeInput,\n): DocumentsWorkflowRuntime {\n const documentProjectors = resolveDocumentProjectorRegistry(\n input.infra.documentProjectors,\n );\n const infra = {\n ...input.infra,\n documentProjectors,\n };\n\n return inheritPrincipalHistoryProtection(input, {\n apiClient: input.apiClient,\n auth: input.auth,\n crypto: input.crypto,\n infra,\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n ),\n state: input.state,\n util: input.util,\n });\n}\n"]}
@@ -2,6 +2,7 @@ import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
2
  import { DOCUMENT_MUTATION_ERROR_CODES, DOCUMENT_SYNC_ERROR_CODES, } from "../../internal/validators/response/index.js";
3
3
  import { ContainerKekRepairRequiredError } from "../../data/documents/shared/containerKekCurrency.js";
4
4
  import { isRetryableDocumentSyncConflict, isUpstreamDeletedDocumentSyncFailure, } from "../../data/documents/shared/responses.js";
5
+ import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
5
6
  import { isKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
6
7
  /**
7
8
  * Read-only counterpart to describeDocumentSyncSubmitFailure: names a refused
@@ -56,7 +57,8 @@ export function projectionIntegrityErrorCode(error) {
56
57
  export function shouldRetryWithFreshProjection(error, messageMatches) {
57
58
  // A peer may already have repaired the chain. Refetch once; the same guard
58
59
  // rejects a still-stale response before any new ciphertext is produced.
59
- if (error instanceof ContainerKekRepairRequiredError)
60
+ if (error instanceof ContainerKekRepairRequiredError ||
61
+ error instanceof ProjectionDependencyUnavailableError)
60
62
  return true;
61
63
  const integrityErrorCode = projectionIntegrityErrorCode(error);
62
64
  if (integrityErrorCode) {
@@ -1 +1 @@
1
- {"version":3,"file":"syncFailureClassification.js","sourceRoot":"","sources":["syncFailureClassification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,6B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,CAAC,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IACxE,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DOCUMENT_MUTATION_ERROR_CODES,\n DOCUMENT_SYNC_ERROR_CODES,\n} from \"@tearleads/validators/response\";\nimport { ContainerKekRepairRequiredError } from \"../../data/documents/shared/containerKekCurrency\";\nimport {\n isRetryableDocumentSyncConflict,\n isUpstreamDeletedDocumentSyncFailure,\n} from \"../../data/documents/shared/responses\";\nimport type { DocumentSyncSubmitFailure } from \"../../data/documents/shared/types\";\nimport { isKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nexport type RemoteDocumentDeletionHandler = (input: {\n /** Present only after the SDK has verified the signed terminal purge proof. */\n readonly commitPurgeProof?:\n | ((transactionExecSql: ExecSql) => Promise<void>)\n | undefined;\n readonly documentId: string;\n}) => Promise<void> | void;\n\n/**\n * Invoked when a submission fails terminally — the failure is neither a\n * retryable conflict nor a recoverable update-id conflict, so the sync pass\n * stops and the pending writes stay queued (e.g. a 403 after write access was\n * revoked). Callers persist the failure so the write queue can surface it.\n */\nexport type TerminalSubmitFailureHandler = (\n failure: DocumentSyncSubmitFailure,\n) => Promise<void> | void;\n\n/**\n * Read-only counterpart to describeDocumentSyncSubmitFailure: names a refused\n * revalidation without implying a blocked write. 403s never reach this — a\n * read-only 403 is deliberately suppressed (edge-case row 9) so unattempted\n * local edits are never flagged.\n */\nexport function describeDocumentRevalidationFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n const detail =\n failure.message.trim().length > 0\n ? failure.message.trim()\n : \"the server refused the read\";\n const suffix = failure.status === null ? \"\" : ` (${failure.status})`;\n return `Remote revalidation failed: ${detail}${suffix}`;\n}\n\n/** Human-readable description of a terminal submit failure for queue display. */\nexport function describeDocumentSyncSubmitFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n if (failure.status === 403) {\n return \"Write access denied by the server (403)\";\n }\n const message =\n failure.message.trim().length > 0 ? failure.message.trim() : \"Sync failed\";\n return failure.status === null ? message : `${message} (${failure.status})`;\n}\n\ntype ProjectionIntegrityErrorCode =\n | \"equivocation\"\n | \"rollback\"\n | \"stale_predecessor\";\n\nfunction keyingVerificationErrorCode(error: unknown): string | null {\n if (!isKeyingVerificationError(error) || !(error instanceof Error)) {\n return null;\n }\n const code = Reflect.get(error, \"code\");\n return typeof code === \"string\" ? code : null;\n}\n\nexport function projectionIntegrityErrorCode(\n error: unknown,\n): ProjectionIntegrityErrorCode | null {\n if (\n !(error instanceof KeyingVerificationError) &&\n !(error instanceof Error && error.name === \"KeyingVerificationError\")\n ) {\n return null;\n }\n\n const code = keyingVerificationErrorCode(error);\n return code === \"rollback\" ||\n code === \"equivocation\" ||\n code === \"stale_predecessor\"\n ? code\n : null;\n}\n\n/**\n * Shared shell for the stale-projection retry classifiers. A cached\n * projection older than a checkpoint we already recorded (\"rollback\") —\n * typical right after a peer shared/rotated a linked container — is resolved\n * by refetching the current projection. The refetch is safe: it cannot\n * bypass the anti-rollback check, because a genuinely rolled-back server\n * response re-throws on the rebuilt plan. Any other keying-verification\n * failure is terminal; anything else defers to the caller's message\n * predicate for its unwrap-failure shape.\n */\nexport function shouldRetryWithFreshProjection(\n error: unknown,\n messageMatches: (message: string) => boolean,\n): boolean {\n // A peer may already have repaired the chain. Refetch once; the same guard\n // rejects a still-stale response before any new ciphertext is produced.\n if (error instanceof ContainerKekRepairRequiredError) return true;\n const integrityErrorCode = projectionIntegrityErrorCode(error);\n if (integrityErrorCode) {\n return integrityErrorCode === \"rollback\";\n }\n if (keyingVerificationErrorCode(error) === \"invalid_shape\") {\n // Verification boundaries normalize malformed/stale projection data to a\n // terminal error. One cache eviction is still safe: a dishonest or broken\n // fresh response fails again outside this retry boundary.\n return true;\n }\n if (isKeyingVerificationError(error)) {\n return false;\n }\n\n return error instanceof Error && messageMatches(error.message);\n}\n\nexport function shouldRetrySyncWithFreshWriterProjection(\n error: unknown,\n): boolean {\n return shouldRetryWithFreshProjection(\n error,\n (message) =>\n message.startsWith(\n \"Document authorizing container KEK path could not be unwrapped\",\n ) && message.includes(\"Container writer projection KEK\"),\n );\n}\n\nexport function isRecoverableDocumentUpdateIdConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.updateIdConflict\n );\n}\n\n/**\n * The server's covering-baseline gate refused a queued rotation checkpoint\n * (e.g. a leftover from an interrupted recovery or a lost heal ack) because\n * it no longer covers the committed frontier. The pass can repair itself by\n * regenerating a fresh covering baseline from the live document instead of\n * resubmitting the stale payload — which would fail terminally forever.\n */\nexport function isCheckpointCoverageConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.checkpointCoverageConflict\n );\n}\n\n/**\n * A create submitted with a stable documentId whose first attempt already\n * committed server-side comes back as this 409 (see the server's\n * `assertCreateCanAdvanceDocumentHead`). It is not a failure — the caller adopts\n * the existing remote document instead of creating a duplicate.\n */\nexport function isDocumentManifestAlreadyExistsConflict(failure: {\n readonly code?: string | undefined;\n readonly message: string;\n readonly status: number | null;\n}): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_MUTATION_ERROR_CODES.manifestAlreadyExists\n );\n}\n\nexport function canRetryDocumentSyncConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n isRetryableDocumentSyncConflict(input.failure)\n );\n}\n\nexport function canRecoverDocumentUpdateIdConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n pendingUpdateCount: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n input.pendingUpdateCount > 0 &&\n isRecoverableDocumentUpdateIdConflict(input.failure)\n );\n}\n\nexport async function handleUpstreamDeletedDocumentSyncFailure(input: {\n documentId: string;\n failure: DocumentSyncSubmitFailure;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n}): Promise<boolean> {\n if (!isUpstreamDeletedDocumentSyncFailure(input.failure)) {\n return false;\n }\n\n await input.onRemoteDocumentDeleted?.({ documentId: input.documentId });\n return true;\n}\n"]}
1
+ {"version":3,"file":"syncFailureClassification.js","sourceRoot":"","sources":["syncFailureClassification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,+BAA+B,EAAE,MAAM,kDAAkD,CAAC;AACnG,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,GACrC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,yBAAyB,EAAE,MAAM,+CAA+C,CAAC;AAqB1F;;;;;GAKG;AACH,MAAM,UAAU,mCAAmC,CACjD,OAA8D;IAE9D,MAAM,MAAM,GACV,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;QAC/B,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE;QACxB,CAAC,CAAC,6BAA6B,CAAC;IACpC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,MAAM,GAAG,CAAC;IACrE,OAAO,+BAA+B,MAAM,GAAG,MAAM,EAAE,CAAC;AAC1D,CAAC;AA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AAC,OAIvD;IACC,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,GAAG;QACtB,OAAO,CAAC,IAAI,KAAK,6BAA6B,CAAC,qBAAqB,CACrE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,KAI5C;IACC,OAAO,CACL,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,WAAW;QACjC,+BAA+B,CAAC,KAAK,CAAC,OAAO,CAAC,CAC/C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kCAAkC,CAAC,KAKlD;IACC,OAAO,CACL,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,WAAW;QACjC,KAAK,CAAC,kBAAkB,GAAG,CAAC;QAC5B,qCAAqC,CAAC,KAAK,CAAC,OAAO,CAAC,CACrD,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAAC,KAI9D;IACC,IAAI,CAAC,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IACxE,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DOCUMENT_MUTATION_ERROR_CODES,\n DOCUMENT_SYNC_ERROR_CODES,\n} from \"@tearleads/validators/response\";\nimport { ContainerKekRepairRequiredError } from \"../../data/documents/shared/containerKekCurrency\";\nimport {\n isRetryableDocumentSyncConflict,\n isUpstreamDeletedDocumentSyncFailure,\n} from \"../../data/documents/shared/responses\";\nimport type { DocumentSyncSubmitFailure } from \"../../data/documents/shared/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { isKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nexport type RemoteDocumentDeletionHandler = (input: {\n /** Present only after the SDK has verified the signed terminal purge proof. */\n readonly commitPurgeProof?:\n | ((transactionExecSql: ExecSql) => Promise<void>)\n | undefined;\n readonly documentId: string;\n}) => Promise<void> | void;\n\n/**\n * Invoked when a submission fails terminally — the failure is neither a\n * retryable conflict nor a recoverable update-id conflict, so the sync pass\n * stops and the pending writes stay queued (e.g. a 403 after write access was\n * revoked). Callers persist the failure so the write queue can surface it.\n */\nexport type TerminalSubmitFailureHandler = (\n failure: DocumentSyncSubmitFailure,\n) => Promise<void> | void;\n\n/**\n * Read-only counterpart to describeDocumentSyncSubmitFailure: names a refused\n * revalidation without implying a blocked write. 403s never reach this — a\n * read-only 403 is deliberately suppressed (edge-case row 9) so unattempted\n * local edits are never flagged.\n */\nexport function describeDocumentRevalidationFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n const detail =\n failure.message.trim().length > 0\n ? failure.message.trim()\n : \"the server refused the read\";\n const suffix = failure.status === null ? \"\" : ` (${failure.status})`;\n return `Remote revalidation failed: ${detail}${suffix}`;\n}\n\n/** Human-readable description of a terminal submit failure for queue display. */\nexport function describeDocumentSyncSubmitFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n if (failure.status === 403) {\n return \"Write access denied by the server (403)\";\n }\n const message =\n failure.message.trim().length > 0 ? failure.message.trim() : \"Sync failed\";\n return failure.status === null ? message : `${message} (${failure.status})`;\n}\n\ntype ProjectionIntegrityErrorCode =\n | \"equivocation\"\n | \"rollback\"\n | \"stale_predecessor\";\n\nfunction keyingVerificationErrorCode(error: unknown): string | null {\n if (!isKeyingVerificationError(error) || !(error instanceof Error)) {\n return null;\n }\n const code = Reflect.get(error, \"code\");\n return typeof code === \"string\" ? code : null;\n}\n\nexport function projectionIntegrityErrorCode(\n error: unknown,\n): ProjectionIntegrityErrorCode | null {\n if (\n !(error instanceof KeyingVerificationError) &&\n !(error instanceof Error && error.name === \"KeyingVerificationError\")\n ) {\n return null;\n }\n\n const code = keyingVerificationErrorCode(error);\n return code === \"rollback\" ||\n code === \"equivocation\" ||\n code === \"stale_predecessor\"\n ? code\n : null;\n}\n\n/**\n * Shared shell for the stale-projection retry classifiers. A cached\n * projection older than a checkpoint we already recorded (\"rollback\") —\n * typical right after a peer shared/rotated a linked container — is resolved\n * by refetching the current projection. The refetch is safe: it cannot\n * bypass the anti-rollback check, because a genuinely rolled-back server\n * response re-throws on the rebuilt plan. Any other keying-verification\n * failure is terminal; anything else defers to the caller's message\n * predicate for its unwrap-failure shape.\n */\nexport function shouldRetryWithFreshProjection(\n error: unknown,\n messageMatches: (message: string) => boolean,\n): boolean {\n // A peer may already have repaired the chain. Refetch once; the same guard\n // rejects a still-stale response before any new ciphertext is produced.\n if (\n error instanceof ContainerKekRepairRequiredError ||\n error instanceof ProjectionDependencyUnavailableError\n )\n return true;\n const integrityErrorCode = projectionIntegrityErrorCode(error);\n if (integrityErrorCode) {\n return integrityErrorCode === \"rollback\";\n }\n if (keyingVerificationErrorCode(error) === \"invalid_shape\") {\n // Verification boundaries normalize malformed/stale projection data to a\n // terminal error. One cache eviction is still safe: a dishonest or broken\n // fresh response fails again outside this retry boundary.\n return true;\n }\n if (isKeyingVerificationError(error)) {\n return false;\n }\n\n return error instanceof Error && messageMatches(error.message);\n}\n\nexport function shouldRetrySyncWithFreshWriterProjection(\n error: unknown,\n): boolean {\n return shouldRetryWithFreshProjection(\n error,\n (message) =>\n message.startsWith(\n \"Document authorizing container KEK path could not be unwrapped\",\n ) && message.includes(\"Container writer projection KEK\"),\n );\n}\n\nexport function isRecoverableDocumentUpdateIdConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.updateIdConflict\n );\n}\n\n/**\n * The server's covering-baseline gate refused a queued rotation checkpoint\n * (e.g. a leftover from an interrupted recovery or a lost heal ack) because\n * it no longer covers the committed frontier. The pass can repair itself by\n * regenerating a fresh covering baseline from the live document instead of\n * resubmitting the stale payload — which would fail terminally forever.\n */\nexport function isCheckpointCoverageConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.checkpointCoverageConflict\n );\n}\n\n/**\n * A create submitted with a stable documentId whose first attempt already\n * committed server-side comes back as this 409 (see the server's\n * `assertCreateCanAdvanceDocumentHead`). It is not a failure — the caller adopts\n * the existing remote document instead of creating a duplicate.\n */\nexport function isDocumentManifestAlreadyExistsConflict(failure: {\n readonly code?: string | undefined;\n readonly message: string;\n readonly status: number | null;\n}): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_MUTATION_ERROR_CODES.manifestAlreadyExists\n );\n}\n\nexport function canRetryDocumentSyncConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n isRetryableDocumentSyncConflict(input.failure)\n );\n}\n\nexport function canRecoverDocumentUpdateIdConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n pendingUpdateCount: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n input.pendingUpdateCount > 0 &&\n isRecoverableDocumentUpdateIdConflict(input.failure)\n );\n}\n\nexport async function handleUpstreamDeletedDocumentSyncFailure(input: {\n documentId: string;\n failure: DocumentSyncSubmitFailure;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n}): Promise<boolean> {\n if (!isUpstreamDeletedDocumentSyncFailure(input.failure)) {\n return false;\n }\n\n await input.onRemoteDocumentDeleted?.({ documentId: input.documentId });\n return true;\n}\n"]}
@@ -1,4 +1,6 @@
1
+ export type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
1
2
  export { type CachePrincipalPolicyBundlesOptions, type CacheReferencedPrincipalPoliciesOptions, cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
2
3
  export { PrincipalPolicyHistoryReadError, type RecoveredPrincipalPolicyHistory, type RecoverPrincipalPolicyHistoryOptions, } from "./principalHistoryRecoveryTypes.js";
3
4
  export { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
5
+ export { type ProjectionPolicyHistoryRecoveryOptions, recoverProjectionPolicyHistory, } from "./recoverProjectionPolicyHistory.js";
4
6
  export { type RecoveredScopedPrincipalPolicyHistory, type RecoverScopedPrincipalPolicyHistoryOptions, recoverScopedPrincipalPolicyHistory, } from "./recoverScopedPrincipalPolicyHistory.js";
@@ -1,5 +1,6 @@
1
1
  export { cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
2
2
  export { PrincipalPolicyHistoryReadError, } from "./principalHistoryRecoveryTypes.js";
3
3
  export { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
4
+ export { recoverProjectionPolicyHistory, } from "./recoverProjectionPolicyHistory.js";
4
5
  export { recoverScopedPrincipalPolicyHistory, } from "./recoverScopedPrincipalPolicyHistory.js";
5
6
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAGL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC","sourcesContent":["export {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\nexport {\n type RecoveredScopedPrincipalPolicyHistory,\n type RecoverScopedPrincipalPolicyHistoryOptions,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAEL,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAGL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC","sourcesContent":["export type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nexport {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\nexport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./recoverProjectionPolicyHistory\";\nexport {\n type RecoveredScopedPrincipalPolicyHistory,\n type RecoverScopedPrincipalPolicyHistoryOptions,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"policyVerification.js","sourceRoot":"","sources":["policyVerification.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,kCAAkC,GAEnC,MAAM,gCAAgC,CAAC;A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AAkB,EAAE,KAAK,CAAC,wBAAwB;SACnD,CAAC,CAAC;QACH,IAAI,qBAAqB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YACxC,SAAS;QACX,CAAC;QAED,MAAM,qBAAqB,GAAG,MAAM,0BAA0B,CAAC;YAC7D,0BAA0B;YAC1B,KAAK;SACN,CAAC,CAAC;QACH,IAAI,OAAO,IAAI,qBAAqB,EAAE,CAAC;YACrC,OAAO,EAAE,KAAK,EAAE,qBAAqB,CAAC,KAAK,EAAE,CAAC;QAChD,CAAC;QAED,qBAAqB,CAAC,GAAG,CAAC,QAAQ,EAAE,qBAAqB,CAAC,eAAe,CAAC,CAAC;IAC7E,CAAC;IAED,OAAO;QACL,gBAAgB,EAAE,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,MAAM,EAAE,CAAC;KAC7D,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicySignerPublicKey } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\n\nexport type PrincipalPolicySignerPublicKeyLoadErrorCode =\n | \"fingerprint-mismatch\"\n | \"not-found\";\n\nexport function principalPolicyStates(\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyBundleResponse[\"currentState\"][] {\n return [\n ...bundle.previousStates.map((entry) => entry.state),\n bundle.currentState,\n ];\n}\n\nfunction signerCacheKey(input: {\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n}): string {\n return `${input.signerUserId}:${input.signingFingerprint}`;\n}\n\nasync function loadTrustedSignerPublicKey(input: {\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly state: PrincipalPolicyBundleResponse[\"currentState\"];\n}): Promise<\n | { readonly signerPublicKey: PrincipalPolicySignerPublicKey }\n | { readonly error: PrincipalPolicySignerPublicKeyLoadErrorCode }\n> {\n const signerKey = await input.resolveTrustedUserIdentity(\n input.state.signerUserId,\n );\n\n if (!signerKey) {\n return { error: \"not-found\" };\n }\n\n if (\n signerKey.signingKeyFingerprint !== input.state.signerUserKeyFingerprint\n ) {\n return { error: \"fingerprint-mismatch\" };\n }\n\n return {\n signerPublicKey: {\n userId: input.state.signerUserId,\n signingKeyFingerprint: input.state.signerUserKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n },\n };\n}\n\nexport async function collectPrincipalPolicySignerPublicKeys(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}): Promise<\n | { readonly signerPublicKeys: PrincipalPolicySignerPublicKey[] }\n | { readonly error: PrincipalPolicySignerPublicKeyLoadErrorCode }\n> {\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n const signerPublicKeysByKey = new Map<\n string,\n PrincipalPolicySignerPublicKey\n >();\n\n for (const state of principalPolicyStates(input.bundle)) {\n const cacheKey = signerCacheKey({\n signerUserId: state.signerUserId,\n signingFingerprint: state.signerUserKeyFingerprint,\n });\n if (signerPublicKeysByKey.has(cacheKey)) {\n continue;\n }\n\n const remoteSignerPublicKey = await loadTrustedSignerPublicKey({\n resolveTrustedUserIdentity,\n state,\n });\n if (\"error\" in remoteSignerPublicKey) {\n return { error: remoteSignerPublicKey.error };\n }\n\n signerPublicKeysByKey.set(cacheKey, remoteSignerPublicKey.signerPublicKey);\n }\n\n return {\n signerPublicKeys: Array.from(signerPublicKeysByKey.values()),\n };\n}\n"]}
1
+ {"version":3,"file":"policyVerification.js","sourceRoot":"","sources":["policyVerification.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,kCAAkC,GAEnC,MAAM,gCAAgC,CAAC;AAMxC,MAAM,UAAU,qBAAqB,CACnC,MAGC;IAED,OAAO;QACL,GAAG,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KA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AAC;QAED,MAAM,qBAAqB,GAAG,MAAM,0BAA0B,CAAC;YAC7D,0BAA0B;YAC1B,KAAK;SACN,CAAC,CAAC;QACH,IAAI,OAAO,IAAI,qBAAqB,EAAE,CAAC;YACrC,OAAO,EAAE,KAAK,EAAE,qBAAqB,CAAC,KAAK,EAAE,CAAC;QAChD,CAAC;QAED,qBAAqB,CAAC,GAAG,CAAC,QAAQ,EAAE,qBAAqB,CAAC,eAAe,CAAC,CAAC;IAC7E,CAAC;IAED,OAAO;QACL,gBAAgB,EAAE,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,MAAM,EAAE,CAAC;KAC7D,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicySignerPublicKey } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\n\nexport type PrincipalPolicySignerPublicKeyLoadErrorCode =\n | \"fingerprint-mismatch\"\n | \"not-found\";\n\nexport function principalPolicyStates(\n bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\"\n >,\n): PrincipalPolicyBundleResponse[\"currentState\"][] {\n return [\n ...bundle.previousStates.map((entry) => entry.state),\n bundle.currentState,\n ];\n}\n\nfunction signerCacheKey(input: {\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n}): string {\n return `${input.signerUserId}:${input.signingFingerprint}`;\n}\n\nasync function loadTrustedSignerPublicKey(input: {\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly state: PrincipalPolicyBundleResponse[\"currentState\"];\n}): Promise<\n | { readonly signerPublicKey: PrincipalPolicySignerPublicKey }\n | { readonly error: PrincipalPolicySignerPublicKeyLoadErrorCode }\n> {\n const signerKey = await input.resolveTrustedUserIdentity(\n input.state.signerUserId,\n );\n\n if (!signerKey) {\n return { error: \"not-found\" };\n }\n\n if (\n signerKey.signingKeyFingerprint !== input.state.signerUserKeyFingerprint\n ) {\n return { error: \"fingerprint-mismatch\" };\n }\n\n return {\n signerPublicKey: {\n userId: input.state.signerUserId,\n signingKeyFingerprint: input.state.signerUserKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n },\n };\n}\n\nexport async function collectPrincipalPolicySignerPublicKeys(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}): Promise<\n | { readonly signerPublicKeys: PrincipalPolicySignerPublicKey[] }\n | { readonly error: PrincipalPolicySignerPublicKeyLoadErrorCode }\n> {\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n const signerPublicKeysByKey = new Map<\n string,\n PrincipalPolicySignerPublicKey\n >();\n\n for (const state of principalPolicyStates(input.bundle)) {\n const cacheKey = signerCacheKey({\n signerUserId: state.signerUserId,\n signingFingerprint: state.signerUserKeyFingerprint,\n });\n if (signerPublicKeysByKey.has(cacheKey)) {\n continue;\n }\n\n const remoteSignerPublicKey = await loadTrustedSignerPublicKey({\n resolveTrustedUserIdentity,\n state,\n });\n if (\"error\" in remoteSignerPublicKey) {\n return { error: remoteSignerPublicKey.error };\n }\n\n signerPublicKeysByKey.set(cacheKey, remoteSignerPublicKey.signerPublicKey);\n }\n\n return {\n signerPublicKeys: Array.from(signerPublicKeysByKey.values()),\n };\n}\n"]}
@@ -0,0 +1,20 @@
1
+ import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
+ import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
3
+ import { PrincipalHistoryEvidenceUnavailableError } from "./principalHistoryRecoveryReferences.js";
4
+ /** Reusable signatures remain conditional on their authenticated authority lineage. */
5
+ export async function validatePrincipalHistoryRecoveryAuthority(input, verifier) {
6
+ const reference = verifier.getExternalAuthorityReference();
7
+ if (!reference)
8
+ return;
9
+ try {
10
+ const authority = await input.loadExternalAuthority?.([reference]);
11
+ if (!authority?.states.some(({ head }) => principalHeadMatchesReference(head, reference)))
12
+ throw new KeyingVerificationError("stale_predecessor", "Cached principal history has a different authority lineage");
13
+ }
14
+ catch (error) {
15
+ if (error instanceof KeyingVerificationError)
16
+ throw new PrincipalHistoryEvidenceUnavailableError(error);
17
+ throw error;
18
+ }
19
+ }
20
+ //# sourceMappingURL=principalHistoryRecoveryAuthority.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalHistoryRecoveryAuthority.js","sourceRoot":"","sources":["principalHistoryRecoveryAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,wCAAwC,EAAE,MAAM,sCAAsC,CAAC;AAGhG,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,yCAAyC,CAC7D,KAA2C,EAC3C,QAAwC;IAExC,MAAM,SAAS,GAAG,QAAQ,CAAC,6BAA6B,EAAE,CAAC;IAC3D,IAAI,CAAC,SAAS;QAAE,OAAO;IACvB,IAAI,CAAC;QACH,MAAM,SAAS,GAAG,MAAM,KAAK,CAAC,qBAAqB,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;QACnE,IACE,CAAC,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CACnC,6BAA6B,CAAC,IAAI,EAAE,SAAS,CAAC,CAC/C;YAED,MAAM,IAAI,uBAAuB,CAC/B,mBAAmB,EACnB,4DAA4D,CAC7D,CAAC;IACN,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB;YAC1C,MAAM,IAAI,wCAAwC,CAAC,KAAK,CAAC,CAAC;QAC5D,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyHistoryVerifier,\n} from \"@tearleads/crypto\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { PrincipalHistoryEvidenceUnavailableError } from \"./principalHistoryRecoveryReferences\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\n/** Reusable signatures remain conditional on their authenticated authority lineage. */\nexport async function validatePrincipalHistoryRecoveryAuthority(\n input: RecoverPrincipalPolicyHistoryOptions,\n verifier: PrincipalPolicyHistoryVerifier,\n): Promise<void> {\n const reference = verifier.getExternalAuthorityReference();\n if (!reference) return;\n try {\n const authority = await input.loadExternalAuthority?.([reference]);\n if (\n !authority?.states.some(({ head }) =>\n principalHeadMatchesReference(head, reference),\n )\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Cached principal history has a different authority lineage\",\n );\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n }\n}\n"]}
@@ -9,7 +9,7 @@ export async function restorePrincipalHistoryRecoveryStage(input, historyInput,
9
9
  head: input.expectedHead,
10
10
  protection: input.protection,
11
11
  });
12
- const id = await principalHistoryStageId(input.organizationId, input.expectedHead, input.protection.context, input.retainedReferences ?? []);
12
+ const id = await principalHistoryStageId(input.organizationId, input.expectedHead, input.protection.context);
13
13
  const saved = await loadPrincipalHistoryStage(input.execSql, id);
14
14
  if (saved) {
15
15
  const current = parsePrincipalHistoryStageCurrent(saved);
@@ -1 +1 @@
1
- {"version":3,"file":"principalHistoryRecoveryStage.js","sourceRoot":"","sources":["principalHistoryRecoveryStage.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EAGpC,qCAAqC,GACtC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAE1B,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,+BAA+B,EAAE,MAAM,wDAAwD,CAAC;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AChB,CAAC;QACN,CAAC;QACD,0EAA0E;QAC1E,0EAA0E;QAC1E,MAAM,4BAA4B,CAChC,KAAK,CAAC,OAAO,EACb,KAAK,EACL,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,KAAK,CAAC,YAAY,EAAE,CACrD,CAAC;IACJ,CAAC;IACD,MAAM,MAAM,GAAG,iBAAiB;QAC9B,CAAC,CAAC,MAAM,qCAAqC,CAAC,KAAK,EAAE,YAAY,EAAE,OAAO,CAAC;QAC3E,CAAC,CAAC,IAAI,CAAC;IACT,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC;QAC/D,OAAO;YACL,EAAE;YACF,OAAO;YACP,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI;YACzC,KAAK,EAAE,IAAI;YACX,QAAQ;YACR,mBAAmB,EAAE,MAAM,CAAC,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACxD,SAAS,EAAE,IAAI;SAChB,CAAC;IACJ,CAAC;IACD,OAAO;QACL,EAAE;QACF,OAAO;QACP,QAAQ,EAAE,oCAAoC,CAAC,YAAY,CAAC;QAC5D,OAAO,EAAE,IAAI;QACb,KAAK,EAAE,IAAI;QACX,QAAQ,EAAE,KAAK;QACf,mBAAmB,EAAE,CAAC;QACtB,SAAS,EAAE,KAAK;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n type PrincipalPolicyHistoryInput,\n type PrincipalPolicyHistoryVerifier,\n restorePrincipalPolicyHistoryVerifier,\n} from \"@tearleads/crypto\";\nimport {\n discardPrincipalHistoryStage,\n loadPrincipalHistoryStage,\n type PrincipalHistoryStage,\n} from \"../../data/persistence/principalHistoryStagePersistence\";\nimport { principalHistoryEvidenceScopeId } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport {\n parsePrincipalHistoryStageCurrent,\n principalHistoryStageId,\n principalHistoryStageProtection,\n} from \"../../data/principals/principalHistoryStageProtection\";\nimport { restoreReusablePrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport interface PrincipalHistoryRecoveryStage {\n readonly id: string;\n readonly scopeId: string;\n readonly verifier: PrincipalPolicyHistoryVerifier;\n readonly initialAfterVersion: number;\n readonly fromCache: boolean;\n complete: boolean;\n current: PrincipalPolicyPageCurrent | null;\n saved: PrincipalHistoryStage | null;\n}\n\nexport async function restorePrincipalHistoryRecoveryStage(\n input: RecoverPrincipalPolicyHistoryOptions,\n historyInput: PrincipalPolicyHistoryInput,\n useReusablePrefix = true,\n): Promise<PrincipalHistoryRecoveryStage> {\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: input.expectedHead,\n protection: input.protection,\n });\n const id = await principalHistoryStageId(\n input.organizationId,\n input.expectedHead,\n input.protection.context,\n input.retainedReferences ?? [],\n );\n const saved = await loadPrincipalHistoryStage(input.execSql, id);\n if (saved) {\n const current = parsePrincipalHistoryStageCurrent(saved);\n if (current && saved.organizationId === input.organizationId) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n saved.progress,\n await principalHistoryStageProtection(\n input.protection,\n input.expectedHead,\n saved,\n ),\n );\n if (restored.ok)\n return {\n id,\n scopeId,\n verifier: restored.value,\n current,\n saved,\n complete: saved.complete,\n initialAfterVersion: saved.afterVersion,\n fromCache: true,\n };\n }\n // Saved bytes are a disposable hint. Only a locally authenticated restore\n // can skip signed history; missing keys or changed inputs replay genesis.\n await discardPrincipalHistoryStage(\n input.execSql,\n saved,\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n }\n const prefix = useReusablePrefix\n ? await restoreReusablePrincipalHistoryPrefix(input, historyInput, scopeId)\n : null;\n if (prefix) {\n const complete = prefix.version === input.expectedHead.version;\n return {\n id,\n scopeId,\n verifier: prefix.verifier,\n current: complete ? prefix.current : null,\n saved: null,\n complete,\n initialAfterVersion: prefix.version - (complete ? 1 : 0),\n fromCache: true,\n };\n }\n return {\n id,\n scopeId,\n verifier: createPrincipalPolicyHistoryVerifier(historyInput),\n current: null,\n saved: null,\n complete: false,\n initialAfterVersion: 0,\n fromCache: false,\n };\n}\n"]}
1
+ {"version":3,"file":"principalHistoryRecoveryStage.js","sourceRoot":"","sources":["principalHistoryRecoveryStage.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EAGpC,qCAAqC,GACtC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAE1B,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,+BAA+B,EAAE,MAAM,wDAAwD,CAAC;AACzG,OAAO,EACL,iCAAiC,EACjC,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AAczF,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,KAA2C,EAC3C,YAAyC,EACzC,iBAAiB,GAAG,IAAI;IAExB,MAAM,OAAO,GAAG,MAAM,+BAA+B,CAAC;QACpD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,IAAI,EAAE,KAAK,CAAC,YAAY;QACxB,UAAU,EAAE,KAAK,CAAC,UAAU;KAC7B,CAAC,CAAC;IACH,MAAM,EAAE,GAAG,MAAM,uBAAuB,CACtC,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,YAAY,EAClB,KAAK,CAAC,UAAU,CAAC,OAAO,CACzB,CAAC;IACF,MAAM,KAAK,GAAG,MAAM,yBA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CAAC,CAAC,CAAC,IAAI;YACzC,KAAK,EAAE,IAAI;YACX,QAAQ;YACR,mBAAmB,EAAE,MAAM,CAAC,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACxD,SAAS,EAAE,IAAI;SAChB,CAAC;IACJ,CAAC;IACD,OAAO;QACL,EAAE;QACF,OAAO;QACP,QAAQ,EAAE,oCAAoC,CAAC,YAAY,CAAC;QAC5D,OAAO,EAAE,IAAI;QACb,KAAK,EAAE,IAAI;QACX,QAAQ,EAAE,KAAK;QACf,mBAAmB,EAAE,CAAC;QACtB,SAAS,EAAE,KAAK;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n type PrincipalPolicyHistoryInput,\n type PrincipalPolicyHistoryVerifier,\n restorePrincipalPolicyHistoryVerifier,\n} from \"@tearleads/crypto\";\nimport {\n discardPrincipalHistoryStage,\n loadPrincipalHistoryStage,\n type PrincipalHistoryStage,\n} from \"../../data/persistence/principalHistoryStagePersistence\";\nimport { principalHistoryEvidenceScopeId } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport {\n parsePrincipalHistoryStageCurrent,\n principalHistoryStageId,\n principalHistoryStageProtection,\n} from \"../../data/principals/principalHistoryStageProtection\";\nimport { restoreReusablePrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport interface PrincipalHistoryRecoveryStage {\n readonly id: string;\n readonly scopeId: string;\n readonly verifier: PrincipalPolicyHistoryVerifier;\n readonly initialAfterVersion: number;\n readonly fromCache: boolean;\n complete: boolean;\n current: PrincipalPolicyPageCurrent | null;\n saved: PrincipalHistoryStage | null;\n}\n\nexport async function restorePrincipalHistoryRecoveryStage(\n input: RecoverPrincipalPolicyHistoryOptions,\n historyInput: PrincipalPolicyHistoryInput,\n useReusablePrefix = true,\n): Promise<PrincipalHistoryRecoveryStage> {\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: input.expectedHead,\n protection: input.protection,\n });\n const id = await principalHistoryStageId(\n input.organizationId,\n input.expectedHead,\n input.protection.context,\n );\n const saved = await loadPrincipalHistoryStage(input.execSql, id);\n if (saved) {\n const current = parsePrincipalHistoryStageCurrent(saved);\n if (current && saved.organizationId === input.organizationId) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n saved.progress,\n await principalHistoryStageProtection(\n input.protection,\n input.expectedHead,\n saved,\n ),\n );\n if (restored.ok)\n return {\n id,\n scopeId,\n verifier: restored.value,\n current,\n saved,\n complete: saved.complete,\n initialAfterVersion: saved.afterVersion,\n fromCache: true,\n };\n }\n // Saved bytes are a disposable hint. Only a locally authenticated restore\n // can skip signed history; missing keys or changed inputs replay genesis.\n await discardPrincipalHistoryStage(\n input.execSql,\n saved,\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n }\n const prefix = useReusablePrefix\n ? await restoreReusablePrincipalHistoryPrefix(input, historyInput, scopeId)\n : null;\n if (prefix) {\n const complete = prefix.version === input.expectedHead.version;\n return {\n id,\n scopeId,\n verifier: prefix.verifier,\n current: complete ? prefix.current : null,\n saved: null,\n complete,\n initialAfterVersion: prefix.version - (complete ? 1 : 0),\n fromCache: true,\n };\n }\n return {\n id,\n scopeId,\n verifier: createPrincipalPolicyHistoryVerifier(historyInput),\n current: null,\n saved: null,\n complete: false,\n initialAfterVersion: 0,\n fromCache: false,\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { ApiClient, PrincipalPolicyPageCurrent, RequestFailure } from "../../internal/api-client/index.js";
2
- import { KeyingVerificationError, type PrincipalPolicyExternalAuthority, type PrincipalPolicyHistoryProgressOptions, type PrincipalPolicyStateChainEntry, type ReferencedPrincipalHead, type VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
2
+ import { KeyingVerificationError, type PrincipalPolicyExternalAuthority, type PrincipalPolicyHistoryProgressOptions, type ReferencedPrincipalHead, type VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
3
3
  import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
4
4
  import type { TrustedUserIdentityResolver } from "../../data/trustedUserIdentity/index.js";
5
5
  /** A locally observed race, distinct from a rejected signed predecessor. */
@@ -19,8 +19,8 @@ export interface RecoverPrincipalPolicyHistoryOptions {
19
19
  /** Strict Admins mode checks every historical projection in a separate cache scope. */
20
20
  readonly historyVerification?: "standard" | "direct-admins" | undefined;
21
21
  readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
22
- /** Return only authority already authenticated by this client. */
23
- readonly loadExternalAuthority?: ((entries: readonly PrincipalPolicyStateChainEntry[]) => Promise<PrincipalPolicyExternalAuthority | undefined>) | undefined;
22
+ /** Authenticate these exact authority references, including cached-prefix citations. */
23
+ readonly loadExternalAuthority?: ((references: readonly ReferencedPrincipalHead[]) => Promise<PrincipalPolicyExternalAuthority | undefined>) | undefined;
24
24
  readonly stillCurrent: () => boolean;
25
25
  readonly signal?: AbortSignal | undefined;
26
26
  }
@@ -1 +1 @@
1
- {"version":3,"file":"principalHistoryRecoveryTypes.js","sourceRoot":"","sources":["principalHistoryRecoveryTypes.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uBAAuB,GAMxB,MAAM,mBAAmB,CAAC;AAI3B,4EAA4E;AAC5E,MAAM,OAAO,iCAAkC,SAAQ,uBAAuB;IAC5E,YAAY,OAAe;QACzB,KAAK,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC;CACF;AA8BD,MAAM,OAAO,+BAAgC,SAAQ,KAAK;IACnC;IAArB,YAAqB,OAAuB;QAC1C,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QADJ,YAAO,GAAP,OAAO,CAAgB;QAE1C,IAAI,CAAC,IAAI,GAAG,iCAAiC,CAAC;IAChD,CAAC;CACF","sourcesContent":["import type {\n ApiClient,\n PrincipalPolicyPageCurrent,\n RequestFailure,\n} from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type PrincipalPolicyHistoryProgressOptions,\n type PrincipalPolicyStateChainEntry,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\n\n/** A locally observed race, distinct from a rejected signed predecessor. */\nexport class PrincipalHistoryRecoveryRaceError extends KeyingVerificationError {\n constructor(message: string) {\n super(\"stale_predecessor\", message);\n }\n}\n\nexport interface RecoverPrincipalPolicyHistoryOptions {\n readonly apiClient: Pick<ApiClient, \"getPrincipalPolicyPages\">;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly expectedHead: ReferencedPrincipalHead;\n /** Only use locally authenticated completed evidence; never perform HTTP. */\n readonly offline?: boolean | undefined;\n /** Device-controlled key and stable identity/trust-policy context, never supplied by the API. */\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly retainedReferences?: readonly ReferencedPrincipalHead[] | undefined;\n /** Strict Admins mode checks every historical projection in a separate cache scope. */\n readonly historyVerification?: \"standard\" | \"direct-admins\" | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** Return only authority already authenticated by this client. */\n readonly loadExternalAuthority?:\n | ((\n entries: readonly PrincipalPolicyStateChainEntry[],\n ) => Promise<PrincipalPolicyExternalAuthority | undefined>)\n | undefined;\n readonly stillCurrent: () => boolean;\n readonly signal?: AbortSignal | undefined;\n}\n\nexport interface RecoveredPrincipalPolicyHistory {\n readonly current: PrincipalPolicyPageCurrent;\n readonly policy: VerifiedPrincipalPolicyCurrent;\n}\n\nexport class PrincipalPolicyHistoryReadError extends Error {\n constructor(readonly failure: RequestFailure) {\n super(failure.message);\n this.name = \"PrincipalPolicyHistoryReadError\";\n }\n}\n"]}
1
+ {"version":3,"file":"principalHistoryRecoveryTypes.js","sourceRoot":"","sources":["principalHistoryRecoveryTypes.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uBAAuB,GAKxB,MAAM,mBAAmB,CAAC;AAI3B,4EAA4E;AAC5E,MAAM,OAAO,iCAAkC,SAAQ,uBAAuB;IAC5E,YAAY,OAAe;QACzB,KAAK,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC;CACF;AA8BD,MAAM,OAAO,+BAAgC,SAAQ,KAAK;IACnC;IAArB,YAAqB,OAAuB;QAC1C,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QADJ,YAAO,GAAP,OAAO,CAAgB;QAE1C,IAAI,CAAC,IAAI,GAAG,iCAAiC,CAAC;IAChD,CAAC;CACF","sourcesContent":["import type {\n ApiClient,\n PrincipalPolicyPageCurrent,\n RequestFailure,\n} from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type PrincipalPolicyHistoryProgressOptions,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\n\n/** A locally observed race, distinct from a rejected signed predecessor. */\nexport class PrincipalHistoryRecoveryRaceError extends KeyingVerificationError {\n constructor(message: string) {\n super(\"stale_predecessor\", message);\n }\n}\n\nexport interface RecoverPrincipalPolicyHistoryOptions {\n readonly apiClient: Pick<ApiClient, \"getPrincipalPolicyPages\">;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly expectedHead: ReferencedPrincipalHead;\n /** Only use locally authenticated completed evidence; never perform HTTP. */\n readonly offline?: boolean | undefined;\n /** Device-controlled key and stable identity/trust-policy context, never supplied by the API. */\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly retainedReferences?: readonly ReferencedPrincipalHead[] | undefined;\n /** Strict Admins mode checks every historical projection in a separate cache scope. */\n readonly historyVerification?: \"standard\" | \"direct-admins\" | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** Authenticate these exact authority references, including cached-prefix citations. */\n readonly loadExternalAuthority?:\n | ((\n references: readonly ReferencedPrincipalHead[],\n ) => Promise<PrincipalPolicyExternalAuthority | undefined>)\n | undefined;\n readonly stillCurrent: () => boolean;\n readonly signal?: AbortSignal | undefined;\n}\n\nexport interface RecoveredPrincipalPolicyHistory {\n readonly current: PrincipalPolicyPageCurrent;\n readonly policy: VerifiedPrincipalPolicyCurrent;\n}\n\nexport class PrincipalPolicyHistoryReadError extends Error {\n constructor(readonly failure: RequestFailure) {\n super(failure.message);\n this.name = \"PrincipalPolicyHistoryReadError\";\n }\n}\n"]}
@@ -4,7 +4,12 @@ export function principalHistoryVerificationContext(input) {
4
4
  if (mode !== "standard" && mode !== "direct-admins")
5
5
  throw new KeyingVerificationError("invalid_shape", "Unknown principal history verification mode");
6
6
  if (mode === "standard")
7
- return input.protection.context;
7
+ return input.loadExternalAuthority
8
+ ? serializeKeyingCanonicalJson([
9
+ "tearleads.sdk.principal-history.external-authority.v1",
10
+ input.protection.context,
11
+ ])
12
+ : input.protection.context;
8
13
  if (input.expectedHead.principalType !== "group" ||
9
14
  input.loadExternalAuthority)
10
15
  throw new KeyingVerificationError("invalid_shape", "Strict Admins history requires a group without external authority fallback");
@@ -1 +1 @@
1
- {"version":3,"file":"principalHistoryRecoveryVerification.js","sourceRoot":"","sources":["principalHistoryRecoveryVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAG3B,MAAM,UAAU,mCAAmC,CACjD,KAA2C;IAE3C,MAAM,IAAI,GAAG,KAAK,CAAC,mBAAmB,IAAI,UAAU,CAAC;IACrD,IAAI,IAAI,KAAK,UAAU,IAAI,IAAI,KAAK,eAAe;QACjD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,6CAA6C,CAC9C,CAAC;IACJ,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC;IACzD,IACE,KAAK,CAAC,YAAY,CAAC,aAAa,KAAK,OAAO;QAC5C,KAAK,CAAC,qBAAqB;QAE3B,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,4EAA4E,CAC7E,CAAC;IACJ,2EAA2E;IAC3E,OAAO,4BAA4B,CAAC;QAClC,kDAAkD;QAClD,KAAK,CAAC,UAAU,CAAC,OAAO;KACzB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,KAA2C,EAC3C,OAAkD;IAElD,IAAI,KAAK,CAAC,mBAAmB,KAAK,eAAe;QAAE,OAAO;IAC1D,IACE,OAAO,CAAC,IAAI,CACV,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC;QAC7B,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,OAAO,CAAC,CAC7D;QAED,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,8DAA8D,CAC/D,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyStateChainEntry,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport function principalHistoryVerificationContext(\n input: RecoverPrincipalPolicyHistoryOptions,\n): string {\n const mode = input.historyVerification ?? \"standard\";\n if (mode !== \"standard\" && mode !== \"direct-admins\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Unknown principal history verification mode\",\n );\n if (mode === \"standard\") return input.protection.context;\n if (\n input.expectedHead.principalType !== \"group\" ||\n input.loadExternalAuthority\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Strict Admins history requires a group without external authority fallback\",\n );\n // Retire this local attestation domain whenever strict validation changes.\n return serializeKeyingCanonicalJson([\n \"tearleads.sdk.principal-history.direct-admins.v1\",\n input.protection.context,\n ]);\n}\n\nexport function assertPrincipalHistoryVerificationMode(\n input: RecoverPrincipalPolicyHistoryOptions,\n entries: readonly PrincipalPolicyStateChainEntry[],\n): void {\n if (input.historyVerification !== \"direct-admins\") return;\n if (\n entries.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Reserved Admins history must contain only direct admin users\",\n );\n}\n"]}
1
+ {"version":3,"file":"principalHistoryRecoveryVerification.js","sourceRoot":"","sources":["principalHistoryRecoveryVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAG3B,MAAM,UAAU,mCAAmC,CACjD,KAA2C;IAE3C,MAAM,IAAI,GAAG,KAAK,CAAC,mBAAmB,IAAI,UAAU,CAAC;IACrD,IAAI,IAAI,KAAK,UAAU,IAAI,IAAI,KAAK,eAAe;QACjD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,6CAA6C,CAC9C,CAAC;IACJ,IAAI,IAAI,KAAK,UAAU;QACrB,OAAO,KAAK,CAAC,qBAAqB;YAChC,CAAC,CAAC,4BAA4B,CAAC;gBAC3B,uDAAuD;gBACvD,KAAK,CAAC,UAAU,CAAC,OAAO;aACzB,CAAC;YACJ,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC;IAC/B,IACE,KAAK,CAAC,YAAY,CAAC,aAAa,KAAK,OAAO;QAC5C,KAAK,CAAC,qBAAqB;QAE3B,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,4EAA4E,CAC7E,CAAC;IACJ,2EAA2E;IAC3E,OAAO,4BAA4B,CAAC;QAClC,kDAAkD;QAClD,KAAK,CAAC,UAAU,CAAC,OAAO;KACzB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,KAA2C,EAC3C,OAAkD;IAElD,IAAI,KAAK,CAAC,mBAAmB,KAAK,eAAe;QAAE,OAAO;IAC1D,IACE,OAAO,CAAC,IAAI,CACV,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC;QAC7B,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,OAAO,CAAC,CAC7D;QAED,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,8DAA8D,CAC/D,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyStateChainEntry,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport function principalHistoryVerificationContext(\n input: RecoverPrincipalPolicyHistoryOptions,\n): string {\n const mode = input.historyVerification ?? \"standard\";\n if (mode !== \"standard\" && mode !== \"direct-admins\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Unknown principal history verification mode\",\n );\n if (mode === \"standard\")\n return input.loadExternalAuthority\n ? serializeKeyingCanonicalJson([\n \"tearleads.sdk.principal-history.external-authority.v1\",\n input.protection.context,\n ])\n : input.protection.context;\n if (\n input.expectedHead.principalType !== \"group\" ||\n input.loadExternalAuthority\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Strict Admins history requires a group without external authority fallback\",\n );\n // Retire this local attestation domain whenever strict validation changes.\n return serializeKeyingCanonicalJson([\n \"tearleads.sdk.principal-history.direct-admins.v1\",\n input.protection.context,\n ]);\n}\n\nexport function assertPrincipalHistoryVerificationMode(\n input: RecoverPrincipalPolicyHistoryOptions,\n entries: readonly PrincipalPolicyStateChainEntry[],\n): void {\n if (input.historyVerification !== \"direct-admins\") return;\n if (\n entries.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Reserved Admins history must contain only direct admin users\",\n );\n}\n"]}
@@ -4,7 +4,7 @@ import { assertProjectionVerificationCurrent } from "../../data/keyingProjection
4
4
  import { PrincipalPolicyHistoryReadError } from "./principalHistoryRecoveryTypes.js";
5
5
  import { recoverScopedPrincipalPolicyHistory } from "./recoverScopedPrincipalPolicyHistory.js";
6
6
  /** Refusals and invalid evidence must never silently select a cached policy. */
7
- function isPrincipalRecoveryOutage(error) {
7
+ export function isPrincipalRecoveryOutage(error) {
8
8
  if (!(error instanceof PrincipalPolicyHistoryReadError))
9
9
  return false;
10
10
  const { failure } = error;
@@ -1 +1 @@
1
- {"version":3,"file":"principalRecoveryOutage.js","sourceRoot":"","sources":["principalRecoveryOutage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAE5F,gFAAgF;AAChF,SAAS,yBAAyB,CAAC,KAAc;IAC/C,IAAI,CAAC,CAAC,KAAK,YAAY,+BAA+B,CAAC;QAAE,OAAO,KAAK,CAAC;IACtE,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IAC1B,OAAO,CACL,OAAO,CAAC,IAAI,KAAK,SAAS;QAC1B,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM;YACtB,OAAO,CAAC,MAAM,KAAK,IAAI;YACvB,OAAO,CAAC,MAAM,IAAI,GAAG,CAAC;QACxB,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW;YAC3B,OAAO,CAAC,IAAI,KAAK,qCAAqC,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,OAAmD,EACnD,OAAkE;IAElE,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC1D,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC;YAAE,MAAM,KAAK,CAAC;QACtE,IAAI,CAAC;YACH,OAAO,MAAM,mCAAmC,CAAC;gBAC/C,GAAG,OAAO;gBACV,OAAO,EAAE,IAAI;aACd,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,UAAU,EAAE,CAAC;YACpB,IACE,UAAU,YAAY,uBAAuB;gBAC7C,UAAU,CAAC,IAAI,KAAK,oBAAoB;gBAExC,MAAM,IAAI,oCAAoC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;YACrE,MAAM,UAAU,CAAC;QACnB,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyHistoryReadError } from \"./principalHistoryRecoveryTypes\";\nimport { recoverScopedPrincipalPolicyHistory } from \"./recoverScopedPrincipalPolicyHistory\";\n\n/** Refusals and invalid evidence must never silently select a cached policy. */\nfunction isPrincipalRecoveryOutage(error: unknown): boolean {\n if (!(error instanceof PrincipalPolicyHistoryReadError)) return false;\n const { failure } = error;\n return (\n failure.kind === \"network\" ||\n (failure.kind === \"http\" &&\n failure.status !== null &&\n failure.status >= 500) ||\n (failure.kind === \"cancelled\" &&\n failure.code === \"principal_history_request_timed_out\")\n );\n}\n\nexport async function recoverWithPrincipalOutageFallback(\n recover: typeof recoverScopedPrincipalPolicyHistory,\n options: Parameters<typeof recoverScopedPrincipalPolicyHistory>[0],\n) {\n try {\n return await recover(options);\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (options.offline || !isPrincipalRecoveryOutage(error)) throw error;\n try {\n return await recoverScopedPrincipalPolicyHistory({\n ...options,\n offline: true,\n });\n } catch (localError) {\n if (\n localError instanceof KeyingVerificationError &&\n localError.code === \"missing_dependency\"\n )\n throw new ProjectionDependencyUnavailableError(localError.message);\n throw localError;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"principalRecoveryOutage.js","sourceRoot":"","sources":["principalRecoveryOutage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAE5F,gFAAgF;AAChF,MAAM,UAAU,yBAAyB,CAAC,KAAc;IACtD,IAAI,CAAC,CAAC,KAAK,YAAY,+BAA+B,CAAC;QAAE,OAAO,KAAK,CAAC;IACtE,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IAC1B,OAAO,CACL,OAAO,CAAC,IAAI,KAAK,SAAS;QAC1B,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM;YACtB,OAAO,CAAC,MAAM,KAAK,IAAI;YACvB,OAAO,CAAC,MAAM,IAAI,GAAG,CAAC;QACxB,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW;YAC3B,OAAO,CAAC,IAAI,KAAK,qCAAqC,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,OAAmD,EACnD,OAAkE;IAElE,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC1D,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC;YAAE,MAAM,KAAK,CAAC;QACtE,IAAI,CAAC;YACH,OAAO,MAAM,mCAAmC,CAAC;gBAC/C,GAAG,OAAO;gBACV,OAAO,EAAE,IAAI;aACd,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,UAAU,EAAE,CAAC;YACpB,IACE,UAAU,YAAY,uBAAuB;gBAC7C,UAAU,CAAC,IAAI,KAAK,oBAAoB;gBAExC,MAAM,IAAI,oCAAoC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;YACrE,MAAM,UAAU,CAAC;QACnB,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyHistoryReadError } from \"./principalHistoryRecoveryTypes\";\nimport { recoverScopedPrincipalPolicyHistory } from \"./recoverScopedPrincipalPolicyHistory\";\n\n/** Refusals and invalid evidence must never silently select a cached policy. */\nexport function isPrincipalRecoveryOutage(error: unknown): boolean {\n if (!(error instanceof PrincipalPolicyHistoryReadError)) return false;\n const { failure } = error;\n return (\n failure.kind === \"network\" ||\n (failure.kind === \"http\" &&\n failure.status !== null &&\n failure.status >= 500) ||\n (failure.kind === \"cancelled\" &&\n failure.code === \"principal_history_request_timed_out\")\n );\n}\n\nexport async function recoverWithPrincipalOutageFallback(\n recover: typeof recoverScopedPrincipalPolicyHistory,\n options: Parameters<typeof recoverScopedPrincipalPolicyHistory>[0],\n) {\n try {\n return await recover(options);\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (options.offline || !isPrincipalRecoveryOutage(error)) throw error;\n try {\n return await recoverScopedPrincipalPolicyHistory({\n ...options,\n offline: true,\n });\n } catch (localError) {\n if (\n localError instanceof KeyingVerificationError &&\n localError.code === \"missing_dependency\"\n )\n throw new ProjectionDependencyUnavailableError(localError.message);\n throw localError;\n }\n }\n}\n"]}
@@ -0,0 +1,60 @@
1
+ import { KeyingVerificationError, serializeKeyingCanonicalJson, } from "../../internal/crypto/index.js";
2
+ import { isReferencedPrincipalStateResponse } from "../../internal/validators/response/index.js";
3
+ import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
4
+ /** The greatest cited Admins head commits to the lineage of every earlier citation. */
5
+ export function publicHistoryAuthorityReference(previous, references) {
6
+ return references.reduce((head, reference) => !head || reference.version > head.version ? reference : head, previous);
7
+ }
8
+ export function publicHistoryAuthorityJson(reference) {
9
+ return serializeKeyingCanonicalJson(reference ? { ...reference } : null);
10
+ }
11
+ export function parsePublicHistoryAuthority(input, json) {
12
+ try {
13
+ const value = JSON.parse(json);
14
+ if (value === null)
15
+ return null;
16
+ if (isReferencedPrincipalStateResponse(value) &&
17
+ value.principalType === "group" &&
18
+ value.principalId === input.authorityGroupId)
19
+ return value;
20
+ }
21
+ catch {
22
+ /* Invalid disposable metadata cannot restore verified progress. */
23
+ }
24
+ return undefined;
25
+ }
26
+ export async function loadPublicHistoryAuthority(input, references, cachedPrefix = false) {
27
+ if (!references.length)
28
+ return undefined;
29
+ const authority = await input.loadExternalAuthority?.(references, cachedPrefix);
30
+ if (authority &&
31
+ (authority.currentHead.principalId !== input.authorityGroupId ||
32
+ authority.states.some(({ head }) => head.principalId !== input.authorityGroupId)))
33
+ throw new KeyingVerificationError("object_mismatch", "Authority callback differs from the directory binding");
34
+ if (references.some((reference) => !authority?.states.some(({ head }) => principalHeadMatchesReference(head, reference))))
35
+ throw new KeyingVerificationError("stale_predecessor", "Public history authority differs from its verified Admins lineage");
36
+ return authority;
37
+ }
38
+ export async function validatePublicHistoryAuthority(input, reference, rejectedPrefix = null) {
39
+ try {
40
+ if (reference)
41
+ await loadPublicHistoryAuthority(input, [reference], true);
42
+ }
43
+ catch (error) {
44
+ if (error instanceof KeyingVerificationError)
45
+ throw new PublicHistoryAuthorityUnavailableError(error, rejectedPrefix);
46
+ throw error;
47
+ }
48
+ }
49
+ /** Only cache restoration can request a replay after an authority mismatch. */
50
+ export class PublicHistoryAuthorityUnavailableError extends Error {
51
+ verificationError;
52
+ rejectedPrefix;
53
+ constructor(verificationError, rejectedPrefix) {
54
+ super(verificationError.message);
55
+ this.verificationError = verificationError;
56
+ this.rejectedPrefix = rejectedPrefix;
57
+ this.name = "PublicHistoryAuthorityUnavailableError";
58
+ }
59
+ }
60
+ //# sourceMappingURL=publicPrincipalHistoryAuthority.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publicPrincipalHistoryAuthority.js","sourceRoot":"","sources":["publicPrincipalHistoryAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AAEpF,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AAGtG,uFAAuF;AACvF,MAAM,UAAU,+BAA+B,CAC7C,QAAwC,EACxC,UAA8C;IAE9C,OAAO,UAAU,CAAC,MAAM,CACtB,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,CAClB,CAAC,IAAI,IAAI,SAAS,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,EAC9D,QAAQ,CACT,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,SAAyC;IAEzC,OAAO,4BAA4B,C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IAAI,EAAE,SAAS,CAAC,CAC/C,CACJ;QAED,MAAM,IAAI,uBAAuB,CAC/B,mBAAmB,EACnB,mEAAmE,CACpE,CAAC;IACJ,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,KAAoC,EACpC,SAAyC,EACzC,iBAAgD,IAAI;IAEpD,IAAI,CAAC;QACH,IAAI,SAAS;YAAE,MAAM,0BAA0B,CAAC,KAAK,EAAE,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB;YAC1C,MAAM,IAAI,sCAAsC,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;QAC1E,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,+EAA+E;AAC/E,MAAM,OAAO,sCAAuC,SAAQ,KAAK;IAEpD;IACA;IAFX,YACW,iBAA0C,EAC1C,cAA6C;QAEtD,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAHxB,sBAAiB,GAAjB,iBAAiB,CAAyB;QAC1C,mBAAc,GAAd,cAAc,CAA+B;QAGtD,IAAI,CAAC,IAAI,GAAG,wCAAwC,CAAC;IACvD,CAAC;CACF","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { isReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { PublicPrincipalHistoryOptions } from \"./publicPrincipalHistoryTypes\";\n\n/** The greatest cited Admins head commits to the lineage of every earlier citation. */\nexport function publicHistoryAuthorityReference(\n previous: ReferencedPrincipalHead | null,\n references: readonly ReferencedPrincipalHead[],\n) {\n return references.reduce<ReferencedPrincipalHead | null>(\n (head, reference) =>\n !head || reference.version > head.version ? reference : head,\n previous,\n );\n}\n\nexport function publicHistoryAuthorityJson(\n reference: ReferencedPrincipalHead | null,\n) {\n return serializeKeyingCanonicalJson(reference ? { ...reference } : null);\n}\n\nexport function parsePublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n json: string,\n): ReferencedPrincipalHead | null | undefined {\n try {\n const value: unknown = JSON.parse(json);\n if (value === null) return null;\n if (\n isReferencedPrincipalStateResponse(value) &&\n value.principalType === \"group\" &&\n value.principalId === input.authorityGroupId\n )\n return value;\n } catch {\n /* Invalid disposable metadata cannot restore verified progress. */\n }\n return undefined;\n}\n\nexport async function loadPublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n references: readonly ReferencedPrincipalHead[],\n cachedPrefix = false,\n) {\n if (!references.length) return undefined;\n const authority = await input.loadExternalAuthority?.(\n references,\n cachedPrefix,\n );\n if (\n authority &&\n (authority.currentHead.principalId !== input.authorityGroupId ||\n authority.states.some(\n ({ head }) => head.principalId !== input.authorityGroupId,\n ))\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Authority callback differs from the directory binding\",\n );\n if (\n references.some(\n (reference) =>\n !authority?.states.some(({ head }) =>\n principalHeadMatchesReference(head, reference),\n ),\n )\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Public history authority differs from its verified Admins lineage\",\n );\n return authority;\n}\n\nexport async function validatePublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n reference: ReferencedPrincipalHead | null,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<void> {\n try {\n if (reference) await loadPublicHistoryAuthority(input, [reference], true);\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PublicHistoryAuthorityUnavailableError(error, rejectedPrefix);\n throw error;\n }\n}\n\n/** Only cache restoration can request a replay after an authority mismatch. */\nexport class PublicHistoryAuthorityUnavailableError extends Error {\n constructor(\n readonly verificationError: KeyingVerificationError,\n readonly rejectedPrefix: PrincipalHistoryPrefix | null,\n ) {\n super(verificationError.message);\n this.name = \"PublicHistoryAuthorityUnavailableError\";\n }\n}\n"]}