@tearleads/client-sdk 0.1.11 → 0.1.14

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 (144) hide show
  1. package/README.md +50 -9
  2. package/client/Tearleads.d.ts +4 -0
  3. package/client/Tearleads.js +5 -0
  4. package/client/Tearleads.js.map +1 -1
  5. package/client/index.d.ts +1 -0
  6. package/client/index.js.map +1 -1
  7. package/client/principalHistoryProtection.d.ts +19 -0
  8. package/client/principalHistoryProtection.js +76 -0
  9. package/client/principalHistoryProtection.js.map +1 -0
  10. package/client/workflowRuntime.d.ts +5 -0
  11. package/client/workflowRuntime.js +34 -5
  12. package/client/workflowRuntime.js.map +1 -1
  13. package/data/containers/shared/authorAccess.d.ts +2 -2
  14. package/data/containers/shared/authorAccess.js.map +1 -1
  15. package/data/containers/shared/heldContainerHeads.js.map +1 -1
  16. package/data/containers/shared/principalPolicies.js.map +1 -1
  17. package/data/containers/shared/types.d.ts +3 -2
  18. package/data/containers/shared/types.js.map +1 -1
  19. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
  20. package/data/keyingProjectionVerification/checkpointContext.d.ts +4 -3
  21. package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
  22. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  23. package/data/keyingProjectionVerification/containerPathVerification.js.map +1 -1
  24. package/data/keyingProjectionVerification/containerProjectionVerification.d.ts +4 -3
  25. package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
  26. package/data/keyingProjectionVerification/documentManifestPolicies.js.map +1 -1
  27. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  28. package/data/keyingProjectionVerification/documentProjectionVerification.d.ts +3 -2
  29. package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
  30. package/data/keyingProjectionVerification/organizationFounderBinding.js +9 -4
  31. package/data/keyingProjectionVerification/organizationFounderBinding.js.map +1 -1
  32. package/data/keyingProjectionVerification/principalPolicyCache.js +3 -4
  33. package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
  34. package/data/keyingProjectionVerification/principalPolicyVerification.js +12 -2
  35. package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
  36. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +1 -1
  37. package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js +70 -0
  38. package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js.map +1 -0
  39. package/data/keyingProjectionVerification/types.d.ts +17 -2
  40. package/data/keyingProjectionVerification/types.js +12 -0
  41. package/data/keyingProjectionVerification/types.js.map +1 -1
  42. package/data/persistence/organizationFounderPersistence.js +3 -2
  43. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  44. package/data/persistence/principalHistoryEvidencePersistence.js +91 -0
  45. package/data/persistence/principalHistoryEvidencePersistence.js.map +1 -0
  46. package/data/persistence/principalHistoryPrefixPersistence.js +52 -0
  47. package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -0
  48. package/data/persistence/principalHistoryStagePersistence.js +9 -2
  49. package/data/persistence/principalHistoryStagePersistence.js.map +1 -1
  50. package/data/persistence/principalKeyEnvelopeCandidates.js +67 -0
  51. package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -0
  52. package/data/principals/principalHistoryPrefixProtection.js +29 -0
  53. package/data/principals/principalHistoryPrefixProtection.js.map +1 -0
  54. package/data/principals/principalHistoryProtection.d.ts +10 -0
  55. package/data/principals/principalHistoryProtection.js +14 -0
  56. package/data/principals/principalHistoryProtection.js.map +1 -0
  57. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  58. package/data/principals/principalPolicyCrypto.js +11 -21
  59. package/data/principals/principalPolicyCrypto.js.map +1 -1
  60. package/data/principals/principalPolicyEvidence.d.ts +4 -0
  61. package/data/principals/principalPolicyEvidence.js +12 -0
  62. package/data/principals/principalPolicyEvidence.js.map +1 -0
  63. package/data/sqlite/principalHistoryEvidenceSchema.js +46 -0
  64. package/data/sqlite/principalHistoryEvidenceSchema.js.map +1 -0
  65. package/data/sqlite/principalKeyFingerprintJson.js +9 -0
  66. package/data/sqlite/principalKeyFingerprintJson.js.map +1 -0
  67. package/data/sqlite/principalPolicySchema.js +4 -0
  68. package/data/sqlite/principalPolicySchema.js.map +1 -1
  69. package/data/sqlite/schema.d.ts +304 -0
  70. package/data/sqlite/schema.js +5 -0
  71. package/data/sqlite/schema.js.map +1 -1
  72. package/data/sqlite/sqlTableSchema.js +1 -1
  73. package/data/sqlite/sqlTableSchema.js.map +1 -1
  74. package/index.d.ts +3 -3
  75. package/index.js +1 -1
  76. package/index.js.map +1 -1
  77. package/internal/api-client/principalPolicyPages.d.ts +2 -0
  78. package/internal/api-client/principalPolicyPages.js +11 -2
  79. package/internal/api-client/principalPolicyPages.js.map +1 -1
  80. package/internal/crypto/index.d.ts +1 -1
  81. package/internal/crypto/index.js +1 -1
  82. package/internal/crypto/index.js.map +1 -1
  83. package/internal/crypto/keying/index.d.ts +1 -1
  84. package/internal/crypto/keying/index.js +1 -1
  85. package/internal/crypto/keying/index.js.map +1 -1
  86. package/internal/crypto/keying/principalPolicyHistoryIndex.d.ts +6 -2
  87. package/internal/crypto/keying/principalPolicyHistoryIndex.js +11 -5
  88. package/internal/crypto/keying/principalPolicyHistoryIndex.js.map +1 -1
  89. package/internal/crypto/keying/principalPolicyHistoryReferences.d.ts +2 -0
  90. package/internal/crypto/keying/principalPolicyHistoryReferences.js +19 -2
  91. package/internal/crypto/keying/principalPolicyHistoryReferences.js.map +1 -1
  92. package/package.json +4 -1
  93. package/sqlite/sqlite3-licenses.md +38 -0
  94. package/sqlite/sqlite3.wasm +0 -0
  95. package/sqlite/worker.js +4 -0
  96. package/workflows/containers/child/create.js.map +1 -1
  97. package/workflows/containers/child/move.js.map +1 -1
  98. package/workflows/containers/child/moveWraps.js.map +1 -1
  99. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  100. package/workflows/containers/child/recitePlan.js.map +1 -1
  101. package/workflows/containers/child/rekey.d.ts +3 -2
  102. package/workflows/containers/child/rekey.js.map +1 -1
  103. package/workflows/containers/child/revoke.d.ts +2 -2
  104. package/workflows/containers/child/revoke.js.map +1 -1
  105. package/workflows/containers/child/rotationPrincipalPolicies.js.map +1 -1
  106. package/workflows/containers/child/rotationWraps.js.map +1 -1
  107. package/workflows/containers/child/sharePlanCore.d.ts +11 -10
  108. package/workflows/containers/child/sharePlanCore.js.map +1 -1
  109. package/workflows/documents/linkSetAuthority.js.map +1 -1
  110. package/workflows/principals/index.d.ts +1 -0
  111. package/workflows/principals/index.js +1 -0
  112. package/workflows/principals/index.js.map +1 -1
  113. package/workflows/principals/principalHistoryRecoveryPrefix.js +65 -0
  114. package/workflows/principals/principalHistoryRecoveryPrefix.js.map +1 -0
  115. package/workflows/principals/principalHistoryRecoveryReferences.js +60 -0
  116. package/workflows/principals/principalHistoryRecoveryReferences.js.map +1 -0
  117. package/workflows/principals/principalHistoryRecoveryStage.js +38 -2
  118. package/workflows/principals/principalHistoryRecoveryStage.js.map +1 -1
  119. package/workflows/principals/principalHistoryRecoveryTypes.d.ts +9 -1
  120. package/workflows/principals/principalHistoryRecoveryTypes.js +7 -0
  121. package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
  122. package/workflows/principals/principalHistoryRecoveryVerification.js +24 -0
  123. package/workflows/principals/principalHistoryRecoveryVerification.js.map +1 -0
  124. package/workflows/principals/principalRecoveryDirectory.d.ts +10 -0
  125. package/workflows/principals/principalRecoveryDirectory.js +107 -0
  126. package/workflows/principals/principalRecoveryDirectory.js.map +1 -0
  127. package/workflows/principals/principalRecoveryMemo.js +46 -0
  128. package/workflows/principals/principalRecoveryMemo.js.map +1 -0
  129. package/workflows/principals/principalRecoveryOutage.js +40 -0
  130. package/workflows/principals/principalRecoveryOutage.js.map +1 -0
  131. package/workflows/principals/principalRecoveryQueue.js +22 -0
  132. package/workflows/principals/principalRecoveryQueue.js.map +1 -0
  133. package/workflows/principals/recoverPrincipalPolicyHistory.d.ts +1 -0
  134. package/workflows/principals/recoverPrincipalPolicyHistory.js +108 -36
  135. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
  136. package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +13 -0
  137. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +150 -0
  138. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -0
  139. package/workflows/principals/runtimePolicyRecovery.js +65 -0
  140. package/workflows/principals/runtimePolicyRecovery.js.map +1 -0
  141. package/workflows/principals/runtimePolicyWarmer.js +5 -1
  142. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  143. package/workflows/sync/remoteResetPrincipalScope.js +10 -0
  144. package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"revoke.js","sourceRoot":"","sources":["revoke.ts"],"names":[],"mappings":"AAYA,OAAO,EACL,8BAA8B,EAC9B,wCAAwC,EACxC,mCAAmC,GACpC,MAAM,mBAAmB,CAAC;AAU3B,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,EACL,4BAA4B,EAC5B,0BAA0B,GAC3B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAOpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,EAIL,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AAGpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,mCAAmC,EACnC,uBAAuB,GACxB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,yCAAyC,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAEL,6B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AAC,cAAc;aACnE,CAAC;YACF,MAAM,EAAE,qBAAqB,EAAE,GAAG,KAAK,CAAC,SAAS,CAAC;YAClD,OAAO,uBAAuB,CAAC;gBAC7B,KAAK,EAAE,GAAG,EAAE,CACV,KAAK,CAAC,SAAS,CAAC,eAAe,CAAC,KAAK,CAAC,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC;gBACtE,MAAM,EAAE,qBAAqB;oBAC3B,CAAC,CAAC,GAAG,EAAE,CACH,qBAAqB,CAAC,IAAI,CACxB,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,WAAW,EACjB,OAAO,EACP,EAAE,GAAG,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,CACpC;oBACL,CAAC,CAAC,SAAS;aACd,CAAC,CAAC;QACL,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerKekKeyring,\n ContainerKekPredecessorBridge,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerRevokeAccessEventBody,\n ContainerUserRecipientKey,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport {\n computeContainerKekKeyringHash,\n computeContainerKekPredecessorBridgeHash,\n deriveContainerKekWrappingPublicKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerKekResponse,\n ContainerRotationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertContainerAuthorAccess } from \"../../../data/containers/shared/authorAccess\";\nimport {\n buildContainerCreateKeyEpoch,\n signContainerMutationEvent,\n} from \"../../../data/containers/shared/events\";\nimport {\n asContainerManifestBundle,\n uniqueSortedManifestHashes,\n} from \"../../../data/containers/shared/projection\";\nimport type {\n ContainerMutationAuthor,\n ContainerRevokeApi,\n ContainerRevokePlan,\n MaterializedContainerRevokePlan,\n} from \"../../../data/containers/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keyingCanonicalJson\";\nimport {\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { SecurityIncidentReporter } from \"../../../data/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { buildContainerRotationArtifacts } from \"./moveRotation\";\nimport {\n containerMutationRequestCore,\n previousPathRequestFields,\n readCanonicalRecordOrNull,\n} from \"./mutationRequestCore\";\nimport {\n submitAcknowledgedContainerMutation,\n submitContainerRotation,\n} from \"./mutationSubmit\";\nimport { containerWriterProjectionFromRotationPlan } from \"./rekeyProjection\";\nimport {\n type ContainerRevokeSubject,\n deriveContainerRevokeManifest,\n} from \"./revokeManifest\";\nimport { resolveRotationContext } from \"./rotationContext\";\nimport { collectContainerRevokePrincipalPolicies } from \"./rotationPrincipalPolicies\";\nimport { buildContainerRotationWraps } from \"./rotationWraps\";\n\nfunction buildContainerRevokeRequest(input: {\n body: ContainerRevokeAccessEventBody;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n parentKek: ContainerKekResponse | null;\n predecessorBridge: ContainerKekPredecessorBridge;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly VerifiedPrincipalPolicy[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n ...containerMutationRequestCore(\"revoke\", input),\n ...previousPathRequestFields(\n input.previousManifest,\n input.previousProjection,\n ),\n predecessorBridge: readCanonicalRecord(\n input.predecessorBridge,\n \"Container revoke predecessor bridge\",\n ),\n keyring: readCanonicalRecord(input.keyring, \"Container revoke keyring\"),\n parentKekState: readCanonicalRecordOrNull(\n input.parentKek,\n \"Container revoke parent KEK state\",\n ),\n };\n}\n\nfunction buildContainerRevokePlanResult(input: {\n body: ContainerRevokeAccessEventBody;\n containerId: string;\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n parentKek: ContainerKekResponse | null;\n predecessorBridge: ContainerKekPredecessorBridge;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly VerifiedPrincipalPolicy[];\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}): MaterializedContainerRevokePlan {\n const plan: ContainerRevokePlan = {\n body: input.body,\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n event: input.event,\n eventHash: input.eventHash,\n keyEpoch: input.keyEpoch,\n keyring: input.keyring,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n previousManifest: input.previousManifest,\n request: buildContainerRevokeRequest({\n body: input.body,\n event: input.event,\n keyEpoch: input.keyEpoch,\n keyring: input.keyring,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n parentKek: input.parentKek,\n predecessorBridge: input.predecessorBridge,\n previousManifest: input.previousManifest,\n previousProjection: input.previousProjection,\n principalPolicies: input.principalPolicies,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n }),\n state: input.state,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n };\n\n return { containerKey: input.containerKey, plan };\n}\n\n// biome-ignore lint/complexity/noExcessiveLinesPerFunction: Revoke planning has to keep the manifest, KEK, wraps, and signed event in one auditable transition.\nexport async function buildMaterializedContainerRevokePlan(input: {\n author: ContainerMutationAuthor;\n eventId?: string | undefined;\n execSql: ExecSql;\n /** Keys a batch minted above this container and has yet to commit. */\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n /** False for a projection re-rooted on rotations not yet acknowledged. */\n persistVerificationCheckpoints?: boolean | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n /** Verified policies the path may cite before they are stored locally. */\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n replacementPrincipalPolicy?: VerifiedPrincipalPolicy | undefined;\n revokedSubject: ContainerRevokeSubject;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<MaterializedContainerRevokePlan> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container revoke\",\n );\n const {\n parentKek,\n parentPublicKey,\n predecessorContainerKey,\n previousState,\n target,\n } = await resolveRotationContext(input, \"revoke\");\n const principalPolicies = await collectContainerRevokePrincipalPolicies({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n previousProjection: input.previousProjection,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n assertContainerAuthorAccess({\n author: input.author,\n projection: input.previousProjection,\n principalPolicies,\n minimumAccess: \"admin\",\n });\n const nextContainerKeyEpoch = target.kek.containerKeyEpoch + 1;\n const { containerKey, containerKeyEpochId, keyring, predecessorBridge } =\n await buildContainerRotationArtifacts({\n containerId: previousState.containerId,\n currentKek: target.kek,\n currentKeyMaterial: predecessorContainerKey,\n keyEpoch: nextContainerKeyEpoch,\n signedEpochIds: target.signedEpochIds,\n });\n const body: ContainerRevokeAccessEventBody = {\n eventType: \"container.revoke\",\n parentManifestHash:\n input.previousProjection.path.at(-2)?.manifestHash ?? null,\n containerKeyPublicKey: await deriveContainerKekWrappingPublicKey({\n containerId: previousState.containerId,\n keyMaterial: containerKey,\n }),\n containerKeyEpochId,\n keyringHash: await computeContainerKekKeyringHash(keyring),\n predecessorBridgeHash:\n await computeContainerKekPredecessorBridgeHash(predecessorBridge),\n subjectId: input.revokedSubject.subjectId,\n subjectType: input.revokedSubject.subjectType,\n };\n const { event, eventHash } = await signContainerMutationEvent({\n author: input.author,\n body,\n containerId: previousState.containerId,\n dependencyManifestHashes: uniqueSortedManifestHashes(\n input.previousProjection.path,\n ),\n eventId: input.eventId ?? crypto.randomUUID(),\n previousManifestHash: target.manifest.manifestHash,\n signedAt: input.signedAt ?? new Date().toISOString(),\n });\n const { manifest, manifestHash, state } = await deriveContainerRevokeManifest(\n {\n containerKeyPublicKey: body.containerKeyPublicKey,\n parentManifestHash: body.parentManifestHash,\n containerKeyEpochId,\n eventHash,\n previousManifest: target.manifest,\n revokedSubject: input.revokedSubject,\n },\n );\n const keyEpoch = buildContainerCreateKeyEpoch({\n containerId: previousState.containerId,\n containerKeyEpochId,\n eventHash,\n keyEpoch: nextContainerKeyEpoch,\n manifestHash,\n parentContainerKeyEpochId: parentKek?.containerKeyEpochId ?? null,\n });\n\n const replacementPrincipalPolicy = input.replacementPrincipalPolicy;\n if (\n replacementPrincipalPolicy &&\n (replacementPrincipalPolicy.principalType !==\n input.revokedSubject.subjectType ||\n replacementPrincipalPolicy.principalId !== input.revokedSubject.subjectId)\n ) {\n throw new Error(\"Container revoke replacement principal does not match\");\n }\n const currentPrincipalPolicies = replacementPrincipalPolicy\n ? principalPolicies.filter(\n (policy) =>\n policy.principalType !== replacementPrincipalPolicy.principalType ||\n policy.principalId !== replacementPrincipalPolicy.principalId,\n )\n : principalPolicies;\n const { userRecipientKeys, wraps } = await buildContainerRotationWraps({\n containerKey,\n containerKeyEpochId,\n manifestHash,\n operationLabel: \"Container revoke\",\n parentKek,\n parentPublicKey,\n principalPolicies: currentPrincipalPolicies,\n resolveUserKey: resolveProjectionUserKey,\n state,\n });\n\n return buildContainerRevokePlanResult({\n body,\n containerId: previousState.containerId,\n containerKey,\n containerKeyEpochId,\n event,\n eventHash,\n keyEpoch,\n keyring,\n manifest,\n manifestHash,\n parentKek,\n predecessorBridge,\n previousManifest: asContainerManifestBundle(target.manifest),\n previousProjection: input.previousProjection,\n principalPolicies: currentPrincipalPolicies,\n state,\n userRecipientKeys,\n wraps,\n });\n}\n\nexport async function revokeRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n apiClient: ContainerRevokeApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n revokedSubject: ContainerRevokeSubject;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerRevokePlan;\n response: ContainerRotationResponse;\n} | null> {\n const previousProjection = await input.apiClient.getContainerWriterProjection(\n input.containerId,\n );\n if (!previousProjection) {\n return null;\n }\n\n const materializedPlan = await buildMaterializedContainerRevokePlan({\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n revokedSubject: input.revokedSubject,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n carriedRekeys: {\n planning: {\n apiClient: input.apiClient,\n author: input.author,\n execSql: input.execSql,\n knownContainerKeks: new Map([\n [\n materializedPlan.plan.containerKeyEpochId,\n materializedPlan.containerKey,\n ],\n ]),\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n },\n rotated: () =>\n containerWriterProjectionFromRotationPlan({\n plan: materializedPlan.plan,\n previousProjection,\n }),\n },\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: (carried) => {\n const request = carried.length\n ? { ...materializedPlan.plan.request, containerRekeys: [...carried] }\n : materializedPlan.plan.request;\n const options = {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n };\n const { revokeContainerResult } = input.apiClient;\n return submitContainerRotation({\n plain: () =>\n input.apiClient.revokeContainer(input.containerId, request, options),\n result: revokeContainerResult\n ? () =>\n revokeContainerResult.call(\n input.apiClient,\n input.containerId,\n request,\n { ...options, reportErrors: false },\n )\n : undefined,\n });\n },\n });\n}\n"]}
