@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
@@ -1 +1 @@
1
- {"version":3,"file":"recoverPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverPrincipalPolicyHistory.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAGvB,+BAA+B,EAC/B,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA4D,CAAC;AACjH,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,+BAA+B,EAAE,MAAM,uDAAuD,CAAC;AACxG,OAAO,EAAE,sCAAsC,EAAE,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EACL,wCAAwC,EACxC,+BAA+B,GAChC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAEL,oCAAoC,GACrC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,iCAAiC,EACjC,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,sCAAsC,EACtC,mCAAmC,GACpC,MAAM,wCAAwC,CAAC;AAEhD,MAAM,uCAAwC,SAAQ,KAAK;IACpC;IAArB,YAAqB,iBAA0C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AAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryInput,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyPageResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport {\n discardPrincipalHistoryStage,\n savePrincipalHistoryStage,\n} from \"../../data/persistence/principalHistoryStagePersistence\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { principalHistoryStageProtection } from \"../../data/principals/principalHistoryStageProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./policyVerification\";\nimport { publishReusablePrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport {\n PrincipalHistoryEvidenceUnavailableError,\n selectRecoveredPrincipalHistory,\n} from \"./principalHistoryRecoveryReferences\";\nimport {\n type PrincipalHistoryRecoveryStage,\n restorePrincipalHistoryRecoveryStage,\n} from \"./principalHistoryRecoveryStage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"./principalHistoryRecoveryVerification\";\n\nclass PrincipalHistoryPrefixDisconnectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PrincipalHistoryPrefixDisconnectedError\";\n }\n}\n\nfunction currentArtifacts(\n page: PrincipalPolicyPageResponse,\n): PrincipalPolicyPageCurrent {\n return {\n currentState: page.currentState,\n currentPayload: page.currentPayload,\n currentProjection: page.currentProjection,\n currentGrants: page.currentGrants,\n currentMemberEnvelopes: page.currentMemberEnvelopes,\n };\n}\n\nfunction recoveryIsCurrent(\n input: RecoverPrincipalPolicyHistoryOptions,\n): boolean {\n return !input.signal?.aborted && input.stillCurrent();\n}\n\nfunction assertCurrent(input: RecoverPrincipalPolicyHistoryOptions): void {\n assertProjectionVerificationCurrent(() => recoveryIsCurrent(input));\n}\n\nfunction assertExpectedHead(\n current: PrincipalPolicyPageCurrent,\n expectedHead: RecoverPrincipalPolicyHistoryOptions[\"expectedHead\"],\n): void {\n for (const field of [\n \"principalType\",\n \"principalId\",\n \"version\",\n \"stateHash\",\n \"keyEpoch\",\n \"keyFingerprint\",\n ] as const) {\n if (current.currentState[field] !== expectedHead[field])\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history page does not match its requested head\",\n );\n }\n}\n\nasync function acceptPage(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n response: PrincipalPolicyPageResponse,\n): Promise<void> {\n const page = structuredClone(response);\n assertCurrent(input);\n assertExpectedHead(page, input.expectedHead);\n if (stage.complete) {\n if (\n page.previousStates.length !== 0 ||\n page.historyPage.nextAfterVersion !== null\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed history returned additional entries\",\n );\n stage.current = currentArtifacts(page);\n return;\n }\n const complete = page.historyPage.nextAfterVersion === null;\n const current = currentArtifacts(page);\n const entries = [...page.previousStates];\n if (complete)\n entries.push({\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n });\n assertPrincipalHistoryVerificationMode(input, entries);\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: page.previousStates },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Principal history signer identity could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(entries);\n const appended = await stage.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) {\n if (appended.error.code === \"stale_predecessor\")\n throw new PrincipalHistoryPrefixDisconnectedError(appended.error);\n throw appended.error;\n }\n const next = {\n id: stage.id,\n organizationId: input.organizationId,\n currentJson: JSON.stringify(current),\n afterVersion: appended.value.throughVersion - (complete ? 1 : 0),\n complete,\n };\n const protectedProgress = await stage.verifier.exportProgress(\n await principalHistoryStageProtection(\n input.protection,\n input.expectedHead,\n next,\n ),\n );\n if (!protectedProgress.ok) throw protectedProgress.error;\n const saved = { ...next, progress: protectedProgress.value };\n await savePrincipalHistoryStage({\n execSql: input.execSql,\n stage: saved,\n evidence: await preparePrincipalHistoryEvidencePage({\n scopeId: stage.scopeId,\n organizationId: input.organizationId,\n entries,\n nodes: appended.value.indexNodes,\n }),\n previousProgress: stage.saved?.progress ?? null,\n stillCurrent: () => recoveryIsCurrent(input),\n });\n stage.current = current;\n stage.saved = saved;\n stage.complete = complete;\n}\n\nasync function finishRecovery(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (!stage.current || !stage.complete)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history ended before its pinned head\",\n );\n const history = stage.verifier.finish(input.expectedHead);\n if (!history.ok) throw history.error;\n const selected = await selectRecoveredPrincipalHistory({\n options: input,\n scopeId: stage.scopeId,\n history: history.value,\n checkpoint,\n });\n const current = await verifyPrincipalPolicyCurrent({\n current: stage.current,\n history: selected,\n });\n if (!current.ok) throw current.error;\n verifyPrincipalPolicyCheckpoint({\n chain: current.value.retainedHistory,\n currentState: current.value.state,\n localCheckpoint: checkpoint,\n });\n const latest = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (\n latest?.version !== checkpoint?.version ||\n latest?.stateHash !== checkpoint?.stateHash\n )\n throw new PrincipalHistoryRecoveryRaceError(\n \"Local principal checkpoint changed during history recovery\",\n );\n assertCurrent(input);\n if (!input.offline)\n await publishReusablePrincipalHistoryPrefix(\n input,\n stage.scopeId,\n stage.verifier,\n stage.current,\n );\n assertCurrent(input);\n return { current: stage.current, policy: current.value };\n}\n\nasync function readRecoveryPages(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n): Promise<void> {\n if (input.offline) {\n if (!stage.complete || !stage.current)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed principal history is unavailable offline\",\n );\n assertExpectedHead(stage.current, input.expectedHead);\n return;\n }\n let receivedFinalPage = false;\n for await (const result of input.apiClient.getPrincipalPolicyPages(\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n {\n signal: input.signal,\n stateHash: input.expectedHead.stateHash,\n ...(stage.saved && stage.current\n ? {\n resume: {\n current: stage.current,\n afterVersion: stage.saved.afterVersion,\n },\n }\n : { afterVersion: stage.initialAfterVersion }),\n },\n )) {\n if (!result.ok) {\n // A rejected transport pin cannot justify skipping history on retry.\n // Discard only this operation's progress, then let a new call replay it.\n if (result.kind === \"shape\" && stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n throw new PrincipalPolicyHistoryReadError(result);\n }\n await acceptPage(input, stage, result.data);\n receivedFinalPage = result.data.historyPage.nextAfterVersion === null;\n }\n if (!receivedFinalPage)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history transport did not complete\",\n );\n}\n\nasync function recover(\n input: RecoverPrincipalPolicyHistoryOptions,\n allowEvidenceRebuild = true,\n): Promise<RecoveredPrincipalPolicyHistory> {\n assertCurrent(input);\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (checkpoint && input.expectedHead.version < checkpoint.version)\n throw new KeyingVerificationError(\n input.offline ? \"missing_dependency\" : \"rollback\",\n \"Requested principal history predates the local checkpoint\",\n );\n // Validate the requested pin/selection before creating any disposable caches.\n createPrincipalPolicyHistoryVerifier({\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n localCheckpoint: checkpoint,\n retainedReferences: input.retainedReferences ?? [],\n });\n const historyInput: PrincipalPolicyHistoryInput = {\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n };\n const stage = await restorePrincipalHistoryRecoveryStage(\n input,\n historyInput,\n allowEvidenceRebuild,\n );\n try {\n await readRecoveryPages(input, stage);\n return await finishRecovery(input, stage, checkpoint);\n } catch (error) {\n const lostEvidence =\n error instanceof PrincipalHistoryEvidenceUnavailableError;\n const disconnected =\n error instanceof PrincipalHistoryPrefixDisconnectedError;\n if (!lostEvidence && !disconnected) throw error;\n if (stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n if (\n !input.offline &&\n allowEvidenceRebuild &&\n (lostEvidence || stage.fromCache)\n )\n return recover(input, false);\n throw lostEvidence || disconnected ? error.verificationError : error;\n }\n}\n\n/**\n * Recover one exact head with bounded retained history and durable checked progress.\n * The result is a sparse current-policy capability; this does not advance app checkpoints.\n * Retain organization version 1 when the result will establish founder binding.\n */\nexport async function recoverPrincipalPolicyHistory(\n options: RecoverPrincipalPolicyHistoryOptions,\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (\n !options.organizationId ||\n (options.expectedHead.principalType === \"organization\" &&\n options.expectedHead.principalId !== options.organizationId)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history organization scope is invalid\",\n );\n if (\n options.retainedReferences?.some(\n (reference) => reference.version > options.expectedHead.version,\n )\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested history reference is beyond the recovery head\",\n );\n const input = {\n ...options,\n historyVerification: options.historyVerification ?? \"standard\",\n expectedHead: structuredClone(options.expectedHead),\n retainedReferences: structuredClone(options.retainedReferences ?? []),\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n input.protection.context = principalHistoryVerificationContext(input);\n return await recover(input);\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n"]}
1
+ {"version":3,"file":"recoverPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverPrincipalPolicyHistory.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAGvB,+BAA+B,EAC/B,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA4D,CAAC;AACjH,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,+BAA+B,EAAE,MAAM,uDAAuD,CAAC;AACxG,OAAO,EAAE,sCAAsC,EAAE,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AAChG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EACL,wCAAwC,EACxC,+BAA+B,GAChC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAEL,oCAAoC,GACrC,MAAM,iCAAiC,CAAC;A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,KAAK,GAAG;QACZ,GAAG,OAAO;QACV,mBAAmB,EAAE,OAAO,CAAC,mBAAmB,IAAI,UAAU;QAC9D,YAAY,EAAE,eAAe,CAAC,OAAO,CAAC,YAAY,CAAC;QACnD,kBAAkB,EAAE,eAAe,CAAC,OAAO,CAAC,kBAAkB,IAAI,EAAE,CAAC;QACrE,UAAU,EAAE,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC;KAC9D,CAAC;IACF,IAAI,CAAC;QACH,KAAK,CAAC,UAAU,CAAC,OAAO,GAAG,mCAAmC,CAAC,KAAK,CAAC,CAAC;QACtE,OAAO,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryInput,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyPageResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport {\n discardPrincipalHistoryStage,\n savePrincipalHistoryStage,\n} from \"../../data/persistence/principalHistoryStagePersistence\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { principalHistoryStageProtection } from \"../../data/principals/principalHistoryStageProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./policyVerification\";\nimport { validatePrincipalHistoryRecoveryAuthority } from \"./principalHistoryRecoveryAuthority\";\nimport { publishReusablePrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport {\n PrincipalHistoryEvidenceUnavailableError,\n selectRecoveredPrincipalHistory,\n} from \"./principalHistoryRecoveryReferences\";\nimport {\n type PrincipalHistoryRecoveryStage,\n restorePrincipalHistoryRecoveryStage,\n} from \"./principalHistoryRecoveryStage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"./principalHistoryRecoveryVerification\";\n\nclass PrincipalHistoryPrefixDisconnectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PrincipalHistoryPrefixDisconnectedError\";\n }\n}\n\nfunction currentArtifacts(\n page: PrincipalPolicyPageResponse,\n): PrincipalPolicyPageCurrent {\n return {\n currentState: page.currentState,\n currentPayload: page.currentPayload,\n currentProjection: page.currentProjection,\n currentGrants: page.currentGrants,\n currentMemberEnvelopes: page.currentMemberEnvelopes,\n };\n}\n\nfunction recoveryIsCurrent(\n input: RecoverPrincipalPolicyHistoryOptions,\n): boolean {\n return !input.signal?.aborted && input.stillCurrent();\n}\n\nfunction assertCurrent(input: RecoverPrincipalPolicyHistoryOptions): void {\n assertProjectionVerificationCurrent(() => recoveryIsCurrent(input));\n}\n\nfunction assertExpectedHead(\n current: PrincipalPolicyPageCurrent,\n expectedHead: RecoverPrincipalPolicyHistoryOptions[\"expectedHead\"],\n): void {\n for (const field of [\n \"principalType\",\n \"principalId\",\n \"version\",\n \"stateHash\",\n \"keyEpoch\",\n \"keyFingerprint\",\n ] as const) {\n if (current.currentState[field] !== expectedHead[field])\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history page does not match its requested head\",\n );\n }\n}\n\nasync function acceptPage(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n response: PrincipalPolicyPageResponse,\n): Promise<void> {\n const page = structuredClone(response);\n assertCurrent(input);\n assertExpectedHead(page, input.expectedHead);\n if (stage.complete) {\n if (\n page.previousStates.length !== 0 ||\n page.historyPage.nextAfterVersion !== null\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed history returned additional entries\",\n );\n stage.current = currentArtifacts(page);\n return;\n }\n const complete = page.historyPage.nextAfterVersion === null;\n const current = currentArtifacts(page);\n const entries = [...page.previousStates];\n if (complete)\n entries.push({\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n });\n assertPrincipalHistoryVerificationMode(input, entries);\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: page.previousStates },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Principal history signer identity could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(\n entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n ),\n );\n const appended = await stage.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) {\n if (appended.error.code === \"stale_predecessor\")\n throw new PrincipalHistoryPrefixDisconnectedError(appended.error);\n throw appended.error;\n }\n const next = {\n id: stage.id,\n organizationId: input.organizationId,\n currentJson: JSON.stringify(current),\n afterVersion: appended.value.throughVersion - (complete ? 1 : 0),\n complete,\n };\n const protectedProgress = await stage.verifier.exportProgress(\n await principalHistoryStageProtection(\n input.protection,\n input.expectedHead,\n next,\n ),\n );\n if (!protectedProgress.ok) throw protectedProgress.error;\n const saved = { ...next, progress: protectedProgress.value };\n await savePrincipalHistoryStage({\n execSql: input.execSql,\n stage: saved,\n evidence: await preparePrincipalHistoryEvidencePage({\n scopeId: stage.scopeId,\n organizationId: input.organizationId,\n entries,\n nodes: appended.value.indexNodes,\n }),\n previousProgress: stage.saved?.progress ?? null,\n stillCurrent: () => recoveryIsCurrent(input),\n });\n stage.current = current;\n stage.saved = saved;\n stage.complete = complete;\n}\n\nasync function finishRecovery(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (!stage.current || !stage.complete)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history ended before its pinned head\",\n );\n const history = stage.verifier.finish(input.expectedHead);\n if (!history.ok) throw history.error;\n const selected = await selectRecoveredPrincipalHistory({\n options: input,\n scopeId: stage.scopeId,\n history: history.value,\n checkpoint,\n });\n const current = await verifyPrincipalPolicyCurrent({\n current: stage.current,\n history: selected,\n });\n if (!current.ok) throw current.error;\n verifyPrincipalPolicyCheckpoint({\n chain: current.value.retainedHistory,\n currentState: current.value.state,\n localCheckpoint: checkpoint,\n });\n const latest = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (\n latest?.version !== checkpoint?.version ||\n latest?.stateHash !== checkpoint?.stateHash\n )\n throw new PrincipalHistoryRecoveryRaceError(\n \"Local principal checkpoint changed during history recovery\",\n );\n assertCurrent(input);\n if (!input.offline)\n await publishReusablePrincipalHistoryPrefix(\n input,\n stage.scopeId,\n stage.verifier,\n stage.current,\n );\n assertCurrent(input);\n return { current: stage.current, policy: current.value };\n}\n\nasync function readRecoveryPages(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n): Promise<void> {\n if (input.offline) {\n if (!stage.complete || !stage.current)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed principal history is unavailable offline\",\n );\n assertExpectedHead(stage.current, input.expectedHead);\n return;\n }\n let receivedFinalPage = false;\n for await (const result of input.apiClient.getPrincipalPolicyPages(\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n {\n signal: input.signal,\n stateHash: input.expectedHead.stateHash,\n ...(stage.saved && stage.current\n ? {\n resume: {\n current: stage.current,\n afterVersion: stage.saved.afterVersion,\n },\n }\n : { afterVersion: stage.initialAfterVersion }),\n },\n )) {\n if (!result.ok) {\n // A rejected transport pin cannot justify skipping history on retry.\n // Discard only this operation's progress, then let a new call replay it.\n if (result.kind === \"shape\" && stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n throw new PrincipalPolicyHistoryReadError(result);\n }\n await acceptPage(input, stage, result.data);\n receivedFinalPage = result.data.historyPage.nextAfterVersion === null;\n }\n if (!receivedFinalPage)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history transport did not complete\",\n );\n}\n\nasync function recover(\n input: RecoverPrincipalPolicyHistoryOptions,\n allowEvidenceRebuild = true,\n): Promise<RecoveredPrincipalPolicyHistory> {\n assertCurrent(input);\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (checkpoint && input.expectedHead.version < checkpoint.version)\n throw new KeyingVerificationError(\n input.offline ? \"missing_dependency\" : \"rollback\",\n \"Requested principal history predates the local checkpoint\",\n );\n // Validate the requested pin/selection before creating any disposable caches.\n createPrincipalPolicyHistoryVerifier({\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n localCheckpoint: checkpoint,\n retainedReferences: input.retainedReferences ?? [],\n });\n const historyInput: PrincipalPolicyHistoryInput = {\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n };\n const stage = await restorePrincipalHistoryRecoveryStage(\n input,\n historyInput,\n allowEvidenceRebuild,\n );\n try {\n if (stage.fromCache)\n await validatePrincipalHistoryRecoveryAuthority(input, stage.verifier);\n await readRecoveryPages(input, stage);\n return await finishRecovery(input, stage, checkpoint);\n } catch (error) {\n const lostEvidence =\n error instanceof PrincipalHistoryEvidenceUnavailableError;\n const disconnected =\n error instanceof PrincipalHistoryPrefixDisconnectedError;\n if (!lostEvidence && !disconnected) throw error;\n if (stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n if (\n !input.offline &&\n allowEvidenceRebuild &&\n (lostEvidence || stage.fromCache)\n )\n return recover(input, false);\n throw lostEvidence || disconnected ? error.verificationError : error;\n }\n}\n\n/**\n * Recover one exact head with bounded retained history and durable checked progress.\n * The result is a sparse current-policy capability; this does not advance app checkpoints.\n * Retain organization version 1 when the result will establish founder binding.\n */\nexport async function recoverPrincipalPolicyHistory(\n options: RecoverPrincipalPolicyHistoryOptions,\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (\n !options.organizationId ||\n (options.expectedHead.principalType === \"organization\" &&\n options.expectedHead.principalId !== options.organizationId)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history organization scope is invalid\",\n );\n if (\n options.retainedReferences?.some(\n (reference) => reference.version > options.expectedHead.version,\n )\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested history reference is beyond the recovery head\",\n );\n const input = {\n ...options,\n historyVerification: options.historyVerification ?? \"standard\",\n expectedHead: structuredClone(options.expectedHead),\n retainedReferences: structuredClone(options.retainedReferences ?? []),\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n input.protection.context = principalHistoryVerificationContext(input);\n return await recover(input);\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n"]}
@@ -0,0 +1,9 @@
1
+ import { type ReferencedPrincipalHead, type VerifiedPrincipalPolicySelection } from "../../internal/crypto/index.js";
2
+ import type { ProjectionPolicyEvidenceResponse } from "../../internal/validators/response/index.js";
3
+ import type { PublicPrincipalHistoryOptions } from "./publicPrincipalHistoryTypes.js";
4
+ export interface ProjectionPolicyHistoryRecoveryOptions extends Omit<PublicPrincipalHistoryOptions, "source" | "loadExternalAuthority" | "strictAdmins" | "authorityGroupId" | "replay"> {
5
+ readonly evidence: ProjectionPolicyEvidenceResponse;
6
+ readonly references: readonly ReferencedPrincipalHead[];
7
+ }
8
+ /** Public authorization only; no current-policy cache or checkpoint is written. */
9
+ export declare function recoverProjectionPolicyHistory(input: ProjectionPolicyHistoryRecoveryOptions): Promise<VerifiedPrincipalPolicySelection[]>;
@@ -0,0 +1,98 @@
1
+ import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
+ import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
3
+ import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
4
+ import { publicProjectionDirectoryBindings } from "./publicProjectionDirectory.js";
5
+ import { recoverPublicProjectionPrincipal, rejectPublicProjection, selectPublicProjectionPrincipal, } from "./publicProjectionPrincipal.js";
6
+ function assertSourceCoverage(evidence, references) {
7
+ const sources = [evidence.organization, ...evidence.groups];
8
+ for (const reference of references)
9
+ if (!sources.some((source) => source &&
10
+ source.head.principalType === reference.principalType &&
11
+ source.head.principalId === reference.principalId &&
12
+ source.head.version >= reference.version))
13
+ rejectPublicProjection("required citation has no covering source");
14
+ }
15
+ async function externalAuthority(admins, references, cachedPrefix = false) {
16
+ const head = admins.options.source.head;
17
+ if (!references.length)
18
+ return undefined;
19
+ if (cachedPrefix &&
20
+ references.some((reference) => reference.version > head.version))
21
+ throw new KeyingVerificationError("missing_dependency", "Cached group history requires a newer Admins source");
22
+ if (references.some((reference) => reference.principalId !== head.principalId ||
23
+ reference.version > head.version))
24
+ rejectPublicProjection("external authority exceeds the bound Admins source");
25
+ const policies = await selectPublicProjectionPrincipal(admins, references);
26
+ const states = new Map(policies.flatMap((policy) =>
27
+ // Only this page's citations and the bound source head are authority for
28
+ // this verification step. A retained newer prefix is not another citation.
29
+ policy.retainedHistory
30
+ .filter(({ state }) => [head, ...references].some((reference) => principalHeadMatchesReference(state, reference)))
31
+ .map(({ state, projection }) => [
32
+ state.version,
33
+ {
34
+ head: {
35
+ principalType: "group",
36
+ principalId: state.principalId,
37
+ version: state.version,
38
+ stateHash: state.stateHash,
39
+ keyEpoch: state.keyEpoch,
40
+ keyFingerprint: state.keyFingerprint,
41
+ },
42
+ projection,
43
+ },
44
+ ])));
45
+ return {
46
+ currentHead: { ...head, principalType: "group" },
47
+ states: [...states.values()],
48
+ };
49
+ }
50
+ /** Public authorization only; no current-policy cache or checkpoint is written. */
51
+ export async function recoverProjectionPolicyHistory(input) {
52
+ assertProjectionVerificationCurrent(() => !input.signal?.aborted && input.stillCurrent());
53
+ input = { ...input, references: structuredClone(input.references) };
54
+ const evidence = structuredClone(input.evidence);
55
+ assertSourceCoverage(evidence, input.references);
56
+ if (!evidence.organization) {
57
+ if (evidence.groups.length || evidence.organizationPayloads.length)
58
+ rejectPublicProjection("group evidence requires organization history");
59
+ return [];
60
+ }
61
+ if (evidence.organization.head.principalType !== "organization")
62
+ rejectPublicProjection("organization source has the wrong principal type");
63
+ const organization = await recoverPublicProjectionPrincipal({
64
+ ...input,
65
+ source: evidence.organization,
66
+ }, [
67
+ ...input.references,
68
+ ...evidence.organizationPayloads.map(({ reference }) => reference),
69
+ ]);
70
+ const bindings = await publicProjectionDirectoryBindings(evidence, organization);
71
+ const principals = new Map();
72
+ const adminHeads = [...bindings.values()].map(({ adminHead }) => adminHead);
73
+ for (const adminId of new Set(adminHeads.map((head) => head.principalId))) {
74
+ const source = evidence.groups.find((group) => group.head.principalId === adminId);
75
+ if (!source)
76
+ rejectPublicProjection("signed Admins source is missing");
77
+ principals.set(adminId, await recoverPublicProjectionPrincipal({ ...input, source, strictAdmins: true }, [...input.references, ...adminHeads]));
78
+ }
79
+ for (const source of evidence.groups) {
80
+ if (principals.has(source.head.principalId))
81
+ continue;
82
+ const binding = bindings.get(source.head.principalId);
83
+ const admins = binding && principals.get(binding.adminHead.principalId);
84
+ if (!admins)
85
+ rejectPublicProjection("verified Admins history is missing");
86
+ principals.set(source.head.principalId, await recoverPublicProjectionPrincipal({
87
+ ...input,
88
+ source,
89
+ authorityGroupId: admins.options.source.head.principalId,
90
+ loadExternalAuthority: (references, cachedPrefix) => externalAuthority(admins, references, cachedPrefix),
91
+ }, input.references));
92
+ }
93
+ const policies = [];
94
+ for (const principal of [organization, ...principals.values()])
95
+ policies.push(...(await selectPublicProjectionPrincipal(principal)));
96
+ return policies;
97
+ }
98
+ //# sourceMappingURL=recoverProjectionPolicyHistory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recoverProjectionPolicyHistory.js","sourceRoot":"","sources":["recoverProjectionPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AAEtG,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,EAEL,gCAAgC,EAChC,sBAAsB,EACtB,+BAA+B,GAChC,MAAM,6BAA6B,CAAC;AAerC,SAAS,oBAAoB,CAC3B,QAA0C,EAC1C,UAA8C;IAE9C,MAAM,OAAO,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC5D,KAAK,MAAM,SAAS,IAAI,UAAU;QAChC,IACE,CAAC,OAAO,CAAC,IAAI,CACX,CAAC,MAAM,EAAE,EAAE,CACT,MAAM;YACN,MAAM,CAAC,IAAI,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;YACrD,MAAM,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW;YACjD,MAAM,CAAC,IAAI,CAAC,OAAO,IAAI,SAAS,CAAC,OAAO,CAC3C;YAED,sBAAsB,CAAC,0CAA0C,CAAC,CAAC;A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AAG,CAAC,OAAO,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QACxE,IAAI,CAAC,MAAM;YAAE,sBAAsB,CAAC,oCAAoC,CAAC,CAAC;QAC1E,UAAU,CAAC,GAAG,CACZ,MAAM,CAAC,IAAI,CAAC,WAAW,EACvB,MAAM,gCAAgC,CACpC;YACE,GAAG,KAAK;YACR,MAAM;YACN,gBAAgB,EAAE,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW;YACxD,qBAAqB,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,EAAE,CAClD,iBAAiB,CAAC,MAAM,EAAE,UAAU,EAAE,YAAY,CAAC;SACtD,EACD,KAAK,CAAC,UAAU,CACjB,CACF,CAAC;IACJ,CAAC;IACD,MAAM,QAAQ,GAAuC,EAAE,CAAC;IACxD,KAAK,MAAM,SAAS,IAAI,CAAC,YAAY,EAAE,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC;QAC5D,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,+BAA+B,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IACvE,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { PublicPrincipalHistoryOptions } from \"./publicPrincipalHistoryTypes\";\nimport { publicProjectionDirectoryBindings } from \"./publicProjectionDirectory\";\nimport {\n type PublicProjectionPrincipal,\n recoverPublicProjectionPrincipal,\n rejectPublicProjection,\n selectPublicProjectionPrincipal,\n} from \"./publicProjectionPrincipal\";\n\nexport interface ProjectionPolicyHistoryRecoveryOptions\n extends Omit<\n PublicPrincipalHistoryOptions,\n | \"source\"\n | \"loadExternalAuthority\"\n | \"strictAdmins\"\n | \"authorityGroupId\"\n | \"replay\"\n > {\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly references: readonly ReferencedPrincipalHead[];\n}\n\nfunction assertSourceCoverage(\n evidence: ProjectionPolicyEvidenceResponse,\n references: readonly ReferencedPrincipalHead[],\n): void {\n const sources = [evidence.organization, ...evidence.groups];\n for (const reference of references)\n if (\n !sources.some(\n (source) =>\n source &&\n source.head.principalType === reference.principalType &&\n source.head.principalId === reference.principalId &&\n source.head.version >= reference.version,\n )\n )\n rejectPublicProjection(\"required citation has no covering source\");\n}\n\nasync function externalAuthority(\n admins: PublicProjectionPrincipal,\n references: readonly ReferencedPrincipalHead[],\n cachedPrefix = false,\n): Promise<PrincipalPolicyExternalAuthority | undefined> {\n const head = admins.options.source.head;\n if (!references.length) return undefined;\n if (\n cachedPrefix &&\n references.some((reference) => reference.version > head.version)\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Cached group history requires a newer Admins source\",\n );\n if (\n references.some(\n (reference) =>\n reference.principalId !== head.principalId ||\n reference.version > head.version,\n )\n )\n rejectPublicProjection(\n \"external authority exceeds the bound Admins source\",\n );\n const policies = await selectPublicProjectionPrincipal(admins, references);\n const states = new Map(\n policies.flatMap((policy) =>\n // Only this page's citations and the bound source head are authority for\n // this verification step. A retained newer prefix is not another citation.\n policy.retainedHistory\n .filter(({ state }) =>\n [head, ...references].some((reference) =>\n principalHeadMatchesReference(state, reference),\n ),\n )\n .map(\n ({ state, projection }) =>\n [\n state.version,\n {\n head: {\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n },\n projection,\n },\n ] as const,\n ),\n ),\n );\n return {\n currentHead: { ...head, principalType: \"group\" },\n states: [...states.values()],\n };\n}\n\n/** Public authorization only; no current-policy cache or checkpoint is written. */\nexport async function recoverProjectionPolicyHistory(\n input: ProjectionPolicyHistoryRecoveryOptions,\n): Promise<VerifiedPrincipalPolicySelection[]> {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n input = { ...input, references: structuredClone(input.references) };\n const evidence = structuredClone(input.evidence);\n assertSourceCoverage(evidence, input.references);\n if (!evidence.organization) {\n if (evidence.groups.length || evidence.organizationPayloads.length)\n rejectPublicProjection(\"group evidence requires organization history\");\n return [];\n }\n if (evidence.organization.head.principalType !== \"organization\")\n rejectPublicProjection(\"organization source has the wrong principal type\");\n const organization = await recoverPublicProjectionPrincipal(\n {\n ...input,\n source: evidence.organization,\n },\n [\n ...input.references,\n ...evidence.organizationPayloads.map(({ reference }) => reference),\n ],\n );\n const bindings = await publicProjectionDirectoryBindings(\n evidence,\n organization,\n );\n const principals = new Map<string, PublicProjectionPrincipal>();\n const adminHeads = [...bindings.values()].map(({ adminHead }) => adminHead);\n for (const adminId of new Set(adminHeads.map((head) => head.principalId))) {\n const source = evidence.groups.find(\n (group) => group.head.principalId === adminId,\n );\n if (!source) rejectPublicProjection(\"signed Admins source is missing\");\n principals.set(\n adminId,\n await recoverPublicProjectionPrincipal(\n { ...input, source, strictAdmins: true },\n [...input.references, ...adminHeads],\n ),\n );\n }\n for (const source of evidence.groups) {\n if (principals.has(source.head.principalId)) continue;\n const binding = bindings.get(source.head.principalId);\n const admins = binding && principals.get(binding.adminHead.principalId);\n if (!admins) rejectPublicProjection(\"verified Admins history is missing\");\n principals.set(\n source.head.principalId,\n await recoverPublicProjectionPrincipal(\n {\n ...input,\n source,\n authorityGroupId: admins.options.source.head.principalId,\n loadExternalAuthority: (references, cachedPrefix) =>\n externalAuthority(admins, references, cachedPrefix),\n },\n input.references,\n ),\n );\n }\n const policies: VerifiedPrincipalPolicySelection[] = [];\n for (const principal of [organization, ...principals.values()])\n policies.push(...(await selectPublicProjectionPrincipal(principal)));\n return policies;\n}\n"]}
@@ -0,0 +1,176 @@
1
+ import { createPrincipalPolicyHistoryVerifier, KeyingVerificationError, serializeKeyingCanonicalJson, verifyPrincipalPolicyHistoryReferences, } from "../../internal/crypto/index.js";
2
+ import { isPrincipalPolicySnapshotPageResponse, } from "../../internal/validators/response/index.js";
3
+ import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
4
+ import { loadPrincipalHistoryReference } from "../../data/persistence/principalHistoryEvidencePersistence.js";
5
+ import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
6
+ import { ownPrincipalHistoryProtection } from "../../data/principals/principalHistoryProtection.js";
7
+ import { PrincipalPolicyHistoryReadError } from "./principalHistoryRecoveryTypes.js";
8
+ import { PublicHistoryAuthorityUnavailableError } from "./publicPrincipalHistoryAuthority.js";
9
+ import { appendPublicPrincipalHistoryPage, PublicPrincipalHistoryPrefixDisconnectedError, } from "./publicPrincipalHistoryPage.js";
10
+ import { publishPublicPrincipalHistoryPrefix, restorePublicPrincipalHistoryProgress, } from "./publicPrincipalHistoryProgress.js";
11
+ function assertPage(input, page, after) {
12
+ if (!isPrincipalPolicySnapshotPageResponse(page) ||
13
+ !principalHeadMatchesReference(page.currentState, input.source.head) ||
14
+ page.historyPage.afterVersion !== after)
15
+ throw new KeyingVerificationError("object_mismatch", "Public history page does not match its requested head and cursor");
16
+ const through = after + page.previousStates.length;
17
+ if (page.previousStates.some(({ state }, index) => state.version !== after + index + 1) ||
18
+ through >= input.source.head.version ||
19
+ (page.historyPage.nextAfterVersion === null
20
+ ? through !== input.source.head.version - 1
21
+ : through <= after || page.historyPage.nextAfterVersion !== through))
22
+ throw new KeyingVerificationError("invalid_shape", "Public history page has a gap or invalid continuation");
23
+ }
24
+ async function readPublicPages(input, initial) {
25
+ const current = () => !input.signal?.aborted && input.stillCurrent();
26
+ let progress = initial;
27
+ let lastPage;
28
+ if (!input.offline) {
29
+ for await (const result of input.apiClient.getProjectionPolicyHistoryPages(input.source, { afterVersion: progress.afterVersion, signal: input.signal })) {
30
+ assertProjectionVerificationCurrent(current);
31
+ if (!result.ok)
32
+ throw new PrincipalPolicyHistoryReadError(result);
33
+ const page = result.data;
34
+ assertPage(input, page, progress.afterVersion);
35
+ if (!progress.completedHead)
36
+ progress = await appendPublicPrincipalHistoryPage(input, progress, page);
37
+ else if (page.previousStates.length ||
38
+ page.historyPage.nextAfterVersion !== null)
39
+ throw new KeyingVerificationError("invalid_shape", "Completed public history returned additional entries");
40
+ lastPage = page;
41
+ }
42
+ if (lastPage?.historyPage.nextAfterVersion !== null)
43
+ throw new KeyingVerificationError("missing_dependency", "Public history transport did not complete");
44
+ }
45
+ return { progress, lastPage };
46
+ }
47
+ function finishPublicProgress(progress) {
48
+ if (!progress.completedHead)
49
+ throw new KeyingVerificationError("missing_dependency", "Completed public history is unavailable");
50
+ const finished = progress.verifier.finish(progress.completedHead);
51
+ if (!finished.ok)
52
+ throw finished.error;
53
+ return finished.value;
54
+ }
55
+ async function recoverAttempt(input, allowReuse = true, rejectedPrefix = null) {
56
+ const current = () => !input.signal?.aborted && input.stillCurrent();
57
+ assertProjectionVerificationCurrent(current);
58
+ const mayReplay = allowReuse && !input.offline;
59
+ const initial = await restorePublicPrincipalHistoryProgress(input, allowReuse);
60
+ let pages;
61
+ try {
62
+ pages = await readPublicPages(input, initial);
63
+ }
64
+ catch (error) {
65
+ if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))
66
+ throw error;
67
+ // A signed cached candidate need not belong to this requested chain. Only
68
+ // reused progress permits one replay; a fresh disconnected chain fails.
69
+ if (mayReplay && initial.afterVersion > 0)
70
+ return recover(input, false, initial.cachedPrefix);
71
+ throw error.verificationError;
72
+ }
73
+ const { progress, lastPage } = pages;
74
+ const history = finishPublicProgress(progress);
75
+ let proof;
76
+ try {
77
+ proof = await loadPrincipalHistoryReference({
78
+ execSql: input.execSql,
79
+ scopeId: progress.scopeId,
80
+ history,
81
+ version: input.source.head.version,
82
+ });
83
+ const selected = await verifyPrincipalPolicyHistoryReferences({
84
+ history,
85
+ references: [proof],
86
+ });
87
+ if (!selected.ok)
88
+ throw selected.error;
89
+ }
90
+ catch (error) {
91
+ if (error instanceof KeyingVerificationError && mayReplay)
92
+ return recover(input, false, initial.cachedPrefix);
93
+ throw error;
94
+ }
95
+ // Public prefixes memoize signatures; they are not admitted trust pins. A
96
+ // rejected projection may have left a valid but unrelated signed candidate.
97
+ // Rebuild the requested chain once online; callers still check durable pins
98
+ // and object authority before accepting it. Never reuse a mismatch offline.
99
+ if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {
100
+ if (mayReplay)
101
+ return recover(input, false, initial.cachedPrefix);
102
+ throw new KeyingVerificationError("object_mismatch", "Public history source differs from the verified prefix");
103
+ }
104
+ if (lastPage) {
105
+ const currentProof = {
106
+ ...proof,
107
+ entry: {
108
+ state: lastPage.currentState,
109
+ projection: lastPage.currentProjection,
110
+ grants: lastPage.currentGrants,
111
+ },
112
+ };
113
+ const checked = await verifyPrincipalPolicyHistoryReferences({
114
+ history,
115
+ references: [currentProof],
116
+ });
117
+ if (!checked.ok)
118
+ throw checked.error;
119
+ }
120
+ assertProjectionVerificationCurrent(current);
121
+ if (!input.offline)
122
+ await publishPublicPrincipalHistoryPrefix(input, progress, history, rejectedPrefix);
123
+ assertProjectionVerificationCurrent(current);
124
+ return { scopeId: progress.scopeId, history };
125
+ }
126
+ async function recover(input, allowReuse = true, rejectedPrefix = null) {
127
+ try {
128
+ return await recoverAttempt(input, allowReuse, rejectedPrefix);
129
+ }
130
+ catch (error) {
131
+ if (!(error instanceof PublicHistoryAuthorityUnavailableError))
132
+ throw error;
133
+ if (allowReuse && !input.offline)
134
+ return recoverAttempt(input, false, error.rejectedPrefix);
135
+ throw error.verificationError;
136
+ }
137
+ }
138
+ /** Private-key-backed public history recovery; never admits a current policy pin. */
139
+ export async function recoverPublicPrincipalHistory(options) {
140
+ if (!options.organizationId ||
141
+ (options.offline !== undefined && typeof options.offline !== "boolean") ||
142
+ (options.strictAdmins !== undefined &&
143
+ typeof options.strictAdmins !== "boolean") ||
144
+ (options.strictAdmins &&
145
+ (options.source.head.principalType !== "group" ||
146
+ options.loadExternalAuthority)))
147
+ throw new KeyingVerificationError("invalid_shape", "Invalid public history verification scope");
148
+ if (options.source.head.principalType === "organization" &&
149
+ options.source.head.principalId !== options.organizationId)
150
+ throw new KeyingVerificationError("object_mismatch", "Public organization history is outside its scope");
151
+ // Validate the caller's pinned head before any cache or transport access.
152
+ createPrincipalPolicyHistoryVerifier({
153
+ principalType: options.source.head.principalType,
154
+ principalId: options.source.head.principalId,
155
+ retainedReferences: [options.source.head],
156
+ });
157
+ const protection = ownPrincipalHistoryProtection(options.protection);
158
+ protection.context = serializeKeyingCanonicalJson([
159
+ "tearleads.sdk.public-principal-history.v2",
160
+ protection.context,
161
+ options.strictAdmins === true,
162
+ options.authorityGroupId ?? null,
163
+ ]);
164
+ const input = {
165
+ ...options,
166
+ source: structuredClone(options.source),
167
+ protection,
168
+ };
169
+ try {
170
+ return await recover(input, options.replay !== true);
171
+ }
172
+ finally {
173
+ protection.localKey.fill(0);
174
+ }
175
+ }
176
+ //# sourceMappingURL=recoverPublicPrincipalHistory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAEvB,4BAA4B,EAC5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,qCAAqC,GAEtC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAE3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCA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serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPageResponse,\n type PrincipalPolicySnapshotPageResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport type { PrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { PrincipalPolicyHistoryReadError } from \"./principalHistoryRecoveryTypes\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPageResponse,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPageResponse(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPageResponse | undefined;\n if (!input.offline) {\n for await (const result of input.apiClient.getProjectionPolicyHistoryPages(\n input.source,\n { afterVersion: progress.afterVersion, signal: input.signal },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (!progress.completedHead)\n progress = await appendPublicPrincipalHistoryPage(\n input,\n progress,\n page,\n );\n else if (\n page.previousStates.length ||\n page.historyPage.nextAfterVersion !== null\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n // A signed cached candidate need not belong to this requested chain. Only\n // reused progress permits one replay; a fresh disconnected chain fails.\n if (mayReplay && initial.afterVersion > 0)\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await loadPrincipalHistoryReference({\n execSql: input.execSql,\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n if (lastPage) {\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n }\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<RecoveredPublicPrincipalHistory> {\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix);\n } catch (error) {\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix);\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
@@ -53,12 +53,9 @@ async function recoverScopedPolicy(input, memo) {
53
53
  if (!isAdmins) {
54
54
  admins = (await read.admins(adminHead)).policy;
55
55
  }
56
- const loadExternalAuthority = async (entries) => {
56
+ const loadExternalAuthority = async (citations) => {
57
57
  const references = new Map();
58
- for (const { state } of entries) {
59
- const citation = state.externalAuthority;
60
- if (!citation)
61
- continue;
58
+ for (const citation of citations) {
62
59
  if (citation.principalId !== adminHead.principalId)
63
60
  throw new KeyingVerificationError("object_mismatch", "Group cites another organization's Admins authority");
64
61
  if (citation.version > adminHead.version)
@@ -1 +1 @@
1
- {"version":3,"file":"recoverScopedPrincipalPol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QAClC,WAAW,EAAE,IAAI,GAAG,EAAE;QACtB,MAAM,EAAE,IAAI,GAAG,EAAE;KAClB,CAAC;IACF,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,0CAA0C,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type PrincipalPolicyStateChainEntry,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n type RecoveredPrincipalPolicyHistory,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n type PrincipalRecoveryContext,\n PrincipalRecoveryDirectoryAdvanced,\n type RecoveredPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\nimport {\n createPrincipalRecoveryReader,\n type PrincipalRecoveryMemo,\n} from \"./principalRecoveryMemo\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\nexport interface RecoverScopedPrincipalPolicyHistoryOptions\n extends PrincipalRecoveryContext {\n readonly reference: ReferencedPrincipalHead;\n}\n\nexport interface RecoveredScopedPrincipalPolicyHistory\n extends RecoveredPrincipalPolicyHistory {\n /** Submit these with policy when atomically admitting its organization scope. */\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n}\n\nfunction groupHead(directory: RecoveredPolicyDirectory, principalId: string) {\n const head = directory.descriptor.groupHeads.find(\n (entry) => entry.principalId === principalId,\n );\n if (!head)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Group is absent from the signed organization directory\",\n );\n return head;\n}\n\nfunction authorityHead(state: ReferencedPrincipalHead) {\n return {\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\nfunction scopedGroupProtection(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n adminHead: ReferencedPrincipalHead,\n) {\n return {\n localKey: input.protection.localKey,\n context: serializeKeyingCanonicalJson([\n \"tearleads.sdk.principal-history.scoped-group.v1\",\n input.protection.context,\n input.organizationId,\n adminHead.principalId,\n ]),\n };\n}\n\nasync function recoverScopedPolicy(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n if (\n input.reference.principalType === \"organization\" &&\n input.reference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Requested organization policy is outside its scope\",\n );\n const read = createPrincipalRecoveryReader(input, memo);\n const directory = await read.directory(\n input.reference.principalType === \"organization\" ? [input.reference] : [],\n );\n if (input.reference.principalType === \"organization\")\n return {\n current: directory.current,\n policy: directory.policy,\n dependencies: [],\n };\n const expectedHead = groupHead(directory, input.reference.principalId);\n if (input.reference.version > expectedHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n const adminHead = groupHead(directory, directory.descriptor.adminGroupId);\n const isAdmins = expectedHead.principalId === adminHead.principalId;\n let admins: VerifiedPrincipalPolicyCurrent | null = null;\n if (!isAdmins) {\n admins = (await read.admins(adminHead)).policy;\n }\n const loadExternalAuthority = async (\n entries: readonly PrincipalPolicyStateChainEntry[],\n ): Promise<PrincipalPolicyExternalAuthority | undefined> => {\n const references = new Map<string, ReferencedPrincipalHead>();\n for (const { state } of entries) {\n const citation = state.externalAuthority;\n if (!citation) continue;\n if (citation.principalId !== adminHead.principalId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Group cites another organization's Admins authority\",\n );\n if (citation.version > adminHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n references.set(`${citation.version}:${citation.stateHash}`, citation);\n }\n if (!references.size) return undefined;\n const recovered = await read.admins(adminHead, [...references.values()]);\n return {\n currentHead: adminHead,\n states: recovered.policy.retainedHistory.map(({ state, projection }) => ({\n head: authorityHead(state),\n projection,\n })),\n };\n };\n const recovered = await recoverPrincipalPolicyHistory({\n ...input,\n expectedHead,\n retainedReferences: [input.reference],\n historyVerification: isAdmins ? \"direct-admins\" : \"standard\",\n ...(isAdmins\n ? {}\n : { protection: scopedGroupProtection(input, adminHead) }),\n ...(isAdmins ? {} : { loadExternalAuthority }),\n });\n return {\n ...recovered,\n dependencies: admins ? [directory.policy, admins] : [directory.policy],\n };\n}\n\n/** Recover signed directory and strict Admins dependencies without full histories. */\nasync function recoverScopedPrincipalPolicyHistoryInBatch(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (!options.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal recovery requires an organization scope\",\n );\n const input = {\n apiClient: options.apiClient,\n execSql: options.execSql,\n organizationId: options.organizationId,\n offline: options.offline,\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n signal: options.signal,\n stillCurrent: options.stillCurrent,\n reference: structuredClone(options.reference),\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n // Reject malformed exact citations before any discovery or disposable writes.\n createPrincipalPolicyHistoryVerifier({\n principalId: input.reference.principalId,\n principalType: input.reference.principalType,\n retainedReferences: [input.reference],\n });\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n const recovered = await recoverScopedPolicy(input, memo);\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n return recovered;\n } catch (error) {\n if (!(error instanceof PrincipalRecoveryDirectoryAdvanced)) throw error;\n memo?.directories.clear();\n memo?.admins.clear();\n if (input.offline)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested principal evidence is newer than the offline directory\",\n );\n }\n }\n throw new PrincipalHistoryRecoveryRaceError(\n \"Organization directory remains behind the requested policy evidence\",\n );\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n\nexport function recoverScopedPrincipalPolicyHistory(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n return recoverScopedPrincipalPolicyHistoryInBatch(options);\n}\n\n/** Internal runtime batch: shared results never outlive one caller's collection. */\nexport function createScopedPrincipalPolicyHistoryBatch(): typeof recoverScopedPrincipalPolicyHistory {\n const memo: PrincipalRecoveryMemo = {\n directories: new Map(),\n admins: new Map(),\n };\n return (options) => recoverScopedPrincipalPolicyHistoryInBatch(options, memo);\n}\n"]}
1
+ {"version":3,"file":"recoverScopedPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverScopedPrincipalPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAGvB,4BAA4B,GAE7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EACL,iCAAiC,GAElC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,kCAAkC,GAEnC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,6BAA6B,GAE9B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAahF,SAAS,SAAS,CAAC,SAAmC,EAAE,WAAmB;IACzE,MAAM,IAAI,GAAG,SAAS,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAC/C,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,KAAK,WAAW,CAC7C,CAAC;IACF,IAAI,CAAC,IAAI;Q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IAAI,KAAK,CAAC,OAAO;oBACf,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,kEAAkE,CACnE,CAAC;YACN,CAAC;QACH,CAAC;QACD,MAAM,IAAI,iCAAiC,CACzC,qEAAqE,CACtE,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC;AACH,CAAC;AAED,MAAM,UAAU,mCAAmC,CACjD,OAAmD;IAEnD,OAAO,0CAA0C,CAAC,OAAO,CAAC,CAAC;AAC7D,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,uCAAuC;IACrD,MAAM,IAAI,GAA0B;QAClC,WAAW,EAAE,IAAI,GAAG,EAAE;QACtB,MAAM,EAAE,IAAI,GAAG,EAAE;KAClB,CAAC;IACF,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,0CAA0C,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n type RecoveredPrincipalPolicyHistory,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n type PrincipalRecoveryContext,\n PrincipalRecoveryDirectoryAdvanced,\n type RecoveredPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\nimport {\n createPrincipalRecoveryReader,\n type PrincipalRecoveryMemo,\n} from \"./principalRecoveryMemo\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\nexport interface RecoverScopedPrincipalPolicyHistoryOptions\n extends PrincipalRecoveryContext {\n readonly reference: ReferencedPrincipalHead;\n}\n\nexport interface RecoveredScopedPrincipalPolicyHistory\n extends RecoveredPrincipalPolicyHistory {\n /** Submit these with policy when atomically admitting its organization scope. */\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n}\n\nfunction groupHead(directory: RecoveredPolicyDirectory, principalId: string) {\n const head = directory.descriptor.groupHeads.find(\n (entry) => entry.principalId === principalId,\n );\n if (!head)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Group is absent from the signed organization directory\",\n );\n return head;\n}\n\nfunction authorityHead(state: ReferencedPrincipalHead) {\n return {\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\nfunction scopedGroupProtection(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n adminHead: ReferencedPrincipalHead,\n) {\n return {\n localKey: input.protection.localKey,\n context: serializeKeyingCanonicalJson([\n \"tearleads.sdk.principal-history.scoped-group.v1\",\n input.protection.context,\n input.organizationId,\n adminHead.principalId,\n ]),\n };\n}\n\nasync function recoverScopedPolicy(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n if (\n input.reference.principalType === \"organization\" &&\n input.reference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Requested organization policy is outside its scope\",\n );\n const read = createPrincipalRecoveryReader(input, memo);\n const directory = await read.directory(\n input.reference.principalType === \"organization\" ? [input.reference] : [],\n );\n if (input.reference.principalType === \"organization\")\n return {\n current: directory.current,\n policy: directory.policy,\n dependencies: [],\n };\n const expectedHead = groupHead(directory, input.reference.principalId);\n if (input.reference.version > expectedHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n const adminHead = groupHead(directory, directory.descriptor.adminGroupId);\n const isAdmins = expectedHead.principalId === adminHead.principalId;\n let admins: VerifiedPrincipalPolicyCurrent | null = null;\n if (!isAdmins) {\n admins = (await read.admins(adminHead)).policy;\n }\n const loadExternalAuthority = async (\n citations: readonly ReferencedPrincipalHead[],\n ): Promise<PrincipalPolicyExternalAuthority | undefined> => {\n const references = new Map<string, ReferencedPrincipalHead>();\n for (const citation of citations) {\n if (citation.principalId !== adminHead.principalId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Group cites another organization's Admins authority\",\n );\n if (citation.version > adminHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n references.set(`${citation.version}:${citation.stateHash}`, citation);\n }\n if (!references.size) return undefined;\n const recovered = await read.admins(adminHead, [...references.values()]);\n return {\n currentHead: adminHead,\n states: recovered.policy.retainedHistory.map(({ state, projection }) => ({\n head: authorityHead(state),\n projection,\n })),\n };\n };\n const recovered = await recoverPrincipalPolicyHistory({\n ...input,\n expectedHead,\n retainedReferences: [input.reference],\n historyVerification: isAdmins ? \"direct-admins\" : \"standard\",\n ...(isAdmins\n ? {}\n : { protection: scopedGroupProtection(input, adminHead) }),\n ...(isAdmins ? {} : { loadExternalAuthority }),\n });\n return {\n ...recovered,\n dependencies: admins ? [directory.policy, admins] : [directory.policy],\n };\n}\n\n/** Recover signed directory and strict Admins dependencies without full histories. */\nasync function recoverScopedPrincipalPolicyHistoryInBatch(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (!options.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal recovery requires an organization scope\",\n );\n const input = {\n apiClient: options.apiClient,\n execSql: options.execSql,\n organizationId: options.organizationId,\n offline: options.offline,\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n signal: options.signal,\n stillCurrent: options.stillCurrent,\n reference: structuredClone(options.reference),\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n // Reject malformed exact citations before any discovery or disposable writes.\n createPrincipalPolicyHistoryVerifier({\n principalId: input.reference.principalId,\n principalType: input.reference.principalType,\n retainedReferences: [input.reference],\n });\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n const recovered = await recoverScopedPolicy(input, memo);\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n return recovered;\n } catch (error) {\n if (!(error instanceof PrincipalRecoveryDirectoryAdvanced)) throw error;\n memo?.directories.clear();\n memo?.admins.clear();\n if (input.offline)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested principal evidence is newer than the offline directory\",\n );\n }\n }\n throw new PrincipalHistoryRecoveryRaceError(\n \"Organization directory remains behind the requested policy evidence\",\n );\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n\nexport function recoverScopedPrincipalPolicyHistory(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n return recoverScopedPrincipalPolicyHistoryInBatch(options);\n}\n\n/** Internal runtime batch: shared results never outlive one caller's collection. */\nexport function createScopedPrincipalPolicyHistoryBatch(): typeof recoverScopedPrincipalPolicyHistory {\n const memo: PrincipalRecoveryMemo = {\n directories: new Map(),\n admins: new Map(),\n };\n return (options) => recoverScopedPrincipalPolicyHistoryInBatch(options, memo);\n}\n"]}
@@ -2,13 +2,14 @@ import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
2
  import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
3
3
  import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
4
4
  import { assertProjectionVerificationCurrent, } from "../../data/keyingProjectionVerification/types.js";
5
+ import { readPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
5
6
  import { PrincipalHistoryRecoveryRaceError, PrincipalPolicyHistoryReadError, } from "./principalHistoryRecoveryTypes.js";
6
7
  import { recoverWithPrincipalOutageFallback } from "./principalRecoveryOutage.js";
7
8
  import { queuePrincipalRecovery } from "./principalRecoveryQueue.js";
8
9
  import { createScopedPrincipalPolicyHistoryBatch, recoverScopedPrincipalPolicyHistory, } from "./recoverScopedPrincipalPolicyHistory.js";
9
10
  /** Keep the private recovery key inside its runtime lease throughout verification. */
10
11
  export function createRuntimePrincipalPolicyResolver(runtime) {
11
- const lease = runtime.withPrincipalHistoryProtection;
12
+ const lease = readPrincipalHistoryProtection(runtime);
12
13
  const readPages = runtime.apiClient.getPrincipalPolicyPages?.bind(runtime.apiClient);
13
14
  if (!lease || !readPages)
14
15
  return undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,GAEpC,MAAM,+CAA+C,CAAC;AAKvD,OAAO,EACL,iCAAiC,EACjC,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EACL,uCAAuC,EACvC,mCAAmC,GACpC,MAAM,uCAAuC,CAAC;AAa/C,sFAAsF;AACtF,MAAM,UAAU,oCAAoC,CAClD,OAAuC;IAEvC,MAAM,KAAK,GAAG,OAAO,CAAC,8BAA8B,CAAC;IACrD,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC,uBAAuB,EAAE,IAAI,CAC/D,OAAO,CAAC,SAAS,CAClB,CAAC;IACF,IAAI,CAAC,KAAK,IAAI,CAAC,SAA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;gBACP,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,UAAU;gBACV,SAAS,EAAE,KAAK,CAAC,SAAS;gBAC1B,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;gBAC9D,YAAY;aACb,CAAC;YACF,MAAM,MAAM,GAAG,MAAM,kCAAkC,CACrD,UAAU,CAAC,KAAK,CAAC,aAAa,CAAC,EAC/B,OAAO,CACR,CAAC;YACF,OAAO;gBACL,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,YAAY;aACb,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,IACE,KAAK,YAAY,+BAA+B;gBAChD,KAAK,YAAY,iCAAiC;gBAClD,CAAC,KAAK,YAAY,uBAAuB;oBACvC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;gBAEtC,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACL,CACF,CAAC;AACN,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./principalHistoryRecoveryTypes\";\nimport { recoverWithPrincipalOutageFallback } from \"./principalRecoveryOutage\";\nimport { queuePrincipalRecovery } from \"./principalRecoveryQueue\";\nimport {\n createScopedPrincipalPolicyHistoryBatch,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<Pick<ApiClient, \"getPrincipalPolicyPages\">>;\n readonly infra: { readonly execSql: ExecSql };\n readonly state?: { readonly online: boolean } | undefined;\n readonly util: { readonly reportSecurityIncident: SecurityIncidentReporter };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\n/** Keep the private recovery key inside its runtime lease throughout verification. */\nexport function createRuntimePrincipalPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n): ReferencedPrincipalPolicyWarmer[\"resolveReference\"] {\n const lease = runtime.withPrincipalHistoryProtection;\n const readPages = runtime.apiClient.getPrincipalPolicyPages?.bind(\n runtime.apiClient,\n );\n if (!lease || !readPages) return undefined;\n const batches = new WeakMap<\n object,\n typeof recoverScopedPrincipalPolicyHistory\n >();\n const recoverFor = (batch: object | undefined) => {\n if (!batch) return recoverScopedPrincipalPolicyHistory;\n let recover = batches.get(batch);\n if (!recover) {\n recover = createScopedPrincipalPolicyHistoryBatch();\n batches.set(batch, recover);\n }\n return recover;\n };\n return (input) =>\n queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.reference.principalId,\n objectKind: \"principal\",\n operation: \"principal.policy.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n const offline = runtime.state?.online === false;\n try {\n const options = {\n apiClient: { getPrincipalPolicyPages: readPages },\n execSql: runtime.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n reference: input.reference,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const result = await recoverWithPrincipalOutageFallback(\n recoverFor(input.recoveryBatch),\n options,\n );\n return {\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n stillCurrent,\n };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n error instanceof PrincipalHistoryRecoveryRaceError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,GAEpC,MAAM,+CAA+C,CAAC;AAEvD,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAI/F,OAAO,EACL,iCAAiC,EACjC,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EACL,uCAAuC,EACvC,mCAAmC,GACpC,MAAM,uCAAuC,CAAC;AAkB/C,sFAAsF;AACtF,MAAM,UAAU,oCAAoC,CAClD,OAAuC;IAEvC,MAAM,KAAK,GAAG,8BAA8B,CAAC,OAAO,CAAC,CAAC;IACtD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AC;YACH,MAAM,OAAO,GAAG;gBACd,SAAS,EAAE,EAAE,uBAAuB,EAAE,SAAS,EAAE;gBACjD,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;gBAC9B,OAAO;gBACP,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,UAAU;gBACV,SAAS,EAAE,KAAK,CAAC,SAAS;gBAC1B,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;gBAC9D,YAAY;aACb,CAAC;YACF,MAAM,MAAM,GAAG,MAAM,kCAAkC,CACrD,UAAU,CAAC,KAAK,CAAC,aAAa,CAAC,EAC/B,OAAO,CACR,CAAC;YACF,OAAO;gBACL,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,YAAY;aACb,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,IACE,KAAK,YAAY,+BAA+B;gBAChD,KAAK,YAAY,iCAAiC;gBAClD,CAAC,KAAK,YAAY,uBAAuB;oBACvC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;gBAEtC,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACL,CACF,CAAC;AACN,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./principalHistoryRecoveryTypes\";\nimport { recoverWithPrincipalOutageFallback } from \"./principalRecoveryOutage\";\nimport { queuePrincipalRecovery } from \"./principalRecoveryQueue\";\nimport {\n createScopedPrincipalPolicyHistoryBatch,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<\n Pick<\n ApiClient,\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >\n >;\n readonly infra: { readonly execSql: ExecSql };\n readonly state?: { readonly online: boolean } | undefined;\n readonly util: { readonly reportSecurityIncident: SecurityIncidentReporter };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\n/** Keep the private recovery key inside its runtime lease throughout verification. */\nexport function createRuntimePrincipalPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n): ReferencedPrincipalPolicyWarmer[\"resolveReference\"] {\n const lease = readPrincipalHistoryProtection(runtime);\n const readPages = runtime.apiClient.getPrincipalPolicyPages?.bind(\n runtime.apiClient,\n );\n if (!lease || !readPages) return undefined;\n const batches = new WeakMap<\n object,\n typeof recoverScopedPrincipalPolicyHistory\n >();\n const recoverFor = (batch: object | undefined) => {\n if (!batch) return recoverScopedPrincipalPolicyHistory;\n let recover = batches.get(batch);\n if (!recover) {\n recover = createScopedPrincipalPolicyHistoryBatch();\n batches.set(batch, recover);\n }\n return recover;\n };\n return (input) =>\n queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.reference.principalId,\n objectKind: \"principal\",\n operation: \"principal.policy.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n const offline = runtime.state?.online === false;\n try {\n const options = {\n apiClient: { getPrincipalPolicyPages: readPages },\n execSql: runtime.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n reference: input.reference,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const result = await recoverWithPrincipalOutageFallback(\n recoverFor(input.recoveryBatch),\n options,\n );\n return {\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n stillCurrent,\n };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n error instanceof PrincipalHistoryRecoveryRaceError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n"]}