1
+ {"version":3,"file":"revoke.js","sourceRoot":"","sources":["revoke.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,8BAA8B,EAC9B,wCAAwC,EACxC,mCAAmC,GACpC,MAAM,mBAAmB,CAAC;AAU3B,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,EACL,4BAA4B,EAC5B,0BAA0B,GAC3B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAOpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,EAIL,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AAIpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,mCAAmC,EACnC,uBAAuB,GACxB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,yCAAyC,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAEL,6BAA6B,GAC9B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,sBA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AG,KAAK,CAAC,SAAS,CAAC;YAClD,OAAO,uBAAuB,CAAC;gBAC7B,KAAK,EAAE,GAAG,EAAE,CACV,KAAK,CAAC,SAAS,CAAC,eAAe,CAAC,KAAK,CAAC,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC;gBACtE,MAAM,EAAE,qBAAqB;oBAC3B,CAAC,CAAC,GAAG,EAAE,CACH,qBAAqB,CAAC,IAAI,CACxB,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,WAAW,EACjB,OAAO,EACP,EAAE,GAAG,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,CACpC;oBACL,CAAC,CAAC,SAAS;aACd,CAAC,CAAC;QACL,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerKekKeyring,\n ContainerKekPredecessorBridge,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerRevokeAccessEventBody,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport {\n computeContainerKekKeyringHash,\n computeContainerKekPredecessorBridgeHash,\n deriveContainerKekWrappingPublicKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerKekResponse,\n ContainerRotationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertContainerAuthorAccess } from \"../../../data/containers/shared/authorAccess\";\nimport {\n buildContainerCreateKeyEpoch,\n signContainerMutationEvent,\n} from \"../../../data/containers/shared/events\";\nimport {\n asContainerManifestBundle,\n uniqueSortedManifestHashes,\n} from \"../../../data/containers/shared/projection\";\nimport type {\n ContainerMutationAuthor,\n ContainerRevokeApi,\n ContainerRevokePlan,\n MaterializedContainerRevokePlan,\n} from \"../../../data/containers/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keyingCanonicalJson\";\nimport {\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principals/principalPolicyEvidence\";\nimport type { SecurityIncidentReporter } from \"../../../data/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { buildContainerRotationArtifacts } from \"./moveRotation\";\nimport {\n containerMutationRequestCore,\n previousPathRequestFields,\n readCanonicalRecordOrNull,\n} from \"./mutationRequestCore\";\nimport {\n submitAcknowledgedContainerMutation,\n submitContainerRotation,\n} from \"./mutationSubmit\";\nimport { containerWriterProjectionFromRotationPlan } from \"./rekeyProjection\";\nimport {\n type ContainerRevokeSubject,\n deriveContainerRevokeManifest,\n} from \"./revokeManifest\";\nimport { resolveRotationContext } from \"./rotationContext\";\nimport { collectContainerRevokePrincipalPolicies } from \"./rotationPrincipalPolicies\";\nimport { buildContainerRotationWraps } from \"./rotationWraps\";\n\nfunction buildContainerRevokeRequest(input: {\n body: ContainerRevokeAccessEventBody;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n parentKek: ContainerKekResponse | null;\n predecessorBridge: ContainerKekPredecessorBridge;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n ...containerMutationRequestCore(\"revoke\", input),\n ...previousPathRequestFields(\n input.previousManifest,\n input.previousProjection,\n ),\n predecessorBridge: readCanonicalRecord(\n input.predecessorBridge,\n \"Container revoke predecessor bridge\",\n ),\n keyring: readCanonicalRecord(input.keyring, \"Container revoke keyring\"),\n parentKekState: readCanonicalRecordOrNull(\n input.parentKek,\n \"Container revoke parent KEK state\",\n ),\n };\n}\n\nfunction buildContainerRevokePlanResult(input: {\n body: ContainerRevokeAccessEventBody;\n containerId: string;\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n parentKek: ContainerKekResponse | null;\n predecessorBridge: ContainerKekPredecessorBridge;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}): MaterializedContainerRevokePlan {\n const plan: ContainerRevokePlan = {\n body: input.body,\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n event: input.event,\n eventHash: input.eventHash,\n keyEpoch: input.keyEpoch,\n keyring: input.keyring,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n previousManifest: input.previousManifest,\n request: buildContainerRevokeRequest({\n body: input.body,\n event: input.event,\n keyEpoch: input.keyEpoch,\n keyring: input.keyring,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n parentKek: input.parentKek,\n predecessorBridge: input.predecessorBridge,\n previousManifest: input.previousManifest,\n previousProjection: input.previousProjection,\n principalPolicies: input.principalPolicies,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n }),\n state: input.state,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n };\n\n return { containerKey: input.containerKey, plan };\n}\n\n// biome-ignore lint/complexity/noExcessiveLinesPerFunction: Revoke planning has to keep the manifest, KEK, wraps, and signed event in one auditable transition.\nexport async function buildMaterializedContainerRevokePlan(input: {\n author: ContainerMutationAuthor;\n eventId?: string | undefined;\n execSql: ExecSql;\n /** Keys a batch minted above this container and has yet to commit. */\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n /** False for a projection re-rooted on rotations not yet acknowledged. */\n persistVerificationCheckpoints?: boolean | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n /** Verified policies the path may cite before they are stored locally. */\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n replacementPrincipalPolicy?: PrincipalPolicyCurrentEvidence | undefined;\n revokedSubject: ContainerRevokeSubject;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<MaterializedContainerRevokePlan> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container revoke\",\n );\n const {\n parentKek,\n parentPublicKey,\n predecessorContainerKey,\n previousState,\n target,\n } = await resolveRotationContext(input, \"revoke\");\n const principalPolicies = await collectContainerRevokePrincipalPolicies({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n previousProjection: input.previousProjection,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n assertContainerAuthorAccess({\n author: input.author,\n projection: input.previousProjection,\n principalPolicies,\n minimumAccess: \"admin\",\n });\n const nextContainerKeyEpoch = target.kek.containerKeyEpoch + 1;\n const { containerKey, containerKeyEpochId, keyring, predecessorBridge } =\n await buildContainerRotationArtifacts({\n containerId: previousState.containerId,\n currentKek: target.kek,\n currentKeyMaterial: predecessorContainerKey,\n keyEpoch: nextContainerKeyEpoch,\n signedEpochIds: target.signedEpochIds,\n });\n const body: ContainerRevokeAccessEventBody = {\n eventType: \"container.revoke\",\n parentManifestHash:\n input.previousProjection.path.at(-2)?.manifestHash ?? null,\n containerKeyPublicKey: await deriveContainerKekWrappingPublicKey({\n containerId: previousState.containerId,\n keyMaterial: containerKey,\n }),\n containerKeyEpochId,\n keyringHash: await computeContainerKekKeyringHash(keyring),\n predecessorBridgeHash:\n await computeContainerKekPredecessorBridgeHash(predecessorBridge),\n subjectId: input.revokedSubject.subjectId,\n subjectType: input.revokedSubject.subjectType,\n };\n const { event, eventHash } = await signContainerMutationEvent({\n author: input.author,\n body,\n containerId: previousState.containerId,\n dependencyManifestHashes: uniqueSortedManifestHashes(\n input.previousProjection.path,\n ),\n eventId: input.eventId ?? crypto.randomUUID(),\n previousManifestHash: target.manifest.manifestHash,\n signedAt: input.signedAt ?? new Date().toISOString(),\n });\n const { manifest, manifestHash, state } = await deriveContainerRevokeManifest(\n {\n containerKeyPublicKey: body.containerKeyPublicKey,\n parentManifestHash: body.parentManifestHash,\n containerKeyEpochId,\n eventHash,\n previousManifest: target.manifest,\n revokedSubject: input.revokedSubject,\n },\n );\n const keyEpoch = buildContainerCreateKeyEpoch({\n containerId: previousState.containerId,\n containerKeyEpochId,\n eventHash,\n keyEpoch: nextContainerKeyEpoch,\n manifestHash,\n parentContainerKeyEpochId: parentKek?.containerKeyEpochId ?? null,\n });\n\n const replacementPrincipalPolicy = input.replacementPrincipalPolicy;\n if (\n replacementPrincipalPolicy &&\n (replacementPrincipalPolicy.principalType !==\n input.revokedSubject.subjectType ||\n replacementPrincipalPolicy.principalId !== input.revokedSubject.subjectId)\n ) {\n throw new Error(\"Container revoke replacement principal does not match\");\n }\n const currentPrincipalPolicies = replacementPrincipalPolicy\n ? principalPolicies.filter(\n (policy) =>\n policy.principalType !== replacementPrincipalPolicy.principalType ||\n policy.principalId !== replacementPrincipalPolicy.principalId,\n )\n : principalPolicies;\n const { userRecipientKeys, wraps } = await buildContainerRotationWraps({\n containerKey,\n containerKeyEpochId,\n manifestHash,\n operationLabel: \"Container revoke\",\n parentKek,\n parentPublicKey,\n principalPolicies: currentPrincipalPolicies,\n resolveUserKey: resolveProjectionUserKey,\n state,\n });\n\n return buildContainerRevokePlanResult({\n body,\n containerId: previousState.containerId,\n containerKey,\n containerKeyEpochId,\n event,\n eventHash,\n keyEpoch,\n keyring,\n manifest,\n manifestHash,\n parentKek,\n predecessorBridge,\n previousManifest: asContainerManifestBundle(target.manifest),\n previousProjection: input.previousProjection,\n principalPolicies: currentPrincipalPolicies,\n state,\n userRecipientKeys,\n wraps,\n });\n}\n\nexport async function revokeRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n apiClient: ContainerRevokeApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n revokedSubject: ContainerRevokeSubject;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerRevokePlan;\n response: ContainerRotationResponse;\n} | null> {\n const previousProjection = await input.apiClient.getContainerWriterProjection(\n input.containerId,\n );\n if (!previousProjection) {\n return null;\n }\n\n const materializedPlan = await buildMaterializedContainerRevokePlan({\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n revokedSubject: input.revokedSubject,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n carriedRekeys: {\n planning: {\n apiClient: input.apiClient,\n author: input.author,\n execSql: input.execSql,\n knownContainerKeks: new Map([\n [\n materializedPlan.plan.containerKeyEpochId,\n materializedPlan.containerKey,\n ],\n ]),\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n },\n rotated: () =>\n containerWriterProjectionFromRotationPlan({\n plan: materializedPlan.plan,\n previousProjection,\n }),\n },\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: (carried) => {\n const request = carried.length\n ? { ...materializedPlan.plan.request, containerRekeys: [...carried] }\n : materializedPlan.plan.request;\n const options = {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n };\n const { revokeContainerResult } = input.apiClient;\n return submitContainerRotation({\n plain: () =>\n input.apiClient.revokeContainer(input.containerId, request, options),\n result: revokeContainerResult\n ? () =>\n revokeContainerResult.call(\n input.apiClient,\n input.containerId,\n request,\n { ...options, reportErrors: false },\n )\n : undefined,\n });\n },\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"rotationPrincipalPolicies.js","sourceRoot":"","sources":["rotationPrincipalPolicies.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mDAAmD,CAAC;AAC5F,OAAO,EACL,iDAAiD,GAIlD,MAAM,4CAA4C,CAAC;AAGpD;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,uCAAuC,CAAC,KAQ7D;IACC,OAAO,uBAAuB,CAC5B,MAAM,iDAAiD,CAAC;QACtD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,8BAA8B,EAAE,KAAK,CAAC,8BAA8B;QACpE,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,KAAK,CAAC,kBAAkB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { uniquePrincipalPolicies } from \"../../../data/containers/shared/principalPolicies\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\n/**\n * Shared by rekey and revoke. Lives apart from both: background descendant\n * repair imports the rekey planner, and revoke schedules that repair, so\n * declaring this in revoke would close a dependency cycle.\n */\nexport async function collectContainerRevokePrincipalPolicies(input: {\n execSql: ExecSql;\n persistVerificationCheckpoints?: boolean | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n return uniquePrincipalPolicies(\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.previousProjection,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n );\n}\n"]}
1
+ {"version":3,"file":"rotationPrincipalPolicies.js","sourceRoot":"","sources":["rotationPrincipalPolicies.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mDAAmD,CAAC;AAC5F,OAAO,EACL,iDAAiD,GAIlD,MAAM,4CAA4C,CAAC;AAIpD;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,uCAAuC,CAAC,KAQ7D;IACC,OAAO,uBAAuB,CAC5B,MAAM,iDAAiD,CAAC;QACtD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,8BAA8B,EAAE,KAAK,CAAC,8BAA8B;QACpE,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,KAAK,CAAC,kBAAkB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { uniquePrincipalPolicies } from \"../../../data/containers/shared/principalPolicies\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\n/**\n * Shared by rekey and revoke. Lives apart from both: background descendant\n * repair imports the rekey planner, and revoke schedules that repair, so\n * declaring this in revoke would close a dependency cycle.\n */\nexport async function collectContainerRevokePrincipalPolicies(input: {\n execSql: ExecSql;\n persistVerificationCheckpoints?: boolean | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n return uniquePrincipalPolicies(\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.previousProjection,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"rotationWraps.js","sourceRoot":"","sources":["rotationWraps.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,kCAAkC,EAClC,wBAAwB,EACxB,0BAA0B,G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;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n ContainerDirectGrant,\n ContainerGrantPrincipalHead,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { ContainerKekResponse } from \"@tearleads/validators/response\";\nimport {\n wrapContainerKeyToManagedPrincipal,\n wrapContainerKeyToParent,\n wrapContainerKeyToRootUser,\n} from \"../../../data/containers/shared/projection\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\n\nfunction findPrincipalPolicy(input: {\n operationLabel: string;\n principalPolicies: readonly VerifiedPrincipalPolicy[];\n reference: ReferencedPrincipalHead;\n}): VerifiedPrincipalPolicy {\n const policy = input.principalPolicies.find(\n (candidate) =>\n candidate.principalType === input.reference.principalType &&\n candidate.principalId === input.reference.principalId &&\n candidate.version === input.reference.version &&\n candidate.keyEpoch === input.reference.keyEpoch &&\n candidate.stateHash === input.reference.stateHash,\n );\n if (!policy) {\n // Invariant, not a recoverable state: the API commits a container head\n // only when every referenced group head equals the group's current state\n // (packages/api groupReferenceHeads.ts), and a group change that would\n // leave a grant stale is refused unless it rematerializes that container\n // in the same transaction (principalContainerRematerialization.ts). A\n // verified projection therefore always carries the policy its manifest\n // references; a miss means the caller resolved policies for a different\n // head than the manifest it is rotating.\n throw new Error(\n `${input.operationLabel} referenced ${input.reference.principalType} ${input.reference.principalId} at version ${input.reference.version} (key epoch ${input.reference.keyEpoch}), but no verified policy with that head was supplied; the API only commits heads whose group references are current`,\n );\n }\n return policy;\n}\n\nfunction referenceForManagedGrant(input: {\n grant: ContainerDirectGrant;\n operationLabel: string;\n state: ContainerAccessManifestState;\n}): ContainerGrantPrincipalHead {\n const reference = input.state.referencedPrincipalHeads.find(\n (candidate) =>\n candidate.principalType === input.grant.subjectType &&\n candidate.principalId === input.grant.subjectId,\n );\n if (reference?.principalType !== \"group\") {\n throw new Error(\n `${input.operationLabel} referenced principal head is missing`,\n );\n }\n return { ...reference, principalType: \"group\" };\n}\n\nexport async function buildContainerRotationWraps(input: {\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n manifestHash: string;\n operationLabel: string;\n parentKek: ContainerKekResponse | null;\n parentPublicKey: string | null;\n principalPolicies: readonly VerifiedPrincipalPolicy[];\n resolveUserKey: ProjectionUserKeyResolver;\n state: ContainerAccessManifestState;\n}): Promise<{\n readonly userRecipientKeys: ContainerUserRecipientKey[];\n readonly wraps: ContainerKeyWrap[];\n}> {\n const userRecipientKeys: ContainerUserRecipientKey[] = [];\n const wraps: ContainerKeyWrap[] = [];\n if (input.parentKek) {\n if (!input.parentPublicKey) {\n throw new Error(\n `${input.operationLabel} parent wrapping public key is missing`,\n );\n }\n wraps.push(\n await wrapContainerKeyToParent({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n parentKek: input.parentKek,\n parentPublicKey: input.parentPublicKey,\n }),\n );\n }\n\n for (const grant of input.state.directGrants) {\n if (grant.subjectType === \"user\") {\n const userKey = await input.resolveUserKey(grant.subjectId);\n if (!userKey) {\n throw new Error(\n `${input.operationLabel} recipient key is missing for direct user grant ${grant.subjectId}`,\n );\n }\n const recipient = await wrapContainerKeyToRootUser({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n recipientEncapsulationPublicKey: userKey.encapsulationPublicKey,\n userId: grant.subjectId,\n });\n userRecipientKeys.push(recipient.userRecipientKey);\n wraps.push(recipient.wrap);\n continue;\n }\n\n const reference = referenceForManagedGrant({\n grant,\n operationLabel: input.operationLabel,\n state: input.state,\n });\n const policy = findPrincipalPolicy({\n operationLabel: input.operationLabel,\n principalPolicies: input.principalPolicies,\n reference,\n });\n const recipient = await wrapContainerKeyToManagedPrincipal({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n principalEncapsulationPublicKey: policy.state.encapsulationPublicKey,\n principalHead: reference,\n });\n wraps.push(recipient.wrap);\n }\n\n return {\n userRecipientKeys: userRecipientKeys.sort((left, right) =>\n left.userId.localeCompare(right.userId),\n ),\n wraps: wraps.sort((left, right) =>\n `${left.recipientKind}:${left.recipientId}`.localeCompare(\n `${right.recipientKind}:${right.recipientId}`,\n ),\n ),\n };\n}\n"]}
1
+ {"version":3,"file":"rotationWraps.js","sourceRoot":"","sources":["rotationWraps.ts"],"names":[],"mappings":"AASA,OAAO,EACL,kCAAkC,EAClC,wBAAwB,EACxB,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAIpD,SAAS,mBAAmB,CAAC,KAI5B;IACC,MAAM,MAAM,GAAG,KAAK,CAAC,iBAAiB,CAAC,IAAI,CACzC,CAAC,SAAS,EAAE,EAAE,CACZ,SAAS,CAAC,aAAa,KAAK,KAAK,CAAC,SAAS,CAAC,aAAa;QACzD,SAAS,CAAC,WAAW,KAAK,KAAK,CAAC,SAAS,CAAC,WAAW;QACrD,SAAS,CAAC,OAAO,KAAK,KAAK,CAAC,SAAS,CAAC,OAAO;QAC7C,SAAS,CAAC,QAAQ,KAAK,KAAK,CAAC,SAAS,CAAC,QAAQ;QAC/C,SAAS,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS,CAAC,SAAS,CACpD,CAAC;IACF,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,uEAAuE;QACvE,yEAAyE;QACzE,uEAAuE;QACvE,yEAAyE;QACzE,sEAAsE;QACtE,uEAAuE;QACvE,wEAAwE;QACxE,yCAAyC;QACzC,MAAM,IAAI,KAAK,CACb,GAAG,KAAK,CAAC,cAAc,eAAe,KAAK,CAAC,SAAS,CAAC,aAAa,IAAI,KAAK,CAAC,SAAS,CAAC,WAAW,eAAe,KAAK,CAAC,SAAS,CAAC,OAAO,eAAe,KAAK,CAAC,SAAS,CAAC,QAAQ,sHAAsH,CACtS,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC;AACh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AAE,iBAAiB,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACxD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,CACxC;QACD,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAChC,GAAG,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC,aAAa,CACvD,GAAG,KAAK,CAAC,aAAa,IAAI,KAAK,CAAC,WAAW,EAAE,CAC9C,CACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n ContainerDirectGrant,\n ContainerGrantPrincipalHead,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ContainerKekResponse } from \"@tearleads/validators/response\";\nimport {\n wrapContainerKeyToManagedPrincipal,\n wrapContainerKeyToParent,\n wrapContainerKeyToRootUser,\n} from \"../../../data/containers/shared/projection\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principals/principalPolicyEvidence\";\n\nfunction findPrincipalPolicy(input: {\n operationLabel: string;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n reference: ReferencedPrincipalHead;\n}): PrincipalPolicyCurrentEvidence {\n const policy = input.principalPolicies.find(\n (candidate) =>\n candidate.principalType === input.reference.principalType &&\n candidate.principalId === input.reference.principalId &&\n candidate.version === input.reference.version &&\n candidate.keyEpoch === input.reference.keyEpoch &&\n candidate.stateHash === input.reference.stateHash,\n );\n if (!policy) {\n // Invariant, not a recoverable state: the API commits a container head\n // only when every referenced group head equals the group's current state\n // (packages/api groupReferenceHeads.ts), and a group change that would\n // leave a grant stale is refused unless it rematerializes that container\n // in the same transaction (principalContainerRematerialization.ts). A\n // verified projection therefore always carries the policy its manifest\n // references; a miss means the caller resolved policies for a different\n // head than the manifest it is rotating.\n throw new Error(\n `${input.operationLabel} referenced ${input.reference.principalType} ${input.reference.principalId} at version ${input.reference.version} (key epoch ${input.reference.keyEpoch}), but no verified policy with that head was supplied; the API only commits heads whose group references are current`,\n );\n }\n return policy;\n}\n\nfunction referenceForManagedGrant(input: {\n grant: ContainerDirectGrant;\n operationLabel: string;\n state: ContainerAccessManifestState;\n}): ContainerGrantPrincipalHead {\n const reference = input.state.referencedPrincipalHeads.find(\n (candidate) =>\n candidate.principalType === input.grant.subjectType &&\n candidate.principalId === input.grant.subjectId,\n );\n if (reference?.principalType !== \"group\") {\n throw new Error(\n `${input.operationLabel} referenced principal head is missing`,\n );\n }\n return { ...reference, principalType: \"group\" };\n}\n\nexport async function buildContainerRotationWraps(input: {\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n manifestHash: string;\n operationLabel: string;\n parentKek: ContainerKekResponse | null;\n parentPublicKey: string | null;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n resolveUserKey: ProjectionUserKeyResolver;\n state: ContainerAccessManifestState;\n}): Promise<{\n readonly userRecipientKeys: ContainerUserRecipientKey[];\n readonly wraps: ContainerKeyWrap[];\n}> {\n const userRecipientKeys: ContainerUserRecipientKey[] = [];\n const wraps: ContainerKeyWrap[] = [];\n if (input.parentKek) {\n if (!input.parentPublicKey) {\n throw new Error(\n `${input.operationLabel} parent wrapping public key is missing`,\n );\n }\n wraps.push(\n await wrapContainerKeyToParent({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n parentKek: input.parentKek,\n parentPublicKey: input.parentPublicKey,\n }),\n );\n }\n\n for (const grant of input.state.directGrants) {\n if (grant.subjectType === \"user\") {\n const userKey = await input.resolveUserKey(grant.subjectId);\n if (!userKey) {\n throw new Error(\n `${input.operationLabel} recipient key is missing for direct user grant ${grant.subjectId}`,\n );\n }\n const recipient = await wrapContainerKeyToRootUser({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n recipientEncapsulationPublicKey: userKey.encapsulationPublicKey,\n userId: grant.subjectId,\n });\n userRecipientKeys.push(recipient.userRecipientKey);\n wraps.push(recipient.wrap);\n continue;\n }\n\n const reference = referenceForManagedGrant({\n grant,\n operationLabel: input.operationLabel,\n state: input.state,\n });\n const policy = findPrincipalPolicy({\n operationLabel: input.operationLabel,\n principalPolicies: input.principalPolicies,\n reference,\n });\n const recipient = await wrapContainerKeyToManagedPrincipal({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n principalEncapsulationPublicKey: policy.state.encapsulationPublicKey,\n principalHead: reference,\n });\n wraps.push(recipient.wrap);\n }\n\n return {\n userRecipientKeys: userRecipientKeys.sort((left, right) =>\n left.userId.localeCompare(right.userId),\n ),\n wraps: wraps.sort((left, right) =>\n `${left.recipientKind}:${left.recipientId}`.localeCompare(\n `${right.recipientKind}:${right.recipientId}`,\n ),\n ),\n };\n}\n"]}
@@ -1,19 +1,20 @@
1
- import { type AccessEvent, type AccessManifest, type ContainerAccessManifestState, type ContainerDirectGrant, type ContainerGrantAccessEventBody, type ContainerGrantPrincipalHead, type ContainerKekRecipientTarget, type ContainerKeyWrap, type ContainerUserRecipientKey, type VerifiedPrincipalPolicy } from "../../../internal/crypto/index.js";
1
+ import { type AccessEvent, type AccessManifest, type ContainerAccessManifestState, type ContainerDirectGrant, type ContainerGrantAccessEventBody, type ContainerGrantPrincipalHead, type ContainerKekRecipientTarget, type ContainerKeyWrap, type ContainerUserRecipientKey } from "../../../internal/crypto/index.js";
2
2
  import type { AccessManifestBundleWire } from "../../../internal/validators/request/index.js";
3
3
  import type { ContainerKekResponse, ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
4
4
  import type { ContainerSharePlan, MaterializedContainerSharePlan } from "../../../data/containers/shared/types.js";
5
5
  import { type PrincipalPolicyCache, type ProjectionUserKeyResolver, type ReferencedPrincipalPolicyWarmer } from "../../../data/keyingProjectionVerification.js";
6
+ import type { PrincipalPolicyCurrentEvidence } from "../../../data/principals/principalPolicyEvidence.js";
6
7
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
7
8
  export type ContainerShareRecipient = {
8
9
  readonly recipientEncapsulationPublicKey: Uint8Array;
9
10
  readonly subjectId: string;
10
11
  readonly subjectType: "user";
11
12
  } | {
12
- readonly principalPolicy: VerifiedPrincipalPolicy;
13
+ readonly principalPolicy: PrincipalPolicyCurrentEvidence;
13
14
  readonly subjectId: string;
14
15
  readonly subjectType: "group";
15
16
  };
16
- export declare function referencedPrincipalHeadFromPolicy(policy: VerifiedPrincipalPolicy): ContainerGrantPrincipalHead;
17
+ export declare function referencedPrincipalHeadFromPolicy(policy: PrincipalPolicyCurrentEvidence): ContainerGrantPrincipalHead;
17
18
  /**
18
19
  * The previous manifest's referenced principal heads with the replacement
19
20
  * policy's head upserted in place of any stale head for the same principal.
@@ -23,16 +24,16 @@ export declare function referencedPrincipalHeadFromPolicy(policy: VerifiedPrinci
23
24
  */
24
25
  export declare function refreshedPrincipalReferences(input: {
25
26
  readonly previousState: ContainerAccessManifestState;
26
- readonly replacementPrincipalPolicy?: VerifiedPrincipalPolicy | undefined;
27
+ readonly replacementPrincipalPolicy?: PrincipalPolicyCurrentEvidence | undefined;
27
28
  }): ContainerGrantPrincipalHead[];
28
29
  /**
29
30
  * The previous policies with the replacement policy substituted for any
30
31
  * existing policy of the same principal identity.
31
32
  */
32
33
  export declare function refreshedPrincipalPolicies(input: {
33
- readonly previousPolicies: readonly VerifiedPrincipalPolicy[];
34
- readonly replacementPrincipalPolicy?: VerifiedPrincipalPolicy | undefined;
35
- }): VerifiedPrincipalPolicy[];
34
+ readonly previousPolicies: readonly PrincipalPolicyCurrentEvidence[];
35
+ readonly replacementPrincipalPolicy?: PrincipalPolicyCurrentEvidence | undefined;
36
+ }): PrincipalPolicyCurrentEvidence[];
36
37
  export declare function deriveContainerShareManifest(input: {
37
38
  eventHash: string;
38
39
  grant: ContainerDirectGrant;
@@ -57,7 +58,7 @@ export declare function buildContainerSharePlanResult(input: {
57
58
  manifestHash: string;
58
59
  previousManifest: AccessManifestBundleWire;
59
60
  previousProjection: ContainerWriterProjectionResponse;
60
- principalPolicies: readonly VerifiedPrincipalPolicy[];
61
+ principalPolicies: readonly PrincipalPolicyCurrentEvidence[];
61
62
  recipientTarget: ContainerKekRecipientTarget;
62
63
  state: ContainerAccessManifestState;
63
64
  targetKek: ContainerKekResponse;
@@ -74,8 +75,8 @@ export declare function collectContainerSharePrincipalPolicies(input: {
74
75
  persistVerificationCheckpoints?: boolean | undefined;
75
76
  principalPolicyCache?: PrincipalPolicyCache | undefined;
76
77
  previousProjection: ContainerWriterProjectionResponse;
77
- recipientPolicy?: VerifiedPrincipalPolicy | undefined;
78
+ recipientPolicy?: PrincipalPolicyCurrentEvidence | undefined;
78
79
  resolveUserKey: ProjectionUserKeyResolver;
79
80
  stillCurrent?: (() => boolean) | undefined;
80
81
  warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
81
- }): Promise<VerifiedPrincipalPolicy[]>;
82
+ }): Promise<PrincipalPolicyCurrentEvidence[]>;
@@ -1 +1 @@
1
- {"version":3,"file":"sharePlanCore.js","sourceRoot":"","sources":["sharePlanCore.ts"],"names":[],"mappings":"AAAA,OAAO,EAWL,yBAAyB,EACzB,6BAA6B,GAE9B,MAAM,mBAAmB,CAAC;AAS3B,OAAO,EAAE,uBAAuB,EAAE,MAAM,mDAAmD,CAAC;AAC5F,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,gCAAgC,EAChC,qBAAqB,GACtB,MAAM,yCAAyC,CAAC;AAKjD,OAAO,EACL,iDAAiD,GAIlD,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,uBAA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QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACL,OAAO,0BAA0B,CAAC;QAChC,gBAAgB;QAChB,0BAA0B,EAAE,KAAK,CAAC,eAAe;KAClD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n type AccessEvent,\n type AccessManifest,\n type ContainerAccessManifestState,\n type ContainerDirectGrant,\n type ContainerGrantAccessEventBody,\n type ContainerGrantPrincipalHead,\n type ContainerKekRecipientTarget,\n type ContainerKeyEpoch,\n type ContainerKeyWrap,\n type ContainerUserRecipientKey,\n computeAccessManifestHash,\n deriveContainerAccessManifest,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerKekResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { uniquePrincipalPolicies } from \"../../../data/containers/shared/principalPolicies\";\nimport {\n asContainerManifestBundle,\n getParentKekForTarget,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport {\n readContainerKekRecipientTargets,\n readContainerKeyEpoch,\n} from \"../../../data/containers/shared/readers\";\nimport type {\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n containerMutationRequestCore,\n previousPathRequestFields,\n readCanonicalRecordOrNull,\n} from \"./mutationRequestCore\";\n\nexport type ContainerShareRecipient =\n | {\n readonly recipientEncapsulationPublicKey: Uint8Array;\n readonly subjectId: string;\n readonly subjectType: \"user\";\n }\n | {\n readonly principalPolicy: VerifiedPrincipalPolicy;\n readonly subjectId: string;\n readonly subjectType: \"group\";\n };\n\nfunction grantKey(\n grant: Pick<ContainerDirectGrant, \"subjectId\" | \"subjectType\">,\n): string {\n return `${grant.subjectType}:${grant.subjectId}`;\n}\n\nfunction upsertContainerGrant(\n grants: readonly ContainerDirectGrant[],\n grant: ContainerDirectGrant,\n): ContainerDirectGrant[] {\n return [\n ...grants.filter(\n (existingGrant) => grantKey(existingGrant) !== grantKey(grant),\n ),\n grant,\n ].sort((left, right) => grantKey(left).localeCompare(grantKey(right)));\n}\n\nfunction referencedPrincipalKey(reference: {\n readonly principalId: string;\n readonly principalType: \"group\";\n}): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nexport function referencedPrincipalHeadFromPolicy(\n policy: VerifiedPrincipalPolicy,\n): ContainerGrantPrincipalHead {\n if (policy.principalType !== \"group\") {\n throw new Error(\"Container grants can reference only group policies\");\n }\n return {\n principalType: \"group\",\n principalId: policy.principalId,\n version: policy.version,\n keyEpoch: policy.keyEpoch,\n stateHash: policy.stateHash,\n keyFingerprint: policy.state.keyFingerprint,\n };\n}\n\nfunction upsertReferencedPrincipalHead(\n references: readonly ContainerGrantPrincipalHead[],\n reference: ContainerGrantPrincipalHead,\n): ContainerGrantPrincipalHead[] {\n return [\n ...references.filter(\n (existingReference) =>\n referencedPrincipalKey(existingReference) !==\n referencedPrincipalKey(reference),\n ),\n reference,\n ].sort((left, right) =>\n referencedPrincipalKey(left).localeCompare(referencedPrincipalKey(right)),\n );\n}\n\n/**\n * The previous manifest's referenced principal heads with the replacement\n * policy's head upserted in place of any stale head for the same principal.\n * A rekey substitutes references and never adds one: a manifest may reference\n * only principals it grants, so a replacement for one it does not grant —\n * a carried rekey below the container the policy is granted on — is left out.\n */\nexport function refreshedPrincipalReferences(input: {\n readonly previousState: ContainerAccessManifestState;\n readonly replacementPrincipalPolicy?: VerifiedPrincipalPolicy | undefined;\n}): ContainerGrantPrincipalHead[] {\n const replacement = input.replacementPrincipalPolicy;\n if (\n !replacement ||\n !input.previousState.directGrants.some(\n (grant) =>\n grant.subjectType === replacement.principalType &&\n grant.subjectId === replacement.principalId,\n )\n ) {\n return [...input.previousState.referencedPrincipalHeads];\n }\n return upsertReferencedPrincipalHead(\n input.previousState.referencedPrincipalHeads,\n referencedPrincipalHeadFromPolicy(replacement),\n );\n}\n\n/**\n * The previous policies with the replacement policy substituted for any\n * existing policy of the same principal identity.\n */\nexport function refreshedPrincipalPolicies(input: {\n readonly previousPolicies: readonly VerifiedPrincipalPolicy[];\n readonly replacementPrincipalPolicy?: VerifiedPrincipalPolicy | undefined;\n}): VerifiedPrincipalPolicy[] {\n const replacement = input.replacementPrincipalPolicy;\n if (!replacement) {\n return uniquePrincipalPolicies(input.previousPolicies);\n }\n return uniquePrincipalPolicies([\n ...input.previousPolicies.filter(\n (policy) =>\n policy.principalType !== replacement.principalType ||\n policy.principalId !== replacement.principalId,\n ),\n replacement,\n ]);\n}\n\nexport async function deriveContainerShareManifest(input: {\n eventHash: string;\n grant: ContainerDirectGrant;\n previousManifest: ContainerWriterProjectionResponse[\"path\"][number];\n referencedPrincipalHead: ContainerGrantPrincipalHead | null;\n}): Promise<Pick<ContainerSharePlan, \"manifest\" | \"manifestHash\" | \"state\">> {\n const previousState = readContainerState(input.previousManifest);\n const state: ContainerAccessManifestState = {\n ...previousState,\n epoch: previousState.epoch + 1,\n previousManifestHash: input.previousManifest.manifestHash,\n eventHash: input.eventHash,\n directGrants: upsertContainerGrant(previousState.directGrants, input.grant),\n referencedPrincipalHeads: input.referencedPrincipalHead\n ? upsertReferencedPrincipalHead(\n previousState.referencedPrincipalHeads,\n input.referencedPrincipalHead,\n )\n : previousState.referencedPrincipalHeads,\n };\n const manifest = await deriveContainerAccessManifest(state);\n\n return {\n manifest,\n manifestHash: await computeAccessManifestHash(manifest),\n state,\n };\n}\n\nfunction buildContainerShareRequest(input: {\n body: ContainerGrantAccessEventBody;\n containerManifestHistory: readonly AccessManifestBundleWire[];\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n parentKek: ContainerKekResponse | null;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly VerifiedPrincipalPolicy[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n ...containerMutationRequestCore(\"share\", input),\n ...previousPathRequestFields(\n input.previousManifest,\n input.previousProjection,\n ),\n containerManifestHistory: [...input.containerManifestHistory],\n predecessorBridge: null,\n keyring: null,\n parentKekState: readCanonicalRecordOrNull(\n input.parentKek,\n \"Container share parent KEK state\",\n ),\n };\n}\n\nexport function replaceContainerWrap(\n wraps: readonly ContainerKeyWrap[],\n nextWrap: ContainerKeyWrap,\n): ContainerKeyWrap[] {\n return [\n ...wraps.filter(\n (wrap) =>\n !(\n wrap.recipientKind === nextWrap.recipientKind &&\n wrap.recipientId === nextWrap.recipientId\n ),\n ),\n nextWrap,\n ];\n}\n\nexport function shareManifestHistory(input: {\n readonly containerId: string;\n readonly targetKek: ContainerKekResponse;\n readonly targetManifest: ContainerWriterProjectionResponse[\"path\"][number];\n}): AccessManifestBundleWire[] {\n const byHash = new Map<string, AccessManifestBundleWire>();\n for (const bundle of [\n input.targetManifest,\n ...input.targetKek.containerManifestHistory,\n ]) {\n if (\n readContainerState(bundle).containerId === input.containerId &&\n !byHash.has(bundle.manifestHash)\n ) {\n byHash.set(bundle.manifestHash, asContainerManifestBundle(bundle));\n }\n }\n return [...byHash.values()];\n}\n\nexport function buildContainerSharePlanResult(input: {\n body: ContainerGrantAccessEventBody;\n containerManifestHistory: readonly AccessManifestBundleWire[];\n containerId: string;\n containerKey: Uint8Array;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly VerifiedPrincipalPolicy[];\n recipientTarget: ContainerKekRecipientTarget;\n state: ContainerAccessManifestState;\n targetKek: ContainerKekResponse;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}): MaterializedContainerSharePlan {\n const keyEpoch = readContainerKeyEpoch(\n input.targetKek.keyEpoch,\n \"Container share key epoch\",\n );\n const plan: ContainerSharePlan = {\n body: input.body,\n containerId: input.containerId,\n event: input.event,\n eventHash: input.eventHash,\n grant: input.grant,\n keyEpoch,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n previousKeyring: readCanonicalRecordOrNull(\n input.previousProjection.containerKeks.at(-1)?.keyring ?? null,\n \"Container share previous keyring\",\n ),\n previousManifest: input.previousManifest,\n recipientTarget: input.recipientTarget,\n request: buildContainerShareRequest({\n body: input.body,\n containerManifestHistory: input.containerManifestHistory,\n event: input.event,\n keyEpoch,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n parentKek: getParentKekForTarget(input.previousProjection),\n previousManifest: input.previousManifest,\n previousProjection: input.previousProjection,\n principalPolicies: input.principalPolicies,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n }),\n state: input.state,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n };\n\n return { containerKey: input.containerKey, plan };\n}\n\nexport function collectShareUserRecipientKeys(input: {\n newUserRecipientKey?: ContainerUserRecipientKey | undefined;\n state: ContainerAccessManifestState;\n targetKek: ContainerKekResponse;\n}): ContainerUserRecipientKey[] {\n const directUserIds = new Set(\n input.state.directGrants.flatMap((grant) =>\n grant.subjectType === \"user\" ? [grant.subjectId] : [],\n ),\n );\n const userRecipientKeyByUserId = new Map<string, ContainerUserRecipientKey>();\n\n for (const target of readContainerKekRecipientTargets(\n input.targetKek.recipientTargets,\n \"Container share target KEK recipient targets\",\n )) {\n if (\n target.recipientKind !== \"user\" ||\n !directUserIds.has(target.recipientId)\n ) {\n continue;\n }\n userRecipientKeyByUserId.set(target.recipientId, {\n userId: target.recipientId,\n recipientKeyEpochId: target.recipientKeyEpochId,\n recipientKeyFingerprint: target.recipientKeyFingerprint,\n });\n }\n\n if (input.newUserRecipientKey) {\n userRecipientKeyByUserId.set(\n input.newUserRecipientKey.userId,\n input.newUserRecipientKey,\n );\n }\n\n const missingUserId = [...directUserIds].find(\n (userId) => !userRecipientKeyByUserId.has(userId),\n );\n if (missingUserId) {\n throw new Error(\n `Container share recipient key is missing for direct user grant ${missingUserId}`,\n );\n }\n\n return [...userRecipientKeyByUserId.values()].sort((left, right) =>\n left.userId.localeCompare(right.userId),\n );\n}\n\nexport async function collectContainerSharePrincipalPolicies(input: {\n execSql: ExecSql;\n persistVerificationCheckpoints?: boolean | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n recipientPolicy?: VerifiedPrincipalPolicy | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const previousPolicies =\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.previousProjection,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n return refreshedPrincipalPolicies({\n previousPolicies,\n replacementPrincipalPolicy: input.recipientPolicy,\n });\n}\n"]}
1
+ {"version":3,"file":"sharePlanCore.js","sourceRoot":"","sources":["sharePlanCore.ts"],"names":[],"mappings":"AAAA,OAAO,EAWL,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,mBAAmB,CAAC;AAS3B,OAAO,EAAE,uBAAuB,EAAE,MAAM,mDAAmD,CAAC;AAC5F,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,gCAAgC,EAChC,qBAAqB,GACtB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ACpE,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,KAAK,CAAC,kBAAkB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACL,OAAO,0BAA0B,CAAC;QAChC,gBAAgB;QAChB,0BAA0B,EAAE,KAAK,CAAC,eAAe;KAClD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n type AccessEvent,\n type AccessManifest,\n type ContainerAccessManifestState,\n type ContainerDirectGrant,\n type ContainerGrantAccessEventBody,\n type ContainerGrantPrincipalHead,\n type ContainerKekRecipientTarget,\n type ContainerKeyEpoch,\n type ContainerKeyWrap,\n type ContainerUserRecipientKey,\n computeAccessManifestHash,\n deriveContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerKekResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { uniquePrincipalPolicies } from \"../../../data/containers/shared/principalPolicies\";\nimport {\n asContainerManifestBundle,\n getParentKekForTarget,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport {\n readContainerKekRecipientTargets,\n readContainerKeyEpoch,\n} from \"../../../data/containers/shared/readers\";\nimport type {\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n containerMutationRequestCore,\n previousPathRequestFields,\n readCanonicalRecordOrNull,\n} from \"./mutationRequestCore\";\n\nexport type ContainerShareRecipient =\n | {\n readonly recipientEncapsulationPublicKey: Uint8Array;\n readonly subjectId: string;\n readonly subjectType: \"user\";\n }\n | {\n readonly principalPolicy: PrincipalPolicyCurrentEvidence;\n readonly subjectId: string;\n readonly subjectType: \"group\";\n };\n\nfunction grantKey(\n grant: Pick<ContainerDirectGrant, \"subjectId\" | \"subjectType\">,\n): string {\n return `${grant.subjectType}:${grant.subjectId}`;\n}\n\nfunction upsertContainerGrant(\n grants: readonly ContainerDirectGrant[],\n grant: ContainerDirectGrant,\n): ContainerDirectGrant[] {\n return [\n ...grants.filter(\n (existingGrant) => grantKey(existingGrant) !== grantKey(grant),\n ),\n grant,\n ].sort((left, right) => grantKey(left).localeCompare(grantKey(right)));\n}\n\nfunction referencedPrincipalKey(reference: {\n readonly principalId: string;\n readonly principalType: \"group\";\n}): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nexport function referencedPrincipalHeadFromPolicy(\n policy: PrincipalPolicyCurrentEvidence,\n): ContainerGrantPrincipalHead {\n if (policy.principalType !== \"group\") {\n throw new Error(\"Container grants can reference only group policies\");\n }\n return {\n principalType: \"group\",\n principalId: policy.principalId,\n version: policy.version,\n keyEpoch: policy.keyEpoch,\n stateHash: policy.stateHash,\n keyFingerprint: policy.state.keyFingerprint,\n };\n}\n\nfunction upsertReferencedPrincipalHead(\n references: readonly ContainerGrantPrincipalHead[],\n reference: ContainerGrantPrincipalHead,\n): ContainerGrantPrincipalHead[] {\n return [\n ...references.filter(\n (existingReference) =>\n referencedPrincipalKey(existingReference) !==\n referencedPrincipalKey(reference),\n ),\n reference,\n ].sort((left, right) =>\n referencedPrincipalKey(left).localeCompare(referencedPrincipalKey(right)),\n );\n}\n\n/**\n * The previous manifest's referenced principal heads with the replacement\n * policy's head upserted in place of any stale head for the same principal.\n * A rekey substitutes references and never adds one: a manifest may reference\n * only principals it grants, so a replacement for one it does not grant —\n * a carried rekey below the container the policy is granted on — is left out.\n */\nexport function refreshedPrincipalReferences(input: {\n readonly previousState: ContainerAccessManifestState;\n readonly replacementPrincipalPolicy?:\n | PrincipalPolicyCurrentEvidence\n | undefined;\n}): ContainerGrantPrincipalHead[] {\n const replacement = input.replacementPrincipalPolicy;\n if (\n !replacement ||\n !input.previousState.directGrants.some(\n (grant) =>\n grant.subjectType === replacement.principalType &&\n grant.subjectId === replacement.principalId,\n )\n ) {\n return [...input.previousState.referencedPrincipalHeads];\n }\n return upsertReferencedPrincipalHead(\n input.previousState.referencedPrincipalHeads,\n referencedPrincipalHeadFromPolicy(replacement),\n );\n}\n\n/**\n * The previous policies with the replacement policy substituted for any\n * existing policy of the same principal identity.\n */\nexport function refreshedPrincipalPolicies(input: {\n readonly previousPolicies: readonly PrincipalPolicyCurrentEvidence[];\n readonly replacementPrincipalPolicy?:\n | PrincipalPolicyCurrentEvidence\n | undefined;\n}): PrincipalPolicyCurrentEvidence[] {\n const replacement = input.replacementPrincipalPolicy;\n if (!replacement) {\n return uniquePrincipalPolicies(input.previousPolicies);\n }\n return uniquePrincipalPolicies([\n ...input.previousPolicies.filter(\n (policy) =>\n policy.principalType !== replacement.principalType ||\n policy.principalId !== replacement.principalId,\n ),\n replacement,\n ]);\n}\n\nexport async function deriveContainerShareManifest(input: {\n eventHash: string;\n grant: ContainerDirectGrant;\n previousManifest: ContainerWriterProjectionResponse[\"path\"][number];\n referencedPrincipalHead: ContainerGrantPrincipalHead | null;\n}): Promise<Pick<ContainerSharePlan, \"manifest\" | \"manifestHash\" | \"state\">> {\n const previousState = readContainerState(input.previousManifest);\n const state: ContainerAccessManifestState = {\n ...previousState,\n epoch: previousState.epoch + 1,\n previousManifestHash: input.previousManifest.manifestHash,\n eventHash: input.eventHash,\n directGrants: upsertContainerGrant(previousState.directGrants, input.grant),\n referencedPrincipalHeads: input.referencedPrincipalHead\n ? upsertReferencedPrincipalHead(\n previousState.referencedPrincipalHeads,\n input.referencedPrincipalHead,\n )\n : previousState.referencedPrincipalHeads,\n };\n const manifest = await deriveContainerAccessManifest(state);\n\n return {\n manifest,\n manifestHash: await computeAccessManifestHash(manifest),\n state,\n };\n}\n\nfunction buildContainerShareRequest(input: {\n body: ContainerGrantAccessEventBody;\n containerManifestHistory: readonly AccessManifestBundleWire[];\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n parentKek: ContainerKekResponse | null;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n ...containerMutationRequestCore(\"share\", input),\n ...previousPathRequestFields(\n input.previousManifest,\n input.previousProjection,\n ),\n containerManifestHistory: [...input.containerManifestHistory],\n predecessorBridge: null,\n keyring: null,\n parentKekState: readCanonicalRecordOrNull(\n input.parentKek,\n \"Container share parent KEK state\",\n ),\n };\n}\n\nexport function replaceContainerWrap(\n wraps: readonly ContainerKeyWrap[],\n nextWrap: ContainerKeyWrap,\n): ContainerKeyWrap[] {\n return [\n ...wraps.filter(\n (wrap) =>\n !(\n wrap.recipientKind === nextWrap.recipientKind &&\n wrap.recipientId === nextWrap.recipientId\n ),\n ),\n nextWrap,\n ];\n}\n\nexport function shareManifestHistory(input: {\n readonly containerId: string;\n readonly targetKek: ContainerKekResponse;\n readonly targetManifest: ContainerWriterProjectionResponse[\"path\"][number];\n}): AccessManifestBundleWire[] {\n const byHash = new Map<string, AccessManifestBundleWire>();\n for (const bundle of [\n input.targetManifest,\n ...input.targetKek.containerManifestHistory,\n ]) {\n if (\n readContainerState(bundle).containerId === input.containerId &&\n !byHash.has(bundle.manifestHash)\n ) {\n byHash.set(bundle.manifestHash, asContainerManifestBundle(bundle));\n }\n }\n return [...byHash.values()];\n}\n\nexport function buildContainerSharePlanResult(input: {\n body: ContainerGrantAccessEventBody;\n containerManifestHistory: readonly AccessManifestBundleWire[];\n containerId: string;\n containerKey: Uint8Array;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n recipientTarget: ContainerKekRecipientTarget;\n state: ContainerAccessManifestState;\n targetKek: ContainerKekResponse;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}): MaterializedContainerSharePlan {\n const keyEpoch = readContainerKeyEpoch(\n input.targetKek.keyEpoch,\n \"Container share key epoch\",\n );\n const plan: ContainerSharePlan = {\n body: input.body,\n containerId: input.containerId,\n event: input.event,\n eventHash: input.eventHash,\n grant: input.grant,\n keyEpoch,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n previousKeyring: readCanonicalRecordOrNull(\n input.previousProjection.containerKeks.at(-1)?.keyring ?? null,\n \"Container share previous keyring\",\n ),\n previousManifest: input.previousManifest,\n recipientTarget: input.recipientTarget,\n request: buildContainerShareRequest({\n body: input.body,\n containerManifestHistory: input.containerManifestHistory,\n event: input.event,\n keyEpoch,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n parentKek: getParentKekForTarget(input.previousProjection),\n previousManifest: input.previousManifest,\n previousProjection: input.previousProjection,\n principalPolicies: input.principalPolicies,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n }),\n state: input.state,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n };\n\n return { containerKey: input.containerKey, plan };\n}\n\nexport function collectShareUserRecipientKeys(input: {\n newUserRecipientKey?: ContainerUserRecipientKey | undefined;\n state: ContainerAccessManifestState;\n targetKek: ContainerKekResponse;\n}): ContainerUserRecipientKey[] {\n const directUserIds = new Set(\n input.state.directGrants.flatMap((grant) =>\n grant.subjectType === \"user\" ? [grant.subjectId] : [],\n ),\n );\n const userRecipientKeyByUserId = new Map<string, ContainerUserRecipientKey>();\n\n for (const target of readContainerKekRecipientTargets(\n input.targetKek.recipientTargets,\n \"Container share target KEK recipient targets\",\n )) {\n if (\n target.recipientKind !== \"user\" ||\n !directUserIds.has(target.recipientId)\n ) {\n continue;\n }\n userRecipientKeyByUserId.set(target.recipientId, {\n userId: target.recipientId,\n recipientKeyEpochId: target.recipientKeyEpochId,\n recipientKeyFingerprint: target.recipientKeyFingerprint,\n });\n }\n\n if (input.newUserRecipientKey) {\n userRecipientKeyByUserId.set(\n input.newUserRecipientKey.userId,\n input.newUserRecipientKey,\n );\n }\n\n const missingUserId = [...directUserIds].find(\n (userId) => !userRecipientKeyByUserId.has(userId),\n );\n if (missingUserId) {\n throw new Error(\n `Container share recipient key is missing for direct user grant ${missingUserId}`,\n );\n }\n\n return [...userRecipientKeyByUserId.values()].sort((left, right) =>\n left.userId.localeCompare(right.userId),\n );\n}\n\nexport async function collectContainerSharePrincipalPolicies(input: {\n execSql: ExecSql;\n persistVerificationCheckpoints?: boolean | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n recipientPolicy?: PrincipalPolicyCurrentEvidence | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const previousPolicies =\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.previousProjection,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n return refreshedPrincipalPolicies({\n previousPolicies,\n replacementPrincipalPolicy: input.recipientPolicy,\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"linkSetAuthority.js","sourceRoot":"","sources":["linkSetAuthority.ts"],"names":[],"mappings":"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;AACJ,CAAC;AAED,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,KAKiC;IAEjC,yBAAyB,CAAC,KAAK,EAAE,oCAAoC,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,sBAAsB,KAAK,IAAI;QAAE,OAAO;IAClD,IAAI,CAAC;QACH,KAAK,MAAM,UAAU,IAAI;YACvB,KAAK,CAAC,yBAAyB;YAC/B,GAAG,4BAA4B,CAAC,KAAK,CAAC,gBAAgB,CAAC;SACxD,EAAE,CAAC;YACF,MAAM,iDAAiD,CAAC;gBACtD,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;gBAChD,UAAU;gBACV,cAAc,EAAE,KAAK,CAAC,wBAAwB;gBAC9C,YAAY,EAAE,KAAK,CAAC,YAAY;gBAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;aACvE,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,uCAAuC,CACrC,KAAK,EACL,sDAAsD,CACvD,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { AnyVerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n assertContainerAuthorAccess,\n ContainerAuthorAccessError,\n} from \"../../data/containers/shared/authorAccess\";\nimport { readLinkedContainerIdsFromDocumentManifest } from \"../../data/documents/shared/projection\";\nimport type { DocumentCreateAuthor } from \"../../data/documents/shared/types\";\nimport {\n type ProjectionVerificationOptions,\n resolveProjectionVerifier,\n} from \"../../data/documents/shared/types\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n} from \"../../data/keyingProjectionVerification\";\nimport { documentContainerProjections } from \"../../data/keyingProjectionVerification/documentContainerProjections\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../data/keyingProjectionVerification/error\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\n/** Both paths have been verified; a readable proof does not authorize a link. */\nexport function assertDocumentLinkAuthorAccess(input: {\n author: DocumentCreateAuthor;\n principalPolicies: readonly AnyVerifiedPrincipalPolicy[];\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): void {\n const author = {\n ...input.author,\n organizationId: input.targetContainerProjection.organizationId,\n };\n const permission = {\n author,\n minimumAccess: \"write\" as const,\n principalPolicies: input.principalPolicies,\n };\n assertContainerAuthorAccess({\n ...permission,\n projection: input.targetContainerProjection,\n });\n const linked = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n for (const projection of documentContainerProjections(\n input.writerProjection,\n )) {\n if (!linked.includes(projection.containerId)) continue;\n try {\n assertContainerAuthorAccess({ ...permission, projection });\n return;\n } catch (error) {\n if (!(error instanceof ContainerAuthorAccessError)) throw error;\n }\n }\n throw new ContainerAuthorAccessError(\n \"Document signer lacks write access through a linked container\",\n );\n}\n\n/** Current write authorization needs full policies for the readable paths. */\nexport async function verifyDocumentLinkSetCurrentPolicies(\n input: {\n execSql?: ExecSql | undefined;\n principalPolicyCache: PrincipalPolicyCache;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<void> {\n resolveProjectionVerifier(input, \"Document link-set current policies\");\n if (input.trustedLocalProjection === true) return;\n try {\n for (const projection of [\n input.targetContainerProjection,\n ...documentContainerProjections(input.writerProjection),\n ]) {\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n principalPolicyCache: input.principalPolicyCache,\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n }\n } catch (error) {\n throwKeyingVerificationErrorWithContext(\n error,\n \"Document link-set current policy verification failed\",\n );\n }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KAAK,CAAC;QAClE,CAAC;IACH,CAAC;IACD,MAAM,IAAI,0BAA0B,CAClC,+DAA+D,CAChE,CAAC;AACJ,CAAC;AAED,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,KAKiC;IAEjC,yBAAyB,CAAC,KAAK,EAAE,oCAAoC,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,sBAAsB,KAAK,IAAI;QAAE,OAAO;IAClD,IAAI,CAAC;QACH,KAAK,MAAM,UAAU,IAAI;YACvB,KAAK,CAAC,yBAAyB;YAC/B,GAAG,4BAA4B,CAAC,KAAK,CAAC,gBAAgB,CAAC;SACxD,EAAE,CAAC;YACF,MAAM,iDAAiD,CAAC;gBACtD,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;gBAChD,UAAU;gBACV,cAAc,EAAE,KAAK,CAAC,wBAAwB;gBAC9C,YAAY,EAAE,KAAK,CAAC,YAAY;gBAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;aACvE,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,uCAAuC,CACrC,KAAK,EACL,sDAAsD,CACvD,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n assertContainerAuthorAccess,\n ContainerAuthorAccessError,\n} from \"../../data/containers/shared/authorAccess\";\nimport { readLinkedContainerIdsFromDocumentManifest } from \"../../data/documents/shared/projection\";\nimport type { DocumentCreateAuthor } from \"../../data/documents/shared/types\";\nimport {\n type ProjectionVerificationOptions,\n resolveProjectionVerifier,\n} from \"../../data/documents/shared/types\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n} from \"../../data/keyingProjectionVerification\";\nimport { documentContainerProjections } from \"../../data/keyingProjectionVerification/documentContainerProjections\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../data/principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\n/** Both paths have been verified; a readable proof does not authorize a link. */\nexport function assertDocumentLinkAuthorAccess(input: {\n author: DocumentCreateAuthor;\n principalPolicies: readonly PrincipalPolicyCheckpointEvidence[];\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): void {\n const author = {\n ...input.author,\n organizationId: input.targetContainerProjection.organizationId,\n };\n const permission = {\n author,\n minimumAccess: \"write\" as const,\n principalPolicies: input.principalPolicies,\n };\n assertContainerAuthorAccess({\n ...permission,\n projection: input.targetContainerProjection,\n });\n const linked = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n for (const projection of documentContainerProjections(\n input.writerProjection,\n )) {\n if (!linked.includes(projection.containerId)) continue;\n try {\n assertContainerAuthorAccess({ ...permission, projection });\n return;\n } catch (error) {\n if (!(error instanceof ContainerAuthorAccessError)) throw error;\n }\n }\n throw new ContainerAuthorAccessError(\n \"Document signer lacks write access through a linked container\",\n );\n}\n\n/** Current write authorization needs full policies for the readable paths. */\nexport async function verifyDocumentLinkSetCurrentPolicies(\n input: {\n execSql?: ExecSql | undefined;\n principalPolicyCache: PrincipalPolicyCache;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<void> {\n resolveProjectionVerifier(input, \"Document link-set current policies\");\n if (input.trustedLocalProjection === true) return;\n try {\n for (const projection of [\n input.targetContainerProjection,\n ...documentContainerProjections(input.writerProjection),\n ]) {\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n principalPolicyCache: input.principalPolicyCache,\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n }\n } catch (error) {\n throwKeyingVerificationErrorWithContext(\n error,\n \"Document link-set current policy verification failed\",\n );\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
1
  export { type CachePrincipalPolicyBundlesOptions, type CacheReferencedPrincipalPoliciesOptions, cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
2
2
  export { PrincipalPolicyHistoryReadError, type RecoveredPrincipalPolicyHistory, type RecoverPrincipalPolicyHistoryOptions, } from "./principalHistoryRecoveryTypes.js";
3
3
  export { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
4
+ export { type RecoveredScopedPrincipalPolicyHistory, type RecoverScopedPrincipalPolicyHistoryOptions, recoverScopedPrincipalPolicyHistory, } from "./recoverScopedPrincipalPolicyHistory.js";
@@ -1,4 +1,5 @@
1
1
  export { cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
2
2
  export { PrincipalPolicyHistoryReadError, } from "./principalHistoryRecoveryTypes.js";
3
3
  export { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
4
+ export { recoverScopedPrincipalPolicyHistory, } from "./recoverScopedPrincipalPolicyHistory.js";
4
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC","sourcesContent":["export {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAGL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC","sourcesContent":["export {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\nexport {\n type RecoveredScopedPrincipalPolicyHistory,\n type RecoverScopedPrincipalPolicyHistoryOptions,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n"]}
@@ -0,0 +1,65 @@
1
+ import { restorePrincipalPolicyHistoryVerifier, serializeKeyingCanonicalJson, } from "../../internal/crypto/index.js";
2
+ import { isReferencedPrincipalStateResponse } from "../../internal/validators/response/index.js";
3
+ import { discardPrincipalHistoryPrefix, loadPrincipalHistoryPrefix, savePrincipalHistoryPrefix, } from "../../data/persistence/principalHistoryPrefixPersistence.js";
4
+ import { principalHistoryPrefixProtection } from "../../data/principals/principalHistoryPrefixProtection.js";
5
+ import { parsePrincipalHistoryStageCurrent } from "../../data/principals/principalHistoryStageProtection.js";
6
+ export async function loadVerifiedPrincipalHistoryPrefix(options, historyInput, scopeId) {
7
+ const saved = await loadPrincipalHistoryPrefix(options.execSql, scopeId);
8
+ if (!saved)
9
+ return null;
10
+ let head;
11
+ try {
12
+ head = JSON.parse(saved.headJson);
13
+ }
14
+ catch {
15
+ head = null;
16
+ }
17
+ if (saved.organizationId === options.organizationId &&
18
+ isReferencedPrincipalStateResponse(head) &&
19
+ head.principalType === historyInput.principalType &&
20
+ head.principalId === historyInput.principalId &&
21
+ head.version === saved.version) {
22
+ const restored = await restorePrincipalPolicyHistoryVerifier(historyInput, saved.progress, await principalHistoryPrefixProtection(options.protection, saved));
23
+ const current = parsePrincipalHistoryStageCurrent({
24
+ currentJson: saved.currentJson,
25
+ afterVersion: saved.version - 1,
26
+ });
27
+ if (restored.ok && restored.value.finish(head).ok && current)
28
+ return { verifier: restored.value, head, current };
29
+ }
30
+ await discardPrincipalHistoryPrefix({
31
+ execSql: options.execSql,
32
+ prefix: saved,
33
+ stillCurrent: () => !options.signal?.aborted && options.stillCurrent(),
34
+ });
35
+ return null;
36
+ }
37
+ export async function restoreReusablePrincipalHistoryPrefix(options, historyInput, scopeId) {
38
+ const prefix = await loadVerifiedPrincipalHistoryPrefix(options, historyInput, scopeId);
39
+ if (!prefix || prefix.head.version > options.expectedHead.version)
40
+ return null;
41
+ if (prefix.head.version < options.expectedHead.version ||
42
+ prefix.verifier.finish(options.expectedHead).ok)
43
+ return { ...prefix, version: prefix.head.version };
44
+ // An incompatible target cannot erase an independently valid local hint.
45
+ return null;
46
+ }
47
+ /** The verifier must use stable empty selection/checkpoint inputs. */
48
+ export async function publishReusablePrincipalHistoryPrefix(options, scopeId, verifier, current) {
49
+ const prefix = {
50
+ scopeId,
51
+ organizationId: options.organizationId,
52
+ version: options.expectedHead.version,
53
+ headJson: serializeKeyingCanonicalJson({ ...options.expectedHead }),
54
+ currentJson: JSON.stringify(current),
55
+ };
56
+ const sealed = await verifier.exportProgress(await principalHistoryPrefixProtection(options.protection, prefix));
57
+ if (!sealed.ok)
58
+ throw sealed.error;
59
+ await savePrincipalHistoryPrefix({
60
+ execSql: options.execSql,
61
+ prefix: { ...prefix, progress: sealed.value },
62
+ stillCurrent: () => !options.signal?.aborted && options.stillCurrent(),
63
+ });
64
+ }
65
+ //# sourceMappingURL=principalHistoryRecoveryPrefix.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalHistoryRecoveryPrefix.js","sourceRoot":"","sources":["principalHistoryRecoveryPrefix.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AACpF,OAAO,EACL,6BAA6B,EAC7B,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,gCAAgC,EAAE,MAAM,wDAAwD,CAAC;AAC1G,OAAO,EAAE,iCAAiC,EAAE,MAAM,uDAAuD,CAAC;AAG1G,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,OAAmE,EACnE,YAAyC,EACzC,OAAe;IAMf,MAAM,KAAK,GAAG,MAAM,0BAA0B,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACzE,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IACxB,IAAI,IAAa,CAAC;IAClB,IAAI,CAAC;QACH,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC;IAAC,MAAM,CAAC;QACP,IAAI,GAAG,IAAI,CAAC;IACd,CAAC;IACD,IACE,KAAK,CAAC,cAAc,KAAK,OAAO,CAAC,cAAc;QAC/C,kCAAkC,CAAC,IAAI,CAAC;QACxC,IAAI,CAAC,aAAa,KAAK,YAAY,CAAC,aAAa;QACjD,IAAI,CAAC,WAAW,KAAK,YAAY,CAAC,WAAW;QAC7C,IAAI,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,EAC9B,CAAC;QACD,MAAM,QAAQ,GAAG,MAAM,qCAAqC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rD,yEAAyE;IACzE,OAAO,IAAI,CAAC;AACd,CAAC;AAED,sEAAsE;AACtE,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,OAA6C,EAC7C,OAAe,EACf,QAAwC,EACxC,OAAmC;IAEnC,MAAM,MAAM,GAAG;QACb,OAAO;QACP,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,OAAO;QACrC,QAAQ,EAAE,4BAA4B,CAAC,EAAE,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;QACnE,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;KACrC,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,cAAc,CAC1C,MAAM,gCAAgC,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,CAAC,CACnE,CAAC;IACF,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,MAAM,CAAC,KAAK,CAAC;IACnC,MAAM,0BAA0B,CAAC;QAC/B,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,KAAK,EAAE;QAC7C,YAAY,EAAE,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,IAAI,OAAO,CAAC,YAAY,EAAE;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n type PrincipalPolicyHistoryInput,\n type PrincipalPolicyHistoryVerifier,\n type ReferencedPrincipalHead,\n restorePrincipalPolicyHistoryVerifier,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { isReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport {\n discardPrincipalHistoryPrefix,\n loadPrincipalHistoryPrefix,\n savePrincipalHistoryPrefix,\n} from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHistoryPrefixProtection } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { parsePrincipalHistoryStageCurrent } from \"../../data/principals/principalHistoryStageProtection\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport async function loadVerifiedPrincipalHistoryPrefix(\n options: Omit<RecoverPrincipalPolicyHistoryOptions, \"expectedHead\">,\n historyInput: PrincipalPolicyHistoryInput,\n scopeId: string,\n): Promise<{\n verifier: PrincipalPolicyHistoryVerifier;\n head: ReferencedPrincipalHead;\n current: PrincipalPolicyPageCurrent;\n} | null> {\n const saved = await loadPrincipalHistoryPrefix(options.execSql, scopeId);\n if (!saved) return null;\n let head: unknown;\n try {\n head = JSON.parse(saved.headJson);\n } catch {\n head = null;\n }\n if (\n saved.organizationId === options.organizationId &&\n isReferencedPrincipalStateResponse(head) &&\n head.principalType === historyInput.principalType &&\n head.principalId === historyInput.principalId &&\n head.version === saved.version\n ) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n saved.progress,\n await principalHistoryPrefixProtection(options.protection, saved),\n );\n const current = parsePrincipalHistoryStageCurrent({\n currentJson: saved.currentJson,\n afterVersion: saved.version - 1,\n });\n if (restored.ok && restored.value.finish(head).ok && current)\n return { verifier: restored.value, head, current };\n }\n await discardPrincipalHistoryPrefix({\n execSql: options.execSql,\n prefix: saved,\n stillCurrent: () => !options.signal?.aborted && options.stillCurrent(),\n });\n return null;\n}\n\nexport async function restoreReusablePrincipalHistoryPrefix(\n options: RecoverPrincipalPolicyHistoryOptions,\n historyInput: PrincipalPolicyHistoryInput,\n scopeId: string,\n) {\n const prefix = await loadVerifiedPrincipalHistoryPrefix(\n options,\n historyInput,\n scopeId,\n );\n if (!prefix || prefix.head.version > options.expectedHead.version)\n return null;\n if (\n prefix.head.version < options.expectedHead.version ||\n prefix.verifier.finish(options.expectedHead).ok\n )\n return { ...prefix, version: prefix.head.version };\n // An incompatible target cannot erase an independently valid local hint.\n return null;\n}\n\n/** The verifier must use stable empty selection/checkpoint inputs. */\nexport async function publishReusablePrincipalHistoryPrefix(\n options: RecoverPrincipalPolicyHistoryOptions,\n scopeId: string,\n verifier: PrincipalPolicyHistoryVerifier,\n current: PrincipalPolicyPageCurrent,\n): Promise<void> {\n const prefix = {\n scopeId,\n organizationId: options.organizationId,\n version: options.expectedHead.version,\n headJson: serializeKeyingCanonicalJson({ ...options.expectedHead }),\n currentJson: JSON.stringify(current),\n };\n const sealed = await verifier.exportProgress(\n await principalHistoryPrefixProtection(options.protection, prefix),\n );\n if (!sealed.ok) throw sealed.error;\n await savePrincipalHistoryPrefix({\n execSql: options.execSql,\n prefix: { ...prefix, progress: sealed.value },\n stillCurrent: () => !options.signal?.aborted && options.stillCurrent(),\n });\n}\n"]}
@@ -0,0 +1,60 @@
1
+ import { KeyingVerificationError, verifyPrincipalPolicyHistoryReferences, } from "../../internal/crypto/index.js";
2
+ import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
3
+ import { loadPrincipalHistoryReference } from "../../data/persistence/principalHistoryEvidencePersistence.js";
4
+ import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
5
+ export class PrincipalHistoryEvidenceUnavailableError extends Error {
6
+ verificationError;
7
+ constructor(verificationError) {
8
+ super(verificationError.message);
9
+ this.verificationError = verificationError;
10
+ this.name = "PrincipalHistoryEvidenceUnavailableError";
11
+ }
12
+ }
13
+ async function selectReferences(input) {
14
+ const { options, scopeId, history } = input;
15
+ const current = () => !options.signal?.aborted && options.stillCurrent();
16
+ const base = { execSql: options.execSql, scopeId, history };
17
+ const references = [];
18
+ for (const reference of options.retainedReferences ?? []) {
19
+ assertProjectionVerificationCurrent(current);
20
+ references.push(await loadPrincipalHistoryReference({
21
+ ...base,
22
+ version: reference.version,
23
+ }));
24
+ }
25
+ assertProjectionVerificationCurrent(current);
26
+ const checkpointReference = input.checkpoint
27
+ ? await loadPrincipalHistoryReference({
28
+ ...base,
29
+ version: input.checkpoint.version,
30
+ })
31
+ : undefined;
32
+ const selected = await verifyPrincipalPolicyHistoryReferences({
33
+ history,
34
+ references,
35
+ checkpointReference,
36
+ });
37
+ if (!selected.ok)
38
+ throw selected.error;
39
+ assertProjectionVerificationCurrent(current);
40
+ return selected.value;
41
+ }
42
+ export async function selectRecoveredPrincipalHistory(input) {
43
+ let selected;
44
+ try {
45
+ selected = await selectReferences(input);
46
+ }
47
+ catch (error) {
48
+ if (error instanceof KeyingVerificationError)
49
+ throw new PrincipalHistoryEvidenceUnavailableError(error);
50
+ throw error;
51
+ }
52
+ // First authenticate the stored entry against the private root. Only then
53
+ // compare the caller's citation, so a bad request is not treated as cache loss.
54
+ for (const reference of input.options.retainedReferences ?? []) {
55
+ if (!selected.retainedEntries.some(({ state }) => principalHeadMatchesReference(state, reference)))
56
+ throw new KeyingVerificationError("object_mismatch", "Requested citation does not match the verified principal history");
57
+ }
58
+ return selected;
59
+ }
60
+ //# sourceMappingURL=principalHistoryRecoveryReferences.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalHistoryRecoveryReferences.js","sourceRoot":"","sources":["principalHistoryRecoveryReferences.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAIvB,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AAGtG,MAAM,OAAO,wCAAyC,SAAQ,KAAK;IAC5C;IAArB,YAAqB,iBAA0C;QAC7D,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QADd,sBAAiB,GAAjB,iBAAiB,CAAyB;QAE7D,IAAI,CAAC,IAAI,GAAG,0CAA0C,CAAC;IACzD,CAAC;CACF;AAED,KAAK,UAAU,gBAAgB,CAAC,KAK/B;IACC,MAAM,EAAE,OAAO,E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,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB;YAC1C,MAAM,IAAI,wCAAwC,CAAC,KAAK,CAAC,CAAC;QAC5D,MAAM,KAAK,CAAC;IACd,CAAC;IACD,0EAA0E;IAC1E,gFAAgF;IAChF,KAAK,MAAM,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,kBAAkB,IAAI,EAAE,EAAE,CAAC;QAC/D,IACE,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAC3C,6BAA6B,CAAC,KAAK,EAAE,SAAS,CAAC,CAChD;YAED,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kEAAkE,CACnE,CAAC;IACN,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryReferenceProof,\n type VerifiedPrincipalPolicyHistory,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport class PrincipalHistoryEvidenceUnavailableError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PrincipalHistoryEvidenceUnavailableError\";\n }\n}\n\nasync function selectReferences(input: {\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n readonly scopeId: string;\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly checkpoint: PrincipalPolicyCheckpoint | null;\n}): Promise<VerifiedPrincipalPolicyHistory> {\n const { options, scopeId, history } = input;\n const current = () => !options.signal?.aborted && options.stillCurrent();\n const base = { execSql: options.execSql, scopeId, history };\n const references: PrincipalPolicyHistoryReferenceProof[] = [];\n for (const reference of options.retainedReferences ?? []) {\n assertProjectionVerificationCurrent(current);\n references.push(\n await loadPrincipalHistoryReference({\n ...base,\n version: reference.version,\n }),\n );\n }\n assertProjectionVerificationCurrent(current);\n const checkpointReference = input.checkpoint\n ? await loadPrincipalHistoryReference({\n ...base,\n version: input.checkpoint.version,\n })\n : undefined;\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references,\n checkpointReference,\n });\n if (!selected.ok) throw selected.error;\n assertProjectionVerificationCurrent(current);\n return selected.value;\n}\n\nexport async function selectRecoveredPrincipalHistory(\n input: Parameters<typeof selectReferences>[0],\n): Promise<VerifiedPrincipalPolicyHistory> {\n let selected: VerifiedPrincipalPolicyHistory;\n try {\n selected = await selectReferences(input);\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n }\n // First authenticate the stored entry against the private root. Only then\n // compare the caller's citation, so a bad request is not treated as cache loss.\n for (const reference of input.options.retainedReferences ?? []) {\n if (\n !selected.retainedEntries.some(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Requested citation does not match the verified principal history\",\n );\n }\n return selected;\n}\n"]}