@tearleads/client-sdk 0.1.248 → 0.1.250

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 (178) hide show
  1. package/client/organizations/index.js +5 -3
  2. package/client/organizations/index.js.map +1 -1
  3. package/client/organizations/organizationGroupPresentation.d.ts +1 -1
  4. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  5. package/client/organizations/organizationLeaveRequestVerifier.js +21 -0
  6. package/client/organizations/organizationLeaveRequestVerifier.js.map +1 -0
  7. package/client/organizations/{organizationReadModels.d.ts → organizationReadModelCoordinator.d.ts} +18 -16
  8. package/client/organizations/organizationReadModelCoordinator.js +2 -0
  9. package/client/organizations/organizationReadModelCoordinator.js.map +1 -0
  10. package/client/organizations/organizationReadModelPresentation.js +51 -0
  11. package/client/organizations/organizationReadModelPresentation.js.map +1 -0
  12. package/client/organizations/organizationReadModelScopes.js +37 -0
  13. package/client/organizations/organizationReadModelScopes.js.map +1 -0
  14. package/client/organizations/organizationReadModels.js +131 -88
  15. package/client/organizations/organizationReadModels.js.map +1 -1
  16. package/client/organizations/organizationsTypes.d.ts +13 -5
  17. package/client/organizations/organizationsTypes.js.map +1 -1
  18. package/client/organizations/principalMutations.d.ts +18 -2
  19. package/client/organizations/principalMutations.js +29 -15
  20. package/client/organizations/principalMutations.js.map +1 -1
  21. package/client/runtime/principalMutationApi.d.ts +2 -0
  22. package/client/runtime/principalMutationApi.js +2 -0
  23. package/client/runtime/principalMutationApi.js.map +1 -1
  24. package/client/runtime/principalMutationDispatch.js +47 -10
  25. package/client/runtime/principalMutationDispatch.js.map +1 -1
  26. package/client/runtime/workflowRuntime.js +5 -4
  27. package/client/runtime/workflowRuntime.js.map +1 -1
  28. package/data/containers/shared/mutationRequestOptions.d.ts +2 -0
  29. package/data/containers/shared/mutationRequestOptions.js.map +1 -1
  30. package/data/containers/shared/types.d.ts +12 -2
  31. package/data/containers/shared/types.js.map +1 -1
  32. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js +1 -4
  33. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -1
  34. package/data/persistence/organizations/organizationReadModelRepository.js +20 -2
  35. package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -1
  36. package/data/persistence/principalPolicy/heldOrganizationDirectories.js +6 -1
  37. package/data/persistence/principalPolicy/heldOrganizationDirectories.js.map +1 -1
  38. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js +1 -1
  39. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -1
  40. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js +1 -5
  41. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -1
  42. package/data/principals/organizationGroupDirectoryRequest.js +0 -2
  43. package/data/principals/organizationGroupDirectoryRequest.js.map +1 -1
  44. package/data/principals/organizationPolicyRequest.js +0 -2
  45. package/data/principals/organizationPolicyRequest.js.map +1 -1
  46. package/data/principals/principalPolicyRequest.js +0 -2
  47. package/data/principals/principalPolicyRequest.js.map +1 -1
  48. package/internal/api-client/ApiClient.d.ts +4 -59
  49. package/internal/api-client/client/apiClientContext.d.ts +0 -30
  50. package/internal/api-client/client/containerMutations.d.ts +2 -2
  51. package/internal/api-client/client/containerMutations.js +2 -1
  52. package/internal/api-client/client/containerMutations.js.map +1 -1
  53. package/internal/api-client/client/documents.d.ts +0 -12
  54. package/internal/api-client/client/principalPolicies.d.ts +3 -18
  55. package/internal/api-client/client/writerProjections.d.ts +0 -12
  56. package/internal/api-client/heldDirectoryCitations.d.ts +8 -4
  57. package/internal/api-client/heldDirectoryCitations.js +6 -10
  58. package/internal/api-client/heldDirectoryCitations.js.map +1 -1
  59. package/internal/api-client/organizationPolicyHistory.d.ts +0 -6
  60. package/internal/api-client/principalPolicyRequests.d.ts +2 -18
  61. package/internal/api-client/principalPolicyRequests.js +6 -4
  62. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  63. package/internal/api-client/routes/containers/mutations.js +3 -3
  64. package/internal/api-client/routes/containers/mutations.js.map +1 -1
  65. package/internal/api-client/routes/organizations/createGroup.js +3 -5
  66. package/internal/api-client/routes/organizations/createGroup.js.map +1 -1
  67. package/internal/api-client/routes/principals/policy.js +2 -5
  68. package/internal/api-client/routes/principals/policy.js.map +1 -1
  69. package/internal/api-client/types.d.ts +6 -0
  70. package/internal/api-client/types.js.map +1 -1
  71. package/internal/api-client/verifiedManifestCitations.js +3 -3
  72. package/internal/api-client/verifiedManifestCitations.js.map +1 -1
  73. package/internal/crypto/index.d.ts +1 -1
  74. package/internal/crypto/index.js.map +1 -1
  75. package/internal/crypto/keying/principalPolicyPayload.js +2 -12
  76. package/internal/crypto/keying/principalPolicyPayload.js.map +1 -1
  77. package/internal/crypto/keying/principalPolicyTypes.d.ts +5 -6
  78. package/internal/crypto/keying/principalPolicyTypes.js.map +1 -1
  79. package/internal/crypto/principalState.d.ts +1 -1
  80. package/internal/crypto/principalState.js.map +1 -1
  81. package/internal/crypto/principalStateTypes.d.ts +0 -1
  82. package/internal/crypto/principalStateTypes.js.map +1 -1
  83. package/internal/validators/operation/auth.d.ts +0 -24
  84. package/internal/validators/operation/containerMutations.d.ts +20 -3
  85. package/internal/validators/operation/containerMutations.js +18 -20
  86. package/internal/validators/operation/containerMutations.js.map +1 -1
  87. package/internal/validators/operation/documentMutations.d.ts +0 -48
  88. package/internal/validators/operation/index.d.ts +1 -1
  89. package/internal/validators/operation/index.js +1 -1
  90. package/internal/validators/operation/index.js.map +1 -1
  91. package/internal/validators/operation/organizationPolicyHistory.d.ts +0 -24
  92. package/internal/validators/operation/organizations.d.ts +17 -49
  93. package/internal/validators/operation/organizations.js +4 -2
  94. package/internal/validators/operation/organizations.js.map +1 -1
  95. package/internal/validators/operation/principals.d.ts +17 -57
  96. package/internal/validators/operation/principals.js +5 -2
  97. package/internal/validators/operation/principals.js.map +1 -1
  98. package/internal/validators/operation/writerProjections.d.ts +0 -48
  99. package/internal/validators/request/index.d.ts +1 -1
  100. package/internal/validators/request/index.js +1 -1
  101. package/internal/validators/request/index.js.map +1 -1
  102. package/internal/validators/request/organization.d.ts +15 -32
  103. package/internal/validators/request/organization.js +8 -0
  104. package/internal/validators/request/organization.js.map +1 -1
  105. package/internal/validators/request/organizationProvisioning.d.ts +0 -72
  106. package/internal/validators/request/principal.d.ts +4 -48
  107. package/internal/validators/request/principal.js +4 -2
  108. package/internal/validators/request/principal.js.map +1 -1
  109. package/internal/validators/request/registration.d.ts +0 -24
  110. package/internal/validators/response/areas/organizations.d.ts +3 -2
  111. package/internal/validators/response/areas/organizations.js +3 -2
  112. package/internal/validators/response/areas/organizations.js.map +1 -1
  113. package/internal/validators/response/areas/principals.d.ts +1 -1
  114. package/internal/validators/response/areas/principals.js +1 -1
  115. package/internal/validators/response/areas/principals.js.map +1 -1
  116. package/internal/validators/response/committedReadModel.d.ts +697 -0
  117. package/internal/validators/response/committedReadModel.js +52 -0
  118. package/internal/validators/response/committedReadModel.js.map +1 -0
  119. package/internal/validators/response/container.d.ts +52 -48
  120. package/internal/validators/response/container.js +3 -3
  121. package/internal/validators/response/container.js.map +1 -1
  122. package/internal/validators/response/documentMutation.d.ts +0 -96
  123. package/internal/validators/response/organization.d.ts +0 -191
  124. package/internal/validators/response/organization.js +0 -7
  125. package/internal/validators/response/organization.js.map +1 -1
  126. package/internal/validators/response/organizationPolicyHistory.d.ts +0 -24
  127. package/internal/validators/response/organizationReadModel.d.ts +167 -0
  128. package/internal/validators/response/organizationReadModel.js +5 -0
  129. package/internal/validators/response/organizationReadModel.js.map +1 -1
  130. package/internal/validators/response/policyEvidenceWire.d.ts +5 -3
  131. package/internal/validators/response/policyEvidenceWire.js +6 -4
  132. package/internal/validators/response/policyEvidenceWire.js.map +1 -1
  133. package/internal/validators/response/principal.d.ts +0 -451
  134. package/internal/validators/response/principal.js +0 -8
  135. package/internal/validators/response/principal.js.map +1 -1
  136. package/internal/validators/response/principalPolicyPage.d.ts +0 -48
  137. package/internal/validators/response/principalSnapshot.d.ts +4 -24
  138. package/internal/validators/response/principalSnapshot.js +4 -6
  139. package/internal/validators/response/principalSnapshot.js.map +1 -1
  140. package/internal/validators/response/projectionPolicyEvidence.d.ts +0 -48
  141. package/package.json +1 -1
  142. package/workflows/container-contents/container-state/organizationHost.d.ts +9 -0
  143. package/workflows/container-contents/container-state/organizationHost.js.map +1 -1
  144. package/workflows/container-contents/container-state/remote.js +6 -0
  145. package/workflows/container-contents/container-state/remote.js.map +1 -1
  146. package/workflows/containers/child/share/index.d.ts +4 -2
  147. package/workflows/containers/child/share/index.js +37 -20
  148. package/workflows/containers/child/share/index.js.map +1 -1
  149. package/workflows/organizations/containerContentsHost.js +20 -1
  150. package/workflows/organizations/containerContentsHost.js.map +1 -1
  151. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +5 -1
  152. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
  153. package/workflows/organizations/groupPolicy/currentPolicyMutationAcknowledgement.js +1 -6
  154. package/workflows/organizations/groupPolicy/currentPolicyMutationAcknowledgement.js.map +1 -1
  155. package/workflows/organizations/groupPolicy/groupPolicyMutationAcknowledgement.js +1 -6
  156. package/workflows/organizations/groupPolicy/groupPolicyMutationAcknowledgement.js.map +1 -1
  157. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +8 -1
  158. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  159. package/workflows/organizations/index.d.ts +1 -0
  160. package/workflows/organizations/index.js +1 -0
  161. package/workflows/organizations/index.js.map +1 -1
  162. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js +4 -6
  163. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -1
  164. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +1 -7
  165. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
  166. package/workflows/organizations/readModel/committedReadModel.d.ts +66 -0
  167. package/workflows/organizations/readModel/committedReadModel.js +150 -0
  168. package/workflows/organizations/readModel/committedReadModel.js.map +1 -0
  169. package/workflows/organizations/readModel/readModelProjection.d.ts +15 -2
  170. package/workflows/organizations/readModel/readModelProjection.js +26 -4
  171. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  172. package/workflows/principals/policyCache/principalPolicyCacheValidation.js +0 -13
  173. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
  174. package/workflows/principals/publicHistory/publicProjectionDirectory.js +4 -5
  175. package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -1
  176. package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -6
  177. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -7
  178. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
@@ -1,6 +1,6 @@
1
1
  import type { AccessEvent, AccessManifest, ContainerAccessManifestState, ContainerCreateAccessEventBody, ContainerDirectGrant, ContainerGrantAccessEventBody, ContainerGrantPrincipalHead, ContainerKekKeyring, ContainerKekRecipientTarget, ContainerKeyEpoch, ContainerKeyWrap, ContainerMoveAccessEventBody, ContainerRekeyAccessEventBody, ContainerRevokeAccessEventBody, ContainerUserRecipientKey } from "../../../internal/crypto/index.js";
2
2
  import type { AccessManifestBundleWire, ContainerCreateWithMetadataDocumentRequest, ContainerMutationRequest, ContainerRotationRequest } from "../../../internal/validators/request/index.js";
3
- import type { ContainerCreateWithMetadataDocumentResponse, ContainerKekResponse, ContainerMutationResponse, ContainerRotationResponse, ContainerWriterProjectionResponse, ReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
3
+ import type { ContainerCreateWithMetadataDocumentResponse, ContainerKekResponse, ContainerMutationResponse, ContainerRotationResponse, ContainerShareResponse, ContainerWriterProjectionResponse, OrganizationReadModelDeltaResponse, ReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
4
4
  import type { PrincipalPolicyCurrentEvidence } from "../../principalContracts/principalPolicyEvidence.js";
5
5
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
6
6
  import type { ContainerMutationRequestOptions } from "./mutationRequestOptions.js";
@@ -92,9 +92,19 @@ export interface ContainerShareApi extends ContainerReciteApi {
92
92
  getContainerWriterProjection(containerId: string): Promise<ContainerWriterProjectionResponse | null>;
93
93
  shareContainer(containerId: string, input: ContainerMutationRequest, options?: ContainerMutationRequestOptions): Promise<ContainerMutationResponse | null>;
94
94
  /** Tells a stale path, which a fresh projection clears, from a refusal. */
95
- shareContainerResult?(containerId: string, input: ContainerMutationRequest, options?: ContainerMutationRequestOptions): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;
95
+ shareContainerResult?(containerId: string, input: ContainerMutationRequest, options?: ContainerMutationRequestOptions): Promise<ContainerMutationSubmitResult<ContainerShareResponse>>;
96
96
  evictContainerWriterProjection?(containerId: string): void;
97
97
  }
98
+ /**
99
+ * Sends the organization read-model cursor a share holds, so its response can
100
+ * carry the delta from it; the share settles the lease once it ends.
101
+ */
102
+ export interface ContainerShareCommittedReadModel {
103
+ begin(): Promise<{
104
+ readonly heldCursor: string | undefined;
105
+ settle(delta: OrganizationReadModelDeltaResponse | undefined): void;
106
+ }>;
107
+ }
98
108
  /**
99
109
  * A status-bearing rotation outcome. A refusal that names
100
110
  * `requiredContainerIds` is answerable: sign those descendant rekeys and
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerCreateAccessEventBody,\n ContainerDirectGrant,\n ContainerGrantAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKekKeyring,\n ContainerKekRecipientTarget,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerMoveAccessEventBody,\n ContainerRekeyAccessEventBody,\n ContainerRevokeAccessEventBody,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerCreateWithMetadataDocumentRequest,\n ContainerMutationRequest,\n ContainerRotationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerCreateWithMetadataDocumentResponse,\n ContainerKekResponse,\n ContainerMutationResponse,\n ContainerRotationResponse,\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { ContainerMutationRequestOptions } from \"./mutationRequestOptions\";\nimport type { ContainerReciteApi } from \"./reciteApi\";\n\nexport interface ContainerMutationAuthor {\n organizationId: string;\n signerDeviceId: string;\n signerKeyFingerprint: string;\n signerPrivateKey: Uint8Array;\n signerUserId: string;\n}\n\nexport interface BuildContainerCreatePlanInput {\n author: ContainerMutationAuthor;\n containerId?: string | undefined;\n containerKey: Uint8Array;\n containerKeyEpochId?: string | undefined;\n eventId?: string | undefined;\n /**\n * Optional group grant to bake into the\n * create manifest, wrapping the new container key to that principal in\n * addition to the normal parent-inheritance wrap. Used to birth a child\n * container that is directly readable by a group — e.g. the org public\n * metadata container granted to the reserved Members group. The principal's\n * verified policy must also be supplied via `principalPolicies` so the server\n * can derive the recipient target.\n */\n managedPrincipalGrant?:\n | {\n accessLevel: ContainerDirectGrant[\"accessLevel\"];\n principalEncapsulationPublicKey: string;\n principalHead: ContainerGrantPrincipalHead;\n }\n | undefined;\n metadataDocumentId?: string | undefined;\n systemSlot?: string | null | undefined;\n parentProjection: ContainerWriterProjectionResponse;\n principalPolicies?: readonly PrincipalPolicyCurrentEvidence[] | undefined;\n signedAt?: string | undefined;\n}\n\nexport interface ContainerCreatePlan {\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyEpochHash: string;\n keyTargetHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n metadataDocumentId: string;\n parentContainerId: string | null;\n parentManifestHash: string | null;\n recipientTargets: ContainerKekRecipientTarget[];\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerCreatePlan {\n containerKey: Uint8Array;\n plan: ContainerCreatePlan;\n}\n\nexport interface ContainerCreatePlanContext\n extends BuildContainerCreatePlanInput {\n containerKeyPublicKey: string;\n containerId: string;\n containerKeyEpochId: string;\n eventId: string;\n metadataDocumentId: string;\n parent: ParentContainerCreateContext;\n signedAt: string;\n}\n\nexport interface ContainerMutationSubmitFailure {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report: () => void;\n readonly stalePrincipalHeads?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n readonly status: number | null;\n}\n\nexport type ContainerMutationSubmitResult<T> =\n | {\n readonly data: T;\n readonly ok: true;\n }\n | ContainerMutationSubmitFailure;\n\nexport interface ContainerCreateApi {\n createContainerResult(\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n createContainerWithMetadataDocumentResult(\n input: ContainerCreateWithMetadataDocumentRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<\n ContainerMutationSubmitResult<ContainerCreateWithMetadataDocumentResponse>\n >;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport interface ContainerShareApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n shareContainer(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationResponse | null>;\n /** Tells a stale path, which a fresh projection clears, from a refusal. */\n shareContainerResult?(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n evictContainerWriterProjection?(containerId: string): void;\n}\n\n/**\n * A status-bearing rotation outcome. A refusal that names\n * `requiredContainerIds` is answerable: sign those descendant rekeys and\n * resubmit with them carried.\n */\nexport type ContainerRotationResult =\n | { readonly ok: true; readonly data: ContainerRotationResponse }\n | {\n readonly ok: false;\n readonly code?: string | undefined;\n /** Surface a failure that was submitted with `reportErrors: false`. */\n readonly report?: (() => void) | undefined;\n readonly requiredContainerIds?: readonly string[] | undefined;\n readonly status: number | null;\n };\n\nexport interface ContainerMoveApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n moveContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n moveContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerRevokeApi extends ContainerReciteApi {\n evictContainerWriterProjection?(containerId: string): void;\n evictWriterProjectionsCiting?(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n revokeContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n revokeContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface CreateRemoteContainerResult {\n containerKey: Uint8Array;\n containerId: string;\n metadataDocumentId: string;\n plan: ContainerCreatePlan;\n response: ContainerMutationResponse;\n}\n\nexport interface ContainerSharePlan {\n body: ContainerGrantAccessEventBody;\n /** The unchanged epoch's stored keyring, echoed back by the server. */\n previousKeyring?: Record<string, unknown> | null | undefined;\n containerId: string;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n recipientTarget: ContainerKekRecipientTarget;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerSharePlan {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n}\n\nexport interface ContainerRevokePlan {\n body: ContainerRevokeAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRevokePlan {\n containerKey: Uint8Array;\n plan: ContainerRevokePlan;\n}\n\nexport interface ContainerRekeyPlan {\n body: ContainerRekeyAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRekeyPlan {\n containerKey: Uint8Array;\n plan: ContainerRekeyPlan;\n writerProjection: ContainerWriterProjectionResponse;\n}\n\nexport interface ContainerRekeyApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n rekeyContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; see DocumentSyncApi. */\n rekeyContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerMovePlan {\n body: ContainerMoveAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerMovePlan {\n containerKey: Uint8Array;\n plan: ContainerMovePlan;\n}\n\nexport interface BuildMaterializedContainerMovePlanInput {\n author: ContainerMutationAuthor;\n containerKeyEpochId?: string | undefined;\n destinationParentProjection: ContainerWriterProjectionResponse;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\nexport interface ParentContainerCreateContext {\n manifest: ContainerWriterProjectionResponse[\"path\"][number];\n kek: ContainerKekResponse;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerCreateAccessEventBody,\n ContainerDirectGrant,\n ContainerGrantAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKekKeyring,\n ContainerKekRecipientTarget,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerMoveAccessEventBody,\n ContainerRekeyAccessEventBody,\n ContainerRevokeAccessEventBody,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerCreateWithMetadataDocumentRequest,\n ContainerMutationRequest,\n ContainerRotationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerCreateWithMetadataDocumentResponse,\n ContainerKekResponse,\n ContainerMutationResponse,\n ContainerRotationResponse,\n ContainerShareResponse,\n ContainerWriterProjectionResponse,\n OrganizationReadModelDeltaResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { ContainerMutationRequestOptions } from \"./mutationRequestOptions\";\nimport type { ContainerReciteApi } from \"./reciteApi\";\n\nexport interface ContainerMutationAuthor {\n organizationId: string;\n signerDeviceId: string;\n signerKeyFingerprint: string;\n signerPrivateKey: Uint8Array;\n signerUserId: string;\n}\n\nexport interface BuildContainerCreatePlanInput {\n author: ContainerMutationAuthor;\n containerId?: string | undefined;\n containerKey: Uint8Array;\n containerKeyEpochId?: string | undefined;\n eventId?: string | undefined;\n /**\n * Optional group grant to bake into the\n * create manifest, wrapping the new container key to that principal in\n * addition to the normal parent-inheritance wrap. Used to birth a child\n * container that is directly readable by a group — e.g. the org public\n * metadata container granted to the reserved Members group. The principal's\n * verified policy must also be supplied via `principalPolicies` so the server\n * can derive the recipient target.\n */\n managedPrincipalGrant?:\n | {\n accessLevel: ContainerDirectGrant[\"accessLevel\"];\n principalEncapsulationPublicKey: string;\n principalHead: ContainerGrantPrincipalHead;\n }\n | undefined;\n metadataDocumentId?: string | undefined;\n systemSlot?: string | null | undefined;\n parentProjection: ContainerWriterProjectionResponse;\n principalPolicies?: readonly PrincipalPolicyCurrentEvidence[] | undefined;\n signedAt?: string | undefined;\n}\n\nexport interface ContainerCreatePlan {\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyEpochHash: string;\n keyTargetHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n metadataDocumentId: string;\n parentContainerId: string | null;\n parentManifestHash: string | null;\n recipientTargets: ContainerKekRecipientTarget[];\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerCreatePlan {\n containerKey: Uint8Array;\n plan: ContainerCreatePlan;\n}\n\nexport interface ContainerCreatePlanContext\n extends BuildContainerCreatePlanInput {\n containerKeyPublicKey: string;\n containerId: string;\n containerKeyEpochId: string;\n eventId: string;\n metadataDocumentId: string;\n parent: ParentContainerCreateContext;\n signedAt: string;\n}\n\nexport interface ContainerMutationSubmitFailure {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report: () => void;\n readonly stalePrincipalHeads?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n readonly status: number | null;\n}\n\nexport type ContainerMutationSubmitResult<T> =\n | {\n readonly data: T;\n readonly ok: true;\n }\n | ContainerMutationSubmitFailure;\n\nexport interface ContainerCreateApi {\n createContainerResult(\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n createContainerWithMetadataDocumentResult(\n input: ContainerCreateWithMetadataDocumentRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<\n ContainerMutationSubmitResult<ContainerCreateWithMetadataDocumentResponse>\n >;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport interface ContainerShareApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n shareContainer(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationResponse | null>;\n /** Tells a stale path, which a fresh projection clears, from a refusal. */\n shareContainerResult?(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerShareResponse>>;\n evictContainerWriterProjection?(containerId: string): void;\n}\n\n/**\n * Sends the organization read-model cursor a share holds, so its response can\n * carry the delta from it; the share settles the lease once it ends.\n */\nexport interface ContainerShareCommittedReadModel {\n begin(): Promise<{\n readonly heldCursor: string | undefined;\n settle(delta: OrganizationReadModelDeltaResponse | undefined): void;\n }>;\n}\n\n/**\n * A status-bearing rotation outcome. A refusal that names\n * `requiredContainerIds` is answerable: sign those descendant rekeys and\n * resubmit with them carried.\n */\nexport type ContainerRotationResult =\n | { readonly ok: true; readonly data: ContainerRotationResponse }\n | {\n readonly ok: false;\n readonly code?: string | undefined;\n /** Surface a failure that was submitted with `reportErrors: false`. */\n readonly report?: (() => void) | undefined;\n readonly requiredContainerIds?: readonly string[] | undefined;\n readonly status: number | null;\n };\n\nexport interface ContainerMoveApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n moveContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n moveContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerRevokeApi extends ContainerReciteApi {\n evictContainerWriterProjection?(containerId: string): void;\n evictWriterProjectionsCiting?(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n revokeContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n revokeContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface CreateRemoteContainerResult {\n containerKey: Uint8Array;\n containerId: string;\n metadataDocumentId: string;\n plan: ContainerCreatePlan;\n response: ContainerMutationResponse;\n}\n\nexport interface ContainerSharePlan {\n body: ContainerGrantAccessEventBody;\n /** The unchanged epoch's stored keyring, echoed back by the server. */\n previousKeyring?: Record<string, unknown> | null | undefined;\n containerId: string;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n recipientTarget: ContainerKekRecipientTarget;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerSharePlan {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n}\n\nexport interface ContainerRevokePlan {\n body: ContainerRevokeAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRevokePlan {\n containerKey: Uint8Array;\n plan: ContainerRevokePlan;\n}\n\nexport interface ContainerRekeyPlan {\n body: ContainerRekeyAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRekeyPlan {\n containerKey: Uint8Array;\n plan: ContainerRekeyPlan;\n writerProjection: ContainerWriterProjectionResponse;\n}\n\nexport interface ContainerRekeyApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n rekeyContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; see DocumentSyncApi. */\n rekeyContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerMovePlan {\n body: ContainerMoveAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerMovePlan {\n containerKey: Uint8Array;\n plan: ContainerMovePlan;\n}\n\nexport interface BuildMaterializedContainerMovePlanInput {\n author: ContainerMutationAuthor;\n containerKeyEpochId?: string | undefined;\n destinationParentProjection: ContainerWriterProjectionResponse;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\nexport interface ParentContainerCreateContext {\n manifest: ContainerWriterProjectionResponse[\"path\"][number];\n kek: ContainerKekResponse;\n}\n"]}
@@ -12,10 +12,7 @@ function newer(previous, next) {
12
12
  }
13
13
  function payloadsConflict(previous, payload) {
14
14
  return (!principalHeadMatchesReference(previous.reference, payload.reference) ||
15
- previous.payload.principalId !== payload.payload.principalId ||
16
- previous.payload.principalType !== payload.payload.principalType ||
17
- previous.payload.ciphertext !== payload.payload.ciphertext ||
18
- previous.payload.ciphertextHash !== payload.payload.ciphertextHash);
15
+ previous.payload.ciphertext !== payload.payload.ciphertext);
19
16
  }
20
17
  function keepNewestGroups(groups, candidates) {
21
18
  for (const group of candidates) {
@@ -1 +1 @@
1
- {"version":3,"file":"mergeProjectionPolicyEvidence.js","sourceRoot":"","sources":["mergeProjectionPolicyEvidence.ts"],"names":[],"mappings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G,MAAM,CAAC,MAAM,EAAE,CAAC;KAC7B,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyHistorySourceResponse,\n ProjectionPolicyEvidenceResponse,\n} from \"@tearleads/validators/response\";\nimport { principalHeadMatchesReference } from \"../../principalContracts/organizationAuthorityDescriptor\";\n\nfunction newer(\n previous: PrincipalPolicyHistorySourceResponse | null | undefined,\n next: PrincipalPolicyHistorySourceResponse,\n): boolean {\n if (!previous) return true;\n if (previous.head.principalId !== next.head.principalId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Projection evidence crosses principals\",\n );\n if (\n previous.head.version === next.head.version &&\n !principalHeadMatchesReference(previous.head, next.head)\n )\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Projection evidence contains conflicting heads\",\n );\n return previous.head.version < next.head.version;\n}\n\ntype OrganizationPayload =\n ProjectionPolicyEvidenceResponse[\"organizationPayloads\"][number];\n\nfunction payloadsConflict(\n previous: OrganizationPayload,\n payload: OrganizationPayload,\n): boolean {\n return (\n !principalHeadMatchesReference(previous.reference, payload.reference) ||\n previous.payload.principalId !== payload.payload.principalId ||\n previous.payload.principalType !== payload.payload.principalType ||\n previous.payload.ciphertext !== payload.payload.ciphertext ||\n previous.payload.ciphertextHash !== payload.payload.ciphertextHash\n );\n}\n\nfunction keepNewestGroups(\n groups: Map<string, PrincipalPolicyHistorySourceResponse>,\n candidates: readonly PrincipalPolicyHistorySourceResponse[],\n): void {\n for (const group of candidates) {\n const prior = groups.get(group.head.principalId);\n if (newer(prior, group)) groups.set(group.head.principalId, group);\n }\n}\n\n/** Combine proof material when locally composing projections; verification follows. */\nexport function mergeProjectionPolicyEvidence(\n evidence: readonly ProjectionPolicyEvidenceResponse[],\n): ProjectionPolicyEvidenceResponse {\n let directory: ProjectionPolicyEvidenceResponse | undefined;\n const groups = new Map<string, PrincipalPolicyHistorySourceResponse>();\n const payloads = new Map<string, OrganizationPayload>();\n for (const proof of evidence) {\n const organization = proof.organization;\n if (organization && newer(directory?.organization, organization))\n directory = proof;\n for (const payload of proof.organizationPayloads) {\n const previous = payloads.get(payload.reference.stateHash);\n if (previous && payloadsConflict(previous, payload))\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Projection evidence contains conflicting directory payloads\",\n );\n payloads.set(payload.reference.stateHash, payload);\n }\n keepNewestGroups(groups, proof.groups);\n }\n return {\n organization: directory?.organization ?? null,\n organizationPayloads: [...payloads.values()],\n groups: [...groups.values()],\n };\n}\n"]}
1
+ {"version":3,"file":"mergeProjectionPolicyEvidence.js","sourceRoot":"","sources":["mergeProjectionPolicyEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AAEzG,SAAS,KAAK,CACZ,QAAiE,EACjE,IAA0C;IAE1C,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC3B,IAAI,QAAQ,CAAC,IAAI,CAAC,WAAW,KAAK,IAAI,CAAC,IAAI,CAAC,WAAW;QACrD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,wCAAwC,CACzC,CAAC;IACJ,IACE,QAAQ,CAAC,IAAI,CAAC,OAAO,KAAK,IAAI,CAAC,IAAI,CAAC,OAAO;QAC3C,CAAC,6BAA6B,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC;QAExD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,gDAAgD,CACjD,CAAC;IACJ,OAAO,QAAQ,CAAC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC;AACnD,CAAC;AAKD,SAAS,gBAAgB,CACvB,QAA6B,EAC7B,OAA4B;IAE5B,OAAO,CACL,CAAC,6BAA6B,CAAC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,SAAS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AC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IACD,OAAO;QACL,YAAY,EAAE,SAAS,EAAE,YAAY,IAAI,IAAI;QAC7C,oBAAoB,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC;QAC5C,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC;KAC7B,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyHistorySourceResponse,\n ProjectionPolicyEvidenceResponse,\n} from \"@tearleads/validators/response\";\nimport { principalHeadMatchesReference } from \"../../principalContracts/organizationAuthorityDescriptor\";\n\nfunction newer(\n previous: PrincipalPolicyHistorySourceResponse | null | undefined,\n next: PrincipalPolicyHistorySourceResponse,\n): boolean {\n if (!previous) return true;\n if (previous.head.principalId !== next.head.principalId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Projection evidence crosses principals\",\n );\n if (\n previous.head.version === next.head.version &&\n !principalHeadMatchesReference(previous.head, next.head)\n )\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Projection evidence contains conflicting heads\",\n );\n return previous.head.version < next.head.version;\n}\n\ntype OrganizationPayload =\n ProjectionPolicyEvidenceResponse[\"organizationPayloads\"][number];\n\nfunction payloadsConflict(\n previous: OrganizationPayload,\n payload: OrganizationPayload,\n): boolean {\n return (\n !principalHeadMatchesReference(previous.reference, payload.reference) ||\n previous.payload.ciphertext !== payload.payload.ciphertext\n );\n}\n\nfunction keepNewestGroups(\n groups: Map<string, PrincipalPolicyHistorySourceResponse>,\n candidates: readonly PrincipalPolicyHistorySourceResponse[],\n): void {\n for (const group of candidates) {\n const prior = groups.get(group.head.principalId);\n if (newer(prior, group)) groups.set(group.head.principalId, group);\n }\n}\n\n/** Combine proof material when locally composing projections; verification follows. */\nexport function mergeProjectionPolicyEvidence(\n evidence: readonly ProjectionPolicyEvidenceResponse[],\n): ProjectionPolicyEvidenceResponse {\n let directory: ProjectionPolicyEvidenceResponse | undefined;\n const groups = new Map<string, PrincipalPolicyHistorySourceResponse>();\n const payloads = new Map<string, OrganizationPayload>();\n for (const proof of evidence) {\n const organization = proof.organization;\n if (organization && newer(directory?.organization, organization))\n directory = proof;\n for (const payload of proof.organizationPayloads) {\n const previous = payloads.get(payload.reference.stateHash);\n if (previous && payloadsConflict(previous, payload))\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Projection evidence contains conflicting directory payloads\",\n );\n payloads.set(payload.reference.stateHash, payload);\n }\n keepNewestGroups(groups, proof.groups);\n }\n return {\n organization: directory?.organization ?? null,\n organizationPayloads: [...payloads.values()],\n groups: [...groups.values()],\n };\n}\n"]}
@@ -90,12 +90,17 @@ export class OrganizationReadModelRepository {
90
90
  });
91
91
  // The requester prune also retires pruned users' usage projections.
92
92
  await ensureSqlTables(this.execSql, organizationAccessProjectionTables);
93
- const disposition = await getClientSQLitePersistenceRuntime(this.execSql).transaction((tx) => applyOrganizationReadModelResponseInTransaction(tx, {
93
+ const runtime = getClientSQLitePersistenceRuntime(this.execSql);
94
+ const apply = (tx) => applyOrganizationReadModelResponseInTransaction(tx, {
94
95
  currentUserId: input.currentUserId,
95
96
  now: this.now,
96
97
  requestedCursor: input.requestedCursor,
97
98
  response: input.response,
98
- }));
99
+ });
100
+ const disposition = input.canCommit
101
+ ? ((await runtime.guardedTransaction(apply, input.canCommit)).result ??
102
+ "stale")
103
+ : await runtime.transaction(apply);
99
104
  // An applied change follows an organization hint or mutation; in-flight
100
105
  // operations recover the directory again instead of reusing their memo.
101
106
  if (disposition === "applied")
@@ -147,6 +152,19 @@ export class OrganizationReadModelRepository {
147
152
  // the organization's directory again instead of reusing their memo.
148
153
  getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(input.organizationId);
149
154
  }
155
+ /**
156
+ * The organization's stored projection cursor, shared by every requester on
157
+ * this device: the cursor a reconcile requests from. Null without one.
158
+ */
159
+ async loadOrganizationReadModelCursor(organizationId) {
160
+ await ensureSqlTables(this.execSql, organizationReadModelTables);
161
+ const [row] = await getClientSQLitePersistenceRuntime(this.execSql)
162
+ .db.select({ cursor: organizationReadModelState.cursor })
163
+ .from(organizationReadModelState)
164
+ .where(eq(organizationReadModelState.organizationId, organizationId))
165
+ .limit(1);
166
+ return row?.cursor ?? null;
167
+ }
150
168
  /**
151
169
  * The cursor this requester has applied, or null when it holds none. The
152
170
  * organization row's cursor is shared: another identity on this device may
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReadModelRepository.js","sourceRoot":"","sources":["organizationReadModelRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,qCAAqC,EAAE,MAAM,6CAA6C,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,2BAA2B,EAAE,MAAM,iDAAiD,CAAC;AAC9F,OAAO,EACL,+BAA+B,EAC/B,2BAA2B,EAC3B,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,iDAAiD,EAAE,MAAM,oCAAoC,CAAC;AAKvG,OAAO,EAAE,sCAAsC,EAAE,MAAM,qCAAqC,CAAC;AAC7F,OAAO,EACL,2DAA2D,GAE5D,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAEL,+CAA+C,GAChD,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,gDAAgD,GAEjD,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EAAE,iDAAiD,EAAE,MAAM,8BAA8B,CAAC;AACjG,OAAO,EAAE,mCAAmC,EAAE,MA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CAAC;oBAClB,MAAM,EAAE;wBACN,+BAA+B,CAAC,cAAc;wBAC9C,+BAA+B,CAAC,eAAe;wBAC/C,+BAA+B,CAAC,UAAU;qBAC3C;oBACD,GAAG,EAAE,EAAE,QAAQ,EAAE;iBAClB,CAAC;qBACD,GAAG,EAAE,CAAC;YACX,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,iCAAiC,CACrC,KAA0C,EAC1C,UAAoD;QAEpD,MAAM,eAAe,CAAC,IAAI,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;QACjE,MAAM,IAAI,GAAG,MAAM,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC;aAC/D,EAAE,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,+BAA+B,CAAC,UAAU,EAAE,CAAC;aACrE,IAAI,CAAC,+BAA+B,CAAC;aACrC,KAAK,CACJ,GAAG,CACD,EAAE,CACA,+BAA+B,CAAC,cAAc,EAC9C,KAAK,CAAC,cAAc,CACrB,EACD,EAAE,CACA,+BAA+B,CAAC,eAAe,EAC/C,KAAK,CAAC,eAAe,CACtB,EACD,EAAE,CAAC,+BAA+B,CAAC,UAAU,EAAE,UAAU,CAAC,CAC3D,CACF;aACA,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;IACzB,CAAC;CACF","sourcesContent":["import type { OrganizationReadModelResponse } from \"@tearleads/validators/response\";\nimport { and, eq } from \"drizzle-orm\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../principals/principalPolicyCoordinator\";\nimport { organizationReadModelTables } from \"../../sqlite/schema\";\nimport { organizationDataUsageTables } from \"../../sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { purgeOrganizationDataUsageProjectionInTransaction } from \"./organizationDataUsagePersistence\";\nimport type {\n OrganizationPresentationDenialProjection,\n OrganizationPresentationDenialScope,\n} from \"./organizationPresentationDenialPersistence\";\nimport { notifyOrganizationReadModelInvalidated } from \"./organizationReadModelInvalidation\";\nimport {\n loadRequesterOrganizationReadModelGroupMembersInTransaction,\n type OrganizationReadModelGroupMembers,\n} from \"./organizationReadModelMemberLoad\";\nimport {\n type ApplyOrganizationReadModelResponseResult,\n applyOrganizationReadModelResponseInTransaction,\n} from \"./organizationReadModelPersistence\";\nimport {\n loadOrganizationReadModelProjectionInTransaction,\n type OrganizationReadModelProjection,\n} from \"./organizationReadModelProjection\";\nimport { OrganizationReadModelIntegrityError } from \"./organizationReadModelProtocol\";\nimport { purgeOrganizationReadModelProjectionInTransaction } from \"./organizationReadModelPurge\";\nimport { assertOrganizationReadModelResponse } from \"./organizationReadModelResponseAssertions\";\n\nconst organizationAccessProjectionTables = [\n ...organizationReadModelTables,\n ...organizationDataUsageTables,\n];\n\n/**\n * The durable organization read-model projection, its group display names,\n * and its presentation denial markers, over one database. Invalidation\n * notices and recovery invalidation are keyed by the executor this\n * repository was built from.\n */\nexport class OrganizationReadModelRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n /**\n * The ONE load shell for the durable read-model projection: run `load` in a\n * transaction and, if a stored row fails integrity validation, purge the\n * organization's projection and report null. The projection is a\n * server-refetchable cache, so the next reconcile requests a cursorless\n * snapshot instead of every read and repair pass failing on the same row.\n */\n private async loadWithOrganizationReadModelIntegrityPurge<T>(input: {\n readonly load: (tx: ClientSQLiteTransactionScope) => Promise<T | null>;\n readonly organizationId: string;\n }): Promise<T | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n let purgedInvalidRows = false;\n const result = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).transaction(async (tx) => {\n try {\n return await input.load(tx);\n } catch (error) {\n if (!(error instanceof OrganizationReadModelIntegrityError)) {\n throw error;\n }\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n purgedInvalidRows = true;\n return null;\n }\n });\n if (purgedInvalidRows) {\n // Realtime consumers may hold a caught-up lease over rows that no longer\n // exist; the notification lets them drop it and refetch authoritatively.\n notifyOrganizationReadModelInvalidated(\n this.execSql,\n input.organizationId,\n );\n }\n return result;\n }\n\n async loadOrganizationReadModelProjection(\n organizationId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelProjection | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadOrganizationReadModelProjectionInTransaction({\n currentUserId,\n organizationId,\n tx,\n }),\n });\n }\n\n async loadOrganizationReadModelGroupMembers(\n organizationId: string,\n groupId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelGroupMembers | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadRequesterOrganizationReadModelGroupMembersInTransaction(tx, {\n currentUserId,\n groupId,\n organizationId,\n }),\n });\n }\n\n async applyOrganizationReadModelResponse(input: {\n readonly currentUserId: string;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n }): Promise<ApplyOrganizationReadModelResponseResult> {\n assertOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n response: input.response,\n });\n // The requester prune also retires pruned users' usage projections.\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n\n const disposition = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).transaction(\n (tx): Promise<ApplyOrganizationReadModelResponseResult> =>\n applyOrganizationReadModelResponseInTransaction(tx, {\n currentUserId: input.currentUserId,\n now: this.now,\n requestedCursor: input.requestedCursor,\n response: input.response,\n }),\n );\n // An applied change follows an organization hint or mutation; in-flight\n // operations recover the directory again instead of reusing their memo.\n if (disposition === \"applied\")\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.response.organizationId,\n );\n return disposition;\n }\n\n async purgeOrganizationReadModelProjection(\n organizationId: string,\n options: { readonly onlyRequesterUserId?: string } = {},\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await purgeOrganizationReadModelProjectionInTransaction({\n onlyRequesterUserId: options.onlyRequesterUserId,\n organizationId,\n tx,\n });\n },\n );\n }\n\n /**\n * Purge one requester's access to an organization's presentation projections\n * after the server denied that requester. The denial is requester-scoped: the\n * shared read-model rows stay while another local identity in the same\n * database still holds a requester row, and organization-wide rows fall with\n * the last requester.\n */\n async purgeOrganizationAccessProjection(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await tx\n .delete(organizationReadModelRequesters)\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .run();\n const [remainingRequester] = await tx\n .select({ userId: organizationReadModelRequesters.userId })\n .from(organizationReadModelRequesters)\n .where(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n )\n .limit(1);\n if (!remainingRequester) {\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n }\n await purgeOrganizationDataUsageProjectionInTransaction({\n organizationId: input.organizationId,\n requesterUserId: input.requesterUserId,\n tx,\n });\n },\n );\n // A denial is a realtime-hinted access change: in-flight operations recover\n // the organization's directory again instead of reusing their memo.\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.organizationId,\n );\n }\n\n /**\n * The cursor this requester has applied, or null when it holds none. The\n * organization row's cursor is shared: another identity on this device may\n * have advanced it while this requester's own fields (for example\n * `isOrgAdmin`) still reflect an older response. Only the requester's own\n * applied cursor, while it is still the stored projection's cursor, proves\n * this requester is current. Realtime hints compare against it so a hint for\n * a cursor already applied costs no read.\n */\n async loadAppliedOrganizationReadModelCursor(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<string | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const [row] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ cursor: organizationReadModelRequesters.appliedCursor })\n .from(organizationReadModelRequesters)\n .innerJoin(\n organizationReadModelState,\n and(\n eq(\n organizationReadModelState.organizationId,\n organizationReadModelRequesters.organizationId,\n ),\n eq(\n organizationReadModelState.cursor,\n organizationReadModelRequesters.appliedCursor,\n ),\n ),\n )\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .limit(1);\n return row?.cursor ?? null;\n }\n\n /**\n * Every locally projected organization's pointer to its organization_profile\n * document, keyed by organization id.\n *\n * This is the only container-independent handle on that document. Callers\n * that need an org's display name from local state cannot rely on where the\n * document is linked: the provisioner writes it under a deterministic local\n * alias into the organization-metadata container, while a device that only\n * *synced* it (identity recovery, another member) keys it under the server\n * documentId in whichever container the grant arrived through.\n *\n * The local schema stores only the current read-model contract, so every\n * state row is eligible to provide its profile-document pointer.\n */\n async loadOrganizationProfileDocumentIds(): Promise<Map<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n organizationId: organizationReadModelState.organizationId,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n })\n .from(organizationReadModelState);\n\n return new Map(\n rows.flatMap((row) =>\n row.profileDocumentId\n ? [[row.organizationId, row.profileDocumentId]]\n : [],\n ),\n );\n }\n\n async loadOrganizationGroupDisplayNames(\n organizationId: string,\n ): Promise<ReadonlyMap<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n groupId: organizationReadModelGroups.groupId,\n name: organizationReadModelGroups.name,\n })\n .from(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, organizationId));\n return new Map(\n rows\n .filter((row) => row.name.length > 0)\n .map((row) => [row.groupId, row.name]),\n );\n }\n\n /** Local display cache only: these labels never enter a server request. */\n async saveOrganizationGroupDisplayNames(input: {\n organizationId: string;\n names: readonly { groupId: string; name: string; stateHash: string }[];\n stillCurrent: () => boolean;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(\n async (tx) => {\n for (const group of input.names) {\n await tx\n .update(organizationReadModelGroups)\n .set({ name: group.name })\n .where(\n and(\n eq(\n organizationReadModelGroups.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelGroups.groupId, group.groupId),\n eq(organizationReadModelGroups.stateHash, group.stateHash),\n ),\n )\n .run();\n }\n },\n input.stillCurrent,\n );\n }\n\n /**\n * Durably record a server denial before the revoked projection rows are\n * purged. The marker is what keeps a failed purge plus an offline restart\n * from serving the revoked projection; it is cleared only when an\n * authoritative reconcile stores fresh server state for the same scope.\n */\n async recordOrganizationPresentationDenials(\n scope: OrganizationPresentationDenialScope,\n projections: readonly OrganizationPresentationDenialProjection[],\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const deniedAt = this.now().toISOString();\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n for (const projection of new Set(projections)) {\n await tx\n .insert(organizationPresentationDenials)\n .values({\n organizationId: scope.organizationId,\n requesterUserId: scope.requesterUserId,\n projection,\n deniedAt,\n })\n .onConflictDoUpdate({\n target: [\n organizationPresentationDenials.organizationId,\n organizationPresentationDenials.requesterUserId,\n organizationPresentationDenials.projection,\n ],\n set: { deniedAt },\n })\n .run();\n }\n },\n );\n }\n\n async hasOrganizationPresentationDenial(\n scope: OrganizationPresentationDenialScope,\n projection: OrganizationPresentationDenialProjection,\n ): Promise<boolean> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ projection: organizationPresentationDenials.projection })\n .from(organizationPresentationDenials)\n .where(\n and(\n eq(\n organizationPresentationDenials.organizationId,\n scope.organizationId,\n ),\n eq(\n organizationPresentationDenials.requesterUserId,\n scope.requesterUserId,\n ),\n eq(organizationPresentationDenials.projection, projection),\n ),\n )\n .limit(1);\n return rows.length > 0;\n }\n}\n"]}
1
+ {"version":3,"file":"organizationReadModelRepository.js","sourceRoot":"","sources":["organizationReadModelRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,qCAAqC,EAAE,MAAM,6CAA6C,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,2BAA2B,EAAE,MAAM,iDAAiD,CAAC;AAC9F,OAAO,EACL,+BAA+B,EAC/B,2BAA2B,EAC3B,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,iDAAiD,EAAE,MAAM,oCAAoC,CAAC;AAKvG,OAAO,EAAE,sCAAsC,EAAE,MAAM,qCAAqC,CAAC;AAC7F,OAAO,EACL,2DAA2D,GAE5D,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAEL,+CAA+C,GAChD,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,gDAAgD,GAEjD,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,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AAO,CAAC;aAC/D,EAAE,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,+BAA+B,CAAC,UAAU,EAAE,CAAC;aACrE,IAAI,CAAC,+BAA+B,CAAC;aACrC,KAAK,CACJ,GAAG,CACD,EAAE,CACA,+BAA+B,CAAC,cAAc,EAC9C,KAAK,CAAC,cAAc,CACrB,EACD,EAAE,CACA,+BAA+B,CAAC,eAAe,EAC/C,KAAK,CAAC,eAAe,CACtB,EACD,EAAE,CAAC,+BAA+B,CAAC,UAAU,EAAE,UAAU,CAAC,CAC3D,CACF;aACA,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;IACzB,CAAC;CACF","sourcesContent":["import type { OrganizationReadModelResponse } from \"@tearleads/validators/response\";\nimport { and, eq } from \"drizzle-orm\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../principals/principalPolicyCoordinator\";\nimport { organizationReadModelTables } from \"../../sqlite/schema\";\nimport { organizationDataUsageTables } from \"../../sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { purgeOrganizationDataUsageProjectionInTransaction } from \"./organizationDataUsagePersistence\";\nimport type {\n OrganizationPresentationDenialProjection,\n OrganizationPresentationDenialScope,\n} from \"./organizationPresentationDenialPersistence\";\nimport { notifyOrganizationReadModelInvalidated } from \"./organizationReadModelInvalidation\";\nimport {\n loadRequesterOrganizationReadModelGroupMembersInTransaction,\n type OrganizationReadModelGroupMembers,\n} from \"./organizationReadModelMemberLoad\";\nimport {\n type ApplyOrganizationReadModelResponseResult,\n applyOrganizationReadModelResponseInTransaction,\n} from \"./organizationReadModelPersistence\";\nimport {\n loadOrganizationReadModelProjectionInTransaction,\n type OrganizationReadModelProjection,\n} from \"./organizationReadModelProjection\";\nimport { OrganizationReadModelIntegrityError } from \"./organizationReadModelProtocol\";\nimport { purgeOrganizationReadModelProjectionInTransaction } from \"./organizationReadModelPurge\";\nimport { assertOrganizationReadModelResponse } from \"./organizationReadModelResponseAssertions\";\n\nconst organizationAccessProjectionTables = [\n ...organizationReadModelTables,\n ...organizationDataUsageTables,\n];\n\n/**\n * The durable organization read-model projection, its group display names,\n * and its presentation denial markers, over one database. Invalidation\n * notices and recovery invalidation are keyed by the executor this\n * repository was built from.\n */\nexport class OrganizationReadModelRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n /**\n * The ONE load shell for the durable read-model projection: run `load` in a\n * transaction and, if a stored row fails integrity validation, purge the\n * organization's projection and report null. The projection is a\n * server-refetchable cache, so the next reconcile requests a cursorless\n * snapshot instead of every read and repair pass failing on the same row.\n */\n private async loadWithOrganizationReadModelIntegrityPurge<T>(input: {\n readonly load: (tx: ClientSQLiteTransactionScope) => Promise<T | null>;\n readonly organizationId: string;\n }): Promise<T | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n let purgedInvalidRows = false;\n const result = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).transaction(async (tx) => {\n try {\n return await input.load(tx);\n } catch (error) {\n if (!(error instanceof OrganizationReadModelIntegrityError)) {\n throw error;\n }\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n purgedInvalidRows = true;\n return null;\n }\n });\n if (purgedInvalidRows) {\n // Realtime consumers may hold a caught-up lease over rows that no longer\n // exist; the notification lets them drop it and refetch authoritatively.\n notifyOrganizationReadModelInvalidated(\n this.execSql,\n input.organizationId,\n );\n }\n return result;\n }\n\n async loadOrganizationReadModelProjection(\n organizationId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelProjection | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadOrganizationReadModelProjectionInTransaction({\n currentUserId,\n organizationId,\n tx,\n }),\n });\n }\n\n async loadOrganizationReadModelGroupMembers(\n organizationId: string,\n groupId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelGroupMembers | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadRequesterOrganizationReadModelGroupMembersInTransaction(tx, {\n currentUserId,\n groupId,\n organizationId,\n }),\n });\n }\n\n async applyOrganizationReadModelResponse(input: {\n /** Checked in the commit's own synchronous slice; refused rolls back. */\n readonly canCommit?: (() => boolean) | undefined;\n readonly currentUserId: string;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n }): Promise<ApplyOrganizationReadModelResponseResult> {\n assertOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n response: input.response,\n });\n // The requester prune also retires pruned users' usage projections.\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const apply = (\n tx: Parameters<Parameters<typeof runtime.transaction>[0]>[0],\n ): Promise<ApplyOrganizationReadModelResponseResult> =>\n applyOrganizationReadModelResponseInTransaction(tx, {\n currentUserId: input.currentUserId,\n now: this.now,\n requestedCursor: input.requestedCursor,\n response: input.response,\n });\n const disposition = input.canCommit\n ? ((await runtime.guardedTransaction(apply, input.canCommit)).result ??\n \"stale\")\n : await runtime.transaction(apply);\n // An applied change follows an organization hint or mutation; in-flight\n // operations recover the directory again instead of reusing their memo.\n if (disposition === \"applied\")\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.response.organizationId,\n );\n return disposition;\n }\n\n async purgeOrganizationReadModelProjection(\n organizationId: string,\n options: { readonly onlyRequesterUserId?: string } = {},\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await purgeOrganizationReadModelProjectionInTransaction({\n onlyRequesterUserId: options.onlyRequesterUserId,\n organizationId,\n tx,\n });\n },\n );\n }\n\n /**\n * Purge one requester's access to an organization's presentation projections\n * after the server denied that requester. The denial is requester-scoped: the\n * shared read-model rows stay while another local identity in the same\n * database still holds a requester row, and organization-wide rows fall with\n * the last requester.\n */\n async purgeOrganizationAccessProjection(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await tx\n .delete(organizationReadModelRequesters)\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .run();\n const [remainingRequester] = await tx\n .select({ userId: organizationReadModelRequesters.userId })\n .from(organizationReadModelRequesters)\n .where(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n )\n .limit(1);\n if (!remainingRequester) {\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n }\n await purgeOrganizationDataUsageProjectionInTransaction({\n organizationId: input.organizationId,\n requesterUserId: input.requesterUserId,\n tx,\n });\n },\n );\n // A denial is a realtime-hinted access change: in-flight operations recover\n // the organization's directory again instead of reusing their memo.\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.organizationId,\n );\n }\n\n /**\n * The organization's stored projection cursor, shared by every requester on\n * this device: the cursor a reconcile requests from. Null without one.\n */\n async loadOrganizationReadModelCursor(\n organizationId: string,\n ): Promise<string | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const [row] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ cursor: organizationReadModelState.cursor })\n .from(organizationReadModelState)\n .where(eq(organizationReadModelState.organizationId, organizationId))\n .limit(1);\n return row?.cursor ?? null;\n }\n\n /**\n * The cursor this requester has applied, or null when it holds none. The\n * organization row's cursor is shared: another identity on this device may\n * have advanced it while this requester's own fields (for example\n * `isOrgAdmin`) still reflect an older response. Only the requester's own\n * applied cursor, while it is still the stored projection's cursor, proves\n * this requester is current. Realtime hints compare against it so a hint for\n * a cursor already applied costs no read.\n */\n async loadAppliedOrganizationReadModelCursor(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<string | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const [row] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ cursor: organizationReadModelRequesters.appliedCursor })\n .from(organizationReadModelRequesters)\n .innerJoin(\n organizationReadModelState,\n and(\n eq(\n organizationReadModelState.organizationId,\n organizationReadModelRequesters.organizationId,\n ),\n eq(\n organizationReadModelState.cursor,\n organizationReadModelRequesters.appliedCursor,\n ),\n ),\n )\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .limit(1);\n return row?.cursor ?? null;\n }\n\n /**\n * Every locally projected organization's pointer to its organization_profile\n * document, keyed by organization id.\n *\n * This is the only container-independent handle on that document. Callers\n * that need an org's display name from local state cannot rely on where the\n * document is linked: the provisioner writes it under a deterministic local\n * alias into the organization-metadata container, while a device that only\n * *synced* it (identity recovery, another member) keys it under the server\n * documentId in whichever container the grant arrived through.\n *\n * The local schema stores only the current read-model contract, so every\n * state row is eligible to provide its profile-document pointer.\n */\n async loadOrganizationProfileDocumentIds(): Promise<Map<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n organizationId: organizationReadModelState.organizationId,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n })\n .from(organizationReadModelState);\n\n return new Map(\n rows.flatMap((row) =>\n row.profileDocumentId\n ? [[row.organizationId, row.profileDocumentId]]\n : [],\n ),\n );\n }\n\n async loadOrganizationGroupDisplayNames(\n organizationId: string,\n ): Promise<ReadonlyMap<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n groupId: organizationReadModelGroups.groupId,\n name: organizationReadModelGroups.name,\n })\n .from(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, organizationId));\n return new Map(\n rows\n .filter((row) => row.name.length > 0)\n .map((row) => [row.groupId, row.name]),\n );\n }\n\n /** Local display cache only: these labels never enter a server request. */\n async saveOrganizationGroupDisplayNames(input: {\n organizationId: string;\n names: readonly { groupId: string; name: string; stateHash: string }[];\n stillCurrent: () => boolean;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(\n async (tx) => {\n for (const group of input.names) {\n await tx\n .update(organizationReadModelGroups)\n .set({ name: group.name })\n .where(\n and(\n eq(\n organizationReadModelGroups.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelGroups.groupId, group.groupId),\n eq(organizationReadModelGroups.stateHash, group.stateHash),\n ),\n )\n .run();\n }\n },\n input.stillCurrent,\n );\n }\n\n /**\n * Durably record a server denial before the revoked projection rows are\n * purged. The marker is what keeps a failed purge plus an offline restart\n * from serving the revoked projection; it is cleared only when an\n * authoritative reconcile stores fresh server state for the same scope.\n */\n async recordOrganizationPresentationDenials(\n scope: OrganizationPresentationDenialScope,\n projections: readonly OrganizationPresentationDenialProjection[],\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const deniedAt = this.now().toISOString();\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n for (const projection of new Set(projections)) {\n await tx\n .insert(organizationPresentationDenials)\n .values({\n organizationId: scope.organizationId,\n requesterUserId: scope.requesterUserId,\n projection,\n deniedAt,\n })\n .onConflictDoUpdate({\n target: [\n organizationPresentationDenials.organizationId,\n organizationPresentationDenials.requesterUserId,\n organizationPresentationDenials.projection,\n ],\n set: { deniedAt },\n })\n .run();\n }\n },\n );\n }\n\n async hasOrganizationPresentationDenial(\n scope: OrganizationPresentationDenialScope,\n projection: OrganizationPresentationDenialProjection,\n ): Promise<boolean> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ projection: organizationPresentationDenials.projection })\n .from(organizationPresentationDenials)\n .where(\n and(\n eq(\n organizationPresentationDenials.organizationId,\n scope.organizationId,\n ),\n eq(\n organizationPresentationDenials.requesterUserId,\n scope.requesterUserId,\n ),\n eq(organizationPresentationDenials.projection, projection),\n ),\n )\n .limit(1);\n return rows.length > 0;\n }\n}\n"]}
@@ -34,7 +34,12 @@ export async function heldDirectoryCitations(execSql, organizationId) {
34
34
  directoryState.stateHash === row.stateHash &&
35
35
  directoryState.principalType === "organization" &&
36
36
  directoryState.principalId === organizationId)
37
- citations.push({ directoryState, directoryPayload });
37
+ // Only the ciphertext travels on: a payload cached before #2903 P23
38
+ // also carries fields that no reader uses.
39
+ citations.push({
40
+ directoryState,
41
+ directoryPayload: { ciphertext: directoryPayload.ciphertext },
42
+ });
38
43
  }
39
44
  return citations;
40
45
  }
@@ -1 +1 @@
1
- {"version":3,"file":"heldOrganizationDirectories.js","sourceRoot":"","sources":["heldOrganizationDirectories.ts"],"names":[],"mappings":"AACA,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,sBAAsB,EAAE,MAAM,2CAA2C,CAAC;AACnF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAG/C,SAAS,MAAM,CAAC,IAAY;IAC1B,IAAI,CAAC;QACH,OAAO,IAAI,CA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,sBAAsB,CAAC,aAAa,EAAE,cAAc,CAAC,EACxD,EAAE,CAAC,sBAAsB,CAAC,WAAW,EAAE,cAAc,CAAC,CACvD,CACF;SACA,OAAO,CACN,IAAI,CAAC,sBAAsB,CAAC,SAAS,CAAC,EACtC,IAAI,CAAC,sBAAsB,CAAC,SAAS,CAAC,EACtC,GAAG,CAAC,sBAAsB,CAAC,SAAS,CAAC,CACtC;SACA,KAAK,CAAC,0BAA0B,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import type { HeldDirectoryCitation } from \"@tearleads/api-client\";\nimport {\n isPrincipalStatePayloadResponse,\n isPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { KNOWN_DIRECTORY_HINT_LIMIT } from \"@tearleads/validators/util\";\nimport { and, asc, desc, eq } from \"drizzle-orm\";\nimport { principalPolicyBundles } from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteDatabase,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nfunction parsed(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\n/**\n * The organization directory payloads this device holds in its verified\n * policy bundles, its current state first, at most\n * `KNOWN_DIRECTORY_HINT_LIMIT`. Each travels with its signed state: the\n * request cites a payload only when its bytes hash to that state's\n * `payloadCiphertextHash`, so a refill is exactly the bytes the server would\n * send.\n */\nexport async function heldDirectoryCitations(\n execSql: ExecSql,\n organizationId: string,\n): Promise<HeldDirectoryCitation[]> {\n // Citing only saves bytes: a device that has stored no policy bundle yet\n // (so no table) or cannot read them cites no directory.\n const rows = await heldDirectoryRows(\n getClientSQLitePersistenceRuntime(execSql).db,\n organizationId,\n ).catch(() => []);\n const citations: HeldDirectoryCitation[] = [];\n for (const row of rows) {\n const directoryState = parsed(row.stateJson);\n const directoryPayload = parsed(row.payloadJson);\n // A row must name its own state of this organization, so a request\n // never cites another organization's state hash.\n if (\n isPrincipalStateResponse(directoryState) &&\n isPrincipalStatePayloadResponse(directoryPayload) &&\n directoryState.stateHash === row.stateHash &&\n directoryState.principalType === \"organization\" &&\n directoryState.principalId === organizationId\n )\n citations.push({ directoryState, directoryPayload });\n }\n return citations;\n}\n\nfunction heldDirectoryRows(db: ClientSQLiteDatabase, organizationId: string) {\n return db\n .select({\n stateHash: principalPolicyBundles.stateHash,\n stateJson: principalPolicyBundles.currentStateJson,\n payloadJson: principalPolicyBundles.currentPayloadJson,\n })\n .from(principalPolicyBundles)\n .where(\n and(\n eq(principalPolicyBundles.principalType, \"organization\"),\n eq(principalPolicyBundles.principalId, organizationId),\n ),\n )\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n desc(principalPolicyBundles.updatedAt),\n asc(principalPolicyBundles.stateHash),\n )\n .limit(KNOWN_DIRECTORY_HINT_LIMIT);\n}\n"]}
1
+ {"version":3,"file":"heldOrganizationDirectories.js","sourceRoot":"","sources":["heldOrganizationDirectories.ts"],"names":[],"mappings":"AACA,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,sBAAsB,EAAE,MAAM,2CAA2C,CAAC;AACnF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAG/C,SAAS,MAAM,CAAC,IAAY;IAC1B,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,OAAgB,EAChB,cAAsB;IAEtB,yEAAyE;IACzE,wDAAwD;I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CAAC,SAAS,CAAC,EACtC,IAAI,CAAC,sBAAsB,CAAC,SAAS,CAAC,EACtC,GAAG,CAAC,sBAAsB,CAAC,SAAS,CAAC,CACtC;SACA,KAAK,CAAC,0BAA0B,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import type { HeldDirectoryCitation } from \"@tearleads/api-client\";\nimport {\n isPrincipalStatePayloadResponse,\n isPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { KNOWN_DIRECTORY_HINT_LIMIT } from \"@tearleads/validators/util\";\nimport { and, asc, desc, eq } from \"drizzle-orm\";\nimport { principalPolicyBundles } from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteDatabase,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nfunction parsed(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\n/**\n * The organization directory payloads this device holds in its verified\n * policy bundles, its current state first, at most\n * `KNOWN_DIRECTORY_HINT_LIMIT`. Each travels with its signed state: the\n * request cites a payload only when its bytes hash to that state's\n * `payloadCiphertextHash`, so a refill is exactly the bytes the server would\n * send.\n */\nexport async function heldDirectoryCitations(\n execSql: ExecSql,\n organizationId: string,\n): Promise<HeldDirectoryCitation[]> {\n // Citing only saves bytes: a device that has stored no policy bundle yet\n // (so no table) or cannot read them cites no directory.\n const rows = await heldDirectoryRows(\n getClientSQLitePersistenceRuntime(execSql).db,\n organizationId,\n ).catch(() => []);\n const citations: HeldDirectoryCitation[] = [];\n for (const row of rows) {\n const directoryState = parsed(row.stateJson);\n const directoryPayload = parsed(row.payloadJson);\n // A row must name its own state of this organization, so a request\n // never cites another organization's state hash.\n if (\n isPrincipalStateResponse(directoryState) &&\n isPrincipalStatePayloadResponse(directoryPayload) &&\n directoryState.stateHash === row.stateHash &&\n directoryState.principalType === \"organization\" &&\n directoryState.principalId === organizationId\n )\n // Only the ciphertext travels on: a payload cached before #2903 P23\n // also carries fields that no reader uses.\n citations.push({\n directoryState,\n directoryPayload: { ciphertext: directoryPayload.ciphertext },\n });\n }\n return citations;\n}\n\nfunction heldDirectoryRows(db: ClientSQLiteDatabase, organizationId: string) {\n return db\n .select({\n stateHash: principalPolicyBundles.stateHash,\n stateJson: principalPolicyBundles.currentStateJson,\n payloadJson: principalPolicyBundles.currentPayloadJson,\n })\n .from(principalPolicyBundles)\n .where(\n and(\n eq(principalPolicyBundles.principalType, \"organization\"),\n eq(principalPolicyBundles.principalId, organizationId),\n ),\n )\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n desc(principalPolicyBundles.updatedAt),\n asc(principalPolicyBundles.stateHash),\n )\n .limit(KNOWN_DIRECTORY_HINT_LIMIT);\n}\n"]}
@@ -22,7 +22,7 @@ function securityContent(bundle) {
22
22
  ...bundle.currentMemberEnvelopes,
23
23
  envelopes: [...bundle.currentMemberEnvelopes.envelopes].sort((a, b) => compareCanonicalStrings(canonical(a), canonical(b))),
24
24
  },
25
- currentPayload: withoutCreatedAt(bundle.currentPayload),
25
+ currentPayload: { ciphertext: bundle.currentPayload.ciphertext },
26
26
  currentProjection: normalizePrincipalProjectionMembers(bundle.currentProjection),
27
27
  currentGrants: normalizePrincipalContainerGrants(bundle.currentGrants),
28
28
  currentState: withoutCreatedAt(bundle.currentState),
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyBundleIntegrity.js","sourceRoot":"","sources":["principalPolicyBundleIntegrity.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,GACpC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAEL,mCAAmC,GACpC,MAAM,+BAA+B,CAAC;AAEvC,SAAS,WAAW,CAClB,GAAoC;IAEp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AAK,CAAC,KAAK,CAAC;SACrC,CAAC,CAAC;KACJ,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,mCAAmC,CACjD,MAAuC,EACvC,QAAyC;IAEzC,IAAI,CAAC;QACH,IACE,SAAS,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;YAC/C,SAAS,CAAC,eAAe,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC,EACjD,CAAC;YACD,OAAO;QACT,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,2EAA2E;QAC3E,2EAA2E;IAC7E,CAAC;IACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,mFAAmF,CACpF,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\nimport {\n type StoredPrincipalPolicyBundleJson,\n storedPrincipalPolicyBundleFromJson,\n} from \"./storedPrincipalPolicyBundle\";\n\nfunction parseBundle(\n row: StoredPrincipalPolicyBundleJson,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n return bundle;\n}\n\nfunction canonical(value: unknown): string {\n return canonicalKeyingJsonString(\n value,\n \"principal policy bundle security content\",\n );\n}\n\nfunction withoutCreatedAt<T extends { readonly createdAt: string }>(\n value: T,\n): Omit<T, \"createdAt\"> {\n const { createdAt: _createdAt, ...content } = value;\n return content;\n}\n\nfunction securityContent(bundle: PrincipalPolicyBundleResponse) {\n return {\n currentMemberEnvelopes: {\n ...bundle.currentMemberEnvelopes,\n envelopes: [...bundle.currentMemberEnvelopes.envelopes].sort((a, b) =>\n compareCanonicalStrings(canonical(a), canonical(b)),\n ),\n },\n currentPayload: withoutCreatedAt(bundle.currentPayload),\n currentProjection: normalizePrincipalProjectionMembers(\n bundle.currentProjection,\n ),\n currentGrants: normalizePrincipalContainerGrants(bundle.currentGrants),\n currentState: withoutCreatedAt(bundle.currentState),\n previousStates: bundle.previousStates.map((entry) => ({\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n state: withoutCreatedAt(entry.state),\n })),\n };\n}\n\nexport function assertSameHeadPrincipalPolicyBundle(\n stored: StoredPrincipalPolicyBundleJson,\n incoming: StoredPrincipalPolicyBundleJson,\n): void {\n try {\n if (\n canonical(securityContent(parseBundle(stored))) ===\n canonical(securityContent(parseBundle(incoming)))\n ) {\n return;\n }\n } catch {\n // Invalid same-head cache content is also an integrity conflict: replacing\n // it would erase the only durable evidence that the head was inconsistent.\n }\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle content conflicts with the cached bundle at the same head\",\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyBundleIntegrity.js","sourceRoot":"","sources":["principalPolicyBundleIntegrity.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,GACpC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAEL,mCAAmC,GACpC,MAAM,+BAA+B,CAAC;AAEvC,SAAS,WAAW,CAClB,GAAoC;IAEpC,MAAM,MAAM,GAAG,mCAAmC,CAAC,GAAG,CAAC,CAAC;IACxD,IAAI,CAAC,+BAA+B,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;IAC/D,CAAC;IAC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e,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;YAC/C,SAAS,CAAC,eAAe,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC,EACjD,CAAC;YACD,OAAO;QACT,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,2EAA2E;QAC3E,2EAA2E;IAC7E,CAAC;IACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,mFAAmF,CACpF,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\nimport {\n type StoredPrincipalPolicyBundleJson,\n storedPrincipalPolicyBundleFromJson,\n} from \"./storedPrincipalPolicyBundle\";\n\nfunction parseBundle(\n row: StoredPrincipalPolicyBundleJson,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n return bundle;\n}\n\nfunction canonical(value: unknown): string {\n return canonicalKeyingJsonString(\n value,\n \"principal policy bundle security content\",\n );\n}\n\nfunction withoutCreatedAt<T extends { readonly createdAt: string }>(\n value: T,\n): Omit<T, \"createdAt\"> {\n const { createdAt: _createdAt, ...content } = value;\n return content;\n}\n\nfunction securityContent(bundle: PrincipalPolicyBundleResponse) {\n return {\n currentMemberEnvelopes: {\n ...bundle.currentMemberEnvelopes,\n envelopes: [...bundle.currentMemberEnvelopes.envelopes].sort((a, b) =>\n compareCanonicalStrings(canonical(a), canonical(b)),\n ),\n },\n currentPayload: { ciphertext: bundle.currentPayload.ciphertext },\n currentProjection: normalizePrincipalProjectionMembers(\n bundle.currentProjection,\n ),\n currentGrants: normalizePrincipalContainerGrants(bundle.currentGrants),\n currentState: withoutCreatedAt(bundle.currentState),\n previousStates: bundle.previousStates.map((entry) => ({\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n state: withoutCreatedAt(entry.state),\n })),\n };\n}\n\nexport function assertSameHeadPrincipalPolicyBundle(\n stored: StoredPrincipalPolicyBundleJson,\n incoming: StoredPrincipalPolicyBundleJson,\n): void {\n try {\n if (\n canonical(securityContent(parseBundle(stored))) ===\n canonical(securityContent(parseBundle(incoming)))\n ) {\n return;\n }\n } catch {\n // Invalid same-head cache content is also an integrity conflict: replacing\n // it would erase the only durable evidence that the head was inconsistent.\n }\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle content conflicts with the cached bundle at the same head\",\n );\n}\n"]}
@@ -18,11 +18,7 @@ async function assertCurrentPayloadMatches(input) {
18
18
  const { current, policy } = input;
19
19
  const payloadHash = await computePrincipalStatePayloadCiphertextHash(current.currentPayload.ciphertext);
20
20
  const envelopesRoot = await memberEnvelopesRoot(current);
21
- if (current.currentPayload.principalType !== policy.principalType ||
22
- current.currentPayload.principalId !== policy.principalId ||
23
- current.currentPayload.stateHash !== policy.stateHash ||
24
- current.currentPayload.ciphertextHash !== payloadHash ||
25
- policy.state.payloadCiphertextHash !== payloadHash ||
21
+ if (policy.state.payloadCiphertextHash !== payloadHash ||
26
22
  current.currentMemberEnvelopes.principalType !== policy.principalType ||
27
23
  current.currentMemberEnvelopes.principalId !== policy.principalId ||
28
24
  current.currentMemberEnvelopes.stateHash !== policy.stateHash ||
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedPrincipalPolicyCurrent.js","sourceRoot":"","sources":["verifiedPrincipalPolicyCurrent.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mCAAmC,EACnC,0CAA0C,EAC1C,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,EACnC,sCAAsC,GAGvC,MAAM,mBAAmB,CAAC;AAC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CACnC,EACH,CAAC;QACD,eAAe,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,2BAA2B,CAAC,KAAK,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n computePrincipalMemberEnvelopesRoot,\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n PrincipalMemberEnvelopeValidationError,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\n\ntype VerifiedCurrentPolicy =\n | VerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\nfunction currentMismatch(message: string): never {\n throw new KeyingVerificationError(\"equivocation\", message);\n}\n\nasync function memberEnvelopesRoot(\n current: PrincipalPolicyPageCurrent,\n): Promise<string> {\n try {\n return await computePrincipalMemberEnvelopesRoot(\n current.currentMemberEnvelopes.envelopes,\n );\n } catch (error) {\n if (error instanceof PrincipalMemberEnvelopeValidationError) {\n throw new KeyingVerificationError(\"invalid_shape\", error.message);\n }\n throw error;\n }\n}\n\nasync function assertCurrentPayloadMatches(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n const payloadHash = await computePrincipalStatePayloadCiphertextHash(\n current.currentPayload.ciphertext,\n );\n const envelopesRoot = await memberEnvelopesRoot(current);\n if (\n current.currentPayload.principalType !== policy.principalType ||\n current.currentPayload.principalId !== policy.principalId ||\n current.currentPayload.stateHash !== policy.stateHash ||\n current.currentPayload.ciphertextHash !== payloadHash ||\n policy.state.payloadCiphertextHash !== payloadHash ||\n current.currentMemberEnvelopes.principalType !== policy.principalType ||\n current.currentMemberEnvelopes.principalId !== policy.principalId ||\n current.currentMemberEnvelopes.stateHash !== policy.stateHash ||\n current.currentMemberEnvelopes.epoch !== policy.keyEpoch ||\n envelopesRoot !== policy.state.memberEnvelopesRoot\n ) {\n currentMismatch(\"Verified principal policy current payload mismatch\");\n }\n}\n\n/** Bind current wire artifacts to already verified policy evidence; never authenticate history. */\nexport async function assertCurrentMatchesVerifiedPolicy(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n if (\n current.currentState.principalType !== policy.principalType ||\n current.currentState.principalId !== policy.principalId ||\n current.currentState.version !== policy.version ||\n current.currentState.keyEpoch !== policy.keyEpoch ||\n current.currentState.stateHash !== policy.stateHash ||\n policy.checkpoint.version !== policy.version ||\n policy.checkpoint.stateHash !== policy.stateHash\n ) {\n currentMismatch(\"Verified principal policy current head mismatch\");\n }\n if (\n canonicalKeyingJsonString(\n current.currentState,\n \"principal policy current state\",\n ) !==\n canonicalKeyingJsonString(\n policy.state,\n \"verified principal policy state\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(current.currentProjection),\n \"principal policy current projection\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(policy.projection),\n \"verified principal policy projection\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(current.currentGrants),\n \"principal policy current grants\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(policy.grants),\n \"verified principal policy grants\",\n )\n ) {\n currentMismatch(\"Verified principal policy current content mismatch\");\n }\n\n await assertCurrentPayloadMatches(input);\n}\n"]}
1
+ {"version":3,"file":"verifiedPrincipalPolicyCurrent.js","sourceRoot":"","sources":["verifiedPrincipalPolicyCurrent.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mCAAmC,EACnC,0CAA0C,EAC1C,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,EACnC,sCAAsC,GAGvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAMvE,S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,GAAG,KAAK,CAAC;IAClC,IACE,OAAO,CAAC,YAAY,CAAC,aAAa,KAAK,MAAM,CAAC,aAAa;QAC3D,OAAO,CAAC,YAAY,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW;QACvD,OAAO,CAAC,YAAY,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO;QAC/C,OAAO,CAAC,YAAY,CAAC,QAAQ,KAAK,MAAM,CAAC,QAAQ;QACjD,OAAO,CAAC,YAAY,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS;QACnD,MAAM,CAAC,UAAU,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO;QAC5C,MAAM,CAAC,UAAU,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,EAChD,CAAC;QACD,eAAe,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IACD,IACE,yBAAyB,CACvB,OAAO,CAAC,YAAY,EACpB,gCAAgC,CACjC;QACC,yBAAyB,CACvB,MAAM,CAAC,KAAK,EACZ,iCAAiC,CAClC;QACH,yBAAyB,CACvB,mCAAmC,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAC9D,qCAAqC,CACtC;YACC,yBAAyB,CACvB,mCAAmC,CAAC,MAAM,CAAC,UAAU,CAAC,EACtD,sCAAsC,CACvC;QACH,yBAAyB,CACvB,iCAAiC,CAAC,OAAO,CAAC,aAAa,CAAC,EACxD,iCAAiC,CAClC;YACC,yBAAyB,CACvB,iCAAiC,CAAC,MAAM,CAAC,MAAM,CAAC,EAChD,kCAAkC,CACnC,EACH,CAAC;QACD,eAAe,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,2BAA2B,CAAC,KAAK,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n computePrincipalMemberEnvelopesRoot,\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n PrincipalMemberEnvelopeValidationError,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\n\ntype VerifiedCurrentPolicy =\n | VerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\nfunction currentMismatch(message: string): never {\n throw new KeyingVerificationError(\"equivocation\", message);\n}\n\nasync function memberEnvelopesRoot(\n current: PrincipalPolicyPageCurrent,\n): Promise<string> {\n try {\n return await computePrincipalMemberEnvelopesRoot(\n current.currentMemberEnvelopes.envelopes,\n );\n } catch (error) {\n if (error instanceof PrincipalMemberEnvelopeValidationError) {\n throw new KeyingVerificationError(\"invalid_shape\", error.message);\n }\n throw error;\n }\n}\n\nasync function assertCurrentPayloadMatches(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n const payloadHash = await computePrincipalStatePayloadCiphertextHash(\n current.currentPayload.ciphertext,\n );\n const envelopesRoot = await memberEnvelopesRoot(current);\n if (\n policy.state.payloadCiphertextHash !== payloadHash ||\n current.currentMemberEnvelopes.principalType !== policy.principalType ||\n current.currentMemberEnvelopes.principalId !== policy.principalId ||\n current.currentMemberEnvelopes.stateHash !== policy.stateHash ||\n current.currentMemberEnvelopes.epoch !== policy.keyEpoch ||\n envelopesRoot !== policy.state.memberEnvelopesRoot\n ) {\n currentMismatch(\"Verified principal policy current payload mismatch\");\n }\n}\n\n/** Bind current wire artifacts to already verified policy evidence; never authenticate history. */\nexport async function assertCurrentMatchesVerifiedPolicy(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n if (\n current.currentState.principalType !== policy.principalType ||\n current.currentState.principalId !== policy.principalId ||\n current.currentState.version !== policy.version ||\n current.currentState.keyEpoch !== policy.keyEpoch ||\n current.currentState.stateHash !== policy.stateHash ||\n policy.checkpoint.version !== policy.version ||\n policy.checkpoint.stateHash !== policy.stateHash\n ) {\n currentMismatch(\"Verified principal policy current head mismatch\");\n }\n if (\n canonicalKeyingJsonString(\n current.currentState,\n \"principal policy current state\",\n ) !==\n canonicalKeyingJsonString(\n policy.state,\n \"verified principal policy state\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(current.currentProjection),\n \"principal policy current projection\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(policy.projection),\n \"verified principal policy projection\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(current.currentGrants),\n \"principal policy current grants\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(policy.grants),\n \"verified principal policy grants\",\n )\n ) {\n currentMismatch(\"Verified principal policy current content mismatch\");\n }\n\n await assertCurrentPayloadMatches(input);\n}\n"]}
@@ -57,9 +57,7 @@ export async function buildOrganizationGroupDirectoryPolicyRequest(input) {
57
57
  }), input.signingKeyPair.signingPrivateKey);
58
58
  return {
59
59
  encryptedPayload: {
60
- cipherSuite: "aes-256-gcm",
61
60
  ciphertext: payloadCiphertext,
62
- ciphertextHash: state.payloadCiphertextHash,
63
61
  },
64
62
  grants: [],
65
63
  memberEnvelopes: keying.memberEnvelopes,
@@ -1 +1 @@
1
- {"version":3,"file":"organizationGroupDirectoryRequest.js","sourceRoot":"","sources":["organizationGroupDirectoryRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,mCAAmC,EAGnC,kBAAkB,GACnB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EACL,qCAAqC,EACrC,+BAA+B,GAGhC,MAAM,uDAAuD,CAAC;AAE/D,OAAO,EAEL,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AAEvC,MAAM,UAAU,qBAAqB,CACnC,IAA6B;IAE7B,IAAI,IAAI,CAAC,aAAa,KAAK,OAAO,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,qDA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AC,UAAU,CAAC,cAAc;QAC5C,OAAO,EAAE,KAAK,CAAC,aAAa,CAAC,YAAY,CAAC,OAAO,GAAG,CAAC;QACrD,aAAa,EAAE,KAAK,CAAC,aAAa,CAAC,YAAY,CAAC,SAAS;QACzD,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,sBAAsB,EAAE,MAAM,CAAC,sBAAsB;QACrD,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,OAAO,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;QAChE,eAAe,EAAE,MAAM,CAAC,eAAe;QACvC,UAAU;QACV,MAAM,EAAE,EAAE;QACV,iBAAiB;QACjB,iBAAiB,EAAE,IAAI;QACvB,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAClC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,wBAAwB,EAAE,KAAK,CAAC,kBAAkB;KACnD,CAAC,EACF,KAAK,CAAC,cAAc,CAAC,iBAAiB,CACvC,CAAC;IAEF,OAAO;QACL,gBAAgB,EAAE;YAChB,WAAW,EAAE,aAAa;YAC1B,UAAU,EAAE,iBAAiB;YAC7B,cAAc,EAAE,KAAK,CAAC,qBAAqB;SAC5C;QACD,MAAM,EAAE,EAAE;QACV,eAAe,EAAE,MAAM,CAAC,eAAe;QACvC,UAAU;QACV,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../principalContracts/organizationAuthorityDescriptor\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\nimport {\n type OrganizationDirectoryCurrentPolicy,\n organizationDirectoryKeying,\n} from \"./organizationDirectoryKeying\";\n\nexport function organizationGroupHead(\n head: ReferencedPrincipalHead,\n): OrganizationGroupHead {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n}\n\nexport function replaceOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly nextHead: ReferencedPrincipalHead;\n}): OrganizationGroupHead[] {\n const nextHead = organizationGroupHead(input.nextHead);\n return normalizeOrganizationGroupHeads([\n ...input.descriptor.groupHeads.filter(\n (head) => head.principalId !== nextHead.principalId,\n ),\n nextHead,\n ]);\n}\n\n/**\n * The organization's successor directory state. Its key follows the Admins\n * projection (see `organizationDirectoryKeying`): `currentUserSecretKey` is\n * the signer's KEM secret, needed only to keep the key while admins grow;\n * without it a growth rotates.\n */\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: OrganizationDirectoryCurrentPolicy &\n Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly currentUserSecretKey: Uint8Array | null;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupHeads: readonly OrganizationGroupHead[];\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.adminProjection);\n if (\n projection.length === 0 ||\n projection.some((member) => member.role !== \"admin\")\n ) {\n throw new Error(\"Organization policy must mirror the Admins projection\");\n }\n const keying = await organizationDirectoryKeying({\n currentPolicy: input.currentPolicy,\n currentUserSecretKey: input.currentUserSecretKey,\n projection,\n signerUserId: input.signerUserId,\n users: input.adminUsers,\n });\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n ...input.descriptor,\n groupHeads: input.groupHeads,\n });\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.descriptor.organizationId,\n version: input.currentPolicy.currentState.version + 1,\n prevStateHash: input.currentPolicy.currentState.stateHash,\n keyEpoch: keying.keyEpoch,\n encapsulationPublicKey: keying.encapsulationPublicKey,\n keyFingerprint: keying.keyFingerprint,\n members: projection.map((member) => ({ userId: member.userId })),\n memberEnvelopes: keying.memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n grants: [],\n memberEnvelopes: keying.memberEnvelopes,\n projection,\n state,\n };\n}\n"]}
1
+ {"version":3,"file":"organizationGroupDirectoryRequest.js","sourceRoot":"","sources":["organizationGroupDirectoryRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,mCAAmC,EAGnC,kBAAkB,GACnB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EACL,qCAAqC,EACrC,+BAA+B,GAGhC,MAAM,uDAAuD,CAAC;AAE/D,OAAO,EAEL,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AAEvC,MAAM,UAAU,qBAAqB,CACnC,IAA6B;IAE7B,IAAI,IAAI,CAAC,aAAa,KAAK,OAAO,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,EAAE,GAAG,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC;AAC7C,CAAC;AAED,MAA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AK,CAAC,aAAa,CAAC,YAAY,CAAC,SAAS;QACzD,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,sBAAsB,EAAE,MAAM,CAAC,sBAAsB;QACrD,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,OAAO,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;QAChE,eAAe,EAAE,MAAM,CAAC,eAAe;QACvC,UAAU;QACV,MAAM,EAAE,EAAE;QACV,iBAAiB;QACjB,iBAAiB,EAAE,IAAI;QACvB,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAClC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,wBAAwB,EAAE,KAAK,CAAC,kBAAkB;KACnD,CAAC,EACF,KAAK,CAAC,cAAc,CAAC,iBAAiB,CACvC,CAAC;IAEF,OAAO;QACL,gBAAgB,EAAE;YAChB,UAAU,EAAE,iBAAiB;SAC9B;QACD,MAAM,EAAE,EAAE;QACV,eAAe,EAAE,MAAM,CAAC,eAAe;QACvC,UAAU;QACV,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../principalContracts/organizationAuthorityDescriptor\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\nimport {\n type OrganizationDirectoryCurrentPolicy,\n organizationDirectoryKeying,\n} from \"./organizationDirectoryKeying\";\n\nexport function organizationGroupHead(\n head: ReferencedPrincipalHead,\n): OrganizationGroupHead {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n}\n\nexport function replaceOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly nextHead: ReferencedPrincipalHead;\n}): OrganizationGroupHead[] {\n const nextHead = organizationGroupHead(input.nextHead);\n return normalizeOrganizationGroupHeads([\n ...input.descriptor.groupHeads.filter(\n (head) => head.principalId !== nextHead.principalId,\n ),\n nextHead,\n ]);\n}\n\n/**\n * The organization's successor directory state. Its key follows the Admins\n * projection (see `organizationDirectoryKeying`): `currentUserSecretKey` is\n * the signer's KEM secret, needed only to keep the key while admins grow;\n * without it a growth rotates.\n */\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: OrganizationDirectoryCurrentPolicy &\n Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly currentUserSecretKey: Uint8Array | null;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupHeads: readonly OrganizationGroupHead[];\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.adminProjection);\n if (\n projection.length === 0 ||\n projection.some((member) => member.role !== \"admin\")\n ) {\n throw new Error(\"Organization policy must mirror the Admins projection\");\n }\n const keying = await organizationDirectoryKeying({\n currentPolicy: input.currentPolicy,\n currentUserSecretKey: input.currentUserSecretKey,\n projection,\n signerUserId: input.signerUserId,\n users: input.adminUsers,\n });\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n ...input.descriptor,\n groupHeads: input.groupHeads,\n });\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.descriptor.organizationId,\n version: input.currentPolicy.currentState.version + 1,\n prevStateHash: input.currentPolicy.currentState.stateHash,\n keyEpoch: keying.keyEpoch,\n encapsulationPublicKey: keying.encapsulationPublicKey,\n keyFingerprint: keying.keyFingerprint,\n members: projection.map((member) => ({ userId: member.userId })),\n memberEnvelopes: keying.memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n encryptedPayload: {\n ciphertext: payloadCiphertext,\n },\n grants: [],\n memberEnvelopes: keying.memberEnvelopes,\n projection,\n state,\n };\n}\n"]}
@@ -59,9 +59,7 @@ export async function buildInitialOrganizationPolicyRequest(input) {
59
59
  return {
60
60
  state,
61
61
  encryptedPayload: {
62
- cipherSuite: "aes-256-gcm",
63
62
  ciphertext: payloadCiphertext,
64
- ciphertextHash: state.payloadCiphertextHash,
65
63
  },
66
64
  projection,
67
65
  grants: [],
@@ -1 +1 @@
1
- {"version":3,"file":"organizationPolicyRequest.js","sourceRoot":"","sources":["organizationPolicyRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EAGzB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,qCAAqC,EAAE,MAAM,uDAAuD,CAAC;AAC9G,OAAO,EAAE,+BAA+B,EAAE,MAAM,oDAAoD,CAAC;AAErG,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAS3D;IACC,MAAM,eAAe,GAAG,yBAAyB,EAAE,CAAC;IACpD,MAAM,wBAAwB,GAAG,MAAM,aAAa,CAClD,KAAK,CAAC,cAAc,CAAC,gBAAgB,CACtC,CAAC;IACF,MAAM,+BAA+B,GAAG,MAAM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AG,MAAM,kBAAkB,CACpC,MAAM,+BAA+B,CAAC;QACpC,aAAa,EAAE,cAAc;QAC7B,WAAW,EAAE,KAAK,CAAC,cAAc;QACjC,OAAO,EAAE,CAAC;QACV,aAAa,EAAE,IAAI;QACnB,QAAQ,EAAE,CAAC;QACX,sBAAsB,EAAE,aAAa,CAAC,eAAe,CAAC,SAAS,CAAC;QAChE,cAAc,EAAE,MAAM,aAAa,CAAC,eAAe,CAAC,SAAS,CAAC;QAC9D,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC;QACnC,eAAe;QACf,UAAU;QACV,MAAM,EAAE,EAAE;QACV,iBAAiB;QACjB,iBAAiB,EAAE,IAAI;QACvB,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAClC,YAAY,EAAE,KAAK,CAAC,MAAM;QAC1B,wBAAwB;KACzB,CAAC,EACF,KAAK,CAAC,cAAc,CAAC,iBAAiB,CACvC,CAAC;IAEF,OAAO;QACL,KAAK;QACL,gBAAgB,EAAE;YAChB,WAAW,EAAE,aAAa;YAC1B,UAAU,EAAE,iBAAiB;YAC7B,cAAc,EAAE,KAAK,CAAC,qBAAqB;SAC5C;QACD,UAAU;QACV,MAAM,EAAE,EAAE;QACV,eAAe;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { RegistrationRequest } from \"@tearleads/validators/request\";\nimport { encodeOrganizationAuthorityDescriptor } from \"../principalContracts/organizationAuthorityDescriptor\";\nimport { createPrincipalProjectionMember } from \"../principalContracts/principalIdentityCommitments\";\n\nexport async function buildInitialOrganizationPolicyRequest(input: {\n identityTrustDomain: string;\n adminGroupId: string;\n groupHeads: readonly ReferencedPrincipalHead[];\n encapsulationPublicKey: Uint8Array;\n memberGroupId: string;\n organizationId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<RegistrationRequest[\"initialOrganizationPolicy\"]> {\n const organizationKem = generateKemSeedAndKeyPair();\n const signerUserKeyFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const userEncapsulationKeyFingerprint = await toFingerprint(\n input.encapsulationPublicKey,\n );\n const projection = [\n await createPrincipalProjectionMember(\n {\n userId: input.userId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.encapsulationPublicKey,\n },\n \"admin\",\n ),\n ];\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n version: 2,\n organizationId: input.organizationId,\n adminGroupId: input.adminGroupId,\n memberGroupId: input.memberGroupId,\n groupHeads: input.groupHeads.map((head) => {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n }),\n });\n const [memberEnvelope] = await wrapDekForRecipients(\n organizationKem.secretKey,\n [input.encapsulationPublicKey],\n );\n\n if (!memberEnvelope) {\n throw new Error(\"Failed to wrap organization key for registering user\");\n }\n const memberEnvelopes = [\n {\n userId: input.userId,\n memberKeyFingerprint: userEncapsulationKeyFingerprint,\n kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),\n },\n ];\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.organizationId,\n version: 1,\n prevStateHash: null,\n keyEpoch: 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: [{ userId: input.userId }],\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.userId,\n signerUserKeyFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants: [],\n memberEnvelopes,\n };\n}\n"]}
1
+ {"version":3,"file":"organizationPolicyRequest.js","sourceRoot":"","sources":["organizationPolicyRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EAGzB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,qCAAqC,EAAE,MAAM,uDAAuD,CAAC;AAC9G,OAAO,EAAE,+BAA+B,EAAE,MAAM,oDAAoD,CAAC;AAErG,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAS3D;IACC,MAAM,eAAe,GAAG,yBAAyB,EAAE,CAAC;IACpD,MAAM,wBAAwB,GAAG,MAAM,aAAa,CAClD,KAAK,CAAC,cAAc,CAAC,gBAAgB,CACtC,CAAC;IACF,MAAM,+BAA+B,GAAG,MAAM,aAAa,CACzD,KAAK,CAAC,sBAAsB,CAC7B,CAAC;IACF,MAAM,UAAU,GAAG;QACjB,MAAM,+BAA+B,CACnC;YACE,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,gBAAgB,EAAE,KAAK,CAAC,cAAc,CAAC,gBAAgB;YACvD,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;SACrD,EACD,OAAO,CACR;KACF,CAAC;IACF,MAAM,iBAAiB,GAAG,qCAAqC,CAAC;QAC9D,OAAO,EAAE,CAAC;QACV,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,UAAU,EAAE,KAAK,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WAAW,EAAE;QAClC,YAAY,EAAE,KAAK,CAAC,MAAM;QAC1B,wBAAwB;KACzB,CAAC,EACF,KAAK,CAAC,cAAc,CAAC,iBAAiB,CACvC,CAAC;IAEF,OAAO;QACL,KAAK;QACL,gBAAgB,EAAE;YAChB,UAAU,EAAE,iBAAiB;SAC9B;QACD,UAAU;QACV,MAAM,EAAE,EAAE;QACV,eAAe;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { RegistrationRequest } from \"@tearleads/validators/request\";\nimport { encodeOrganizationAuthorityDescriptor } from \"../principalContracts/organizationAuthorityDescriptor\";\nimport { createPrincipalProjectionMember } from \"../principalContracts/principalIdentityCommitments\";\n\nexport async function buildInitialOrganizationPolicyRequest(input: {\n identityTrustDomain: string;\n adminGroupId: string;\n groupHeads: readonly ReferencedPrincipalHead[];\n encapsulationPublicKey: Uint8Array;\n memberGroupId: string;\n organizationId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<RegistrationRequest[\"initialOrganizationPolicy\"]> {\n const organizationKem = generateKemSeedAndKeyPair();\n const signerUserKeyFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const userEncapsulationKeyFingerprint = await toFingerprint(\n input.encapsulationPublicKey,\n );\n const projection = [\n await createPrincipalProjectionMember(\n {\n userId: input.userId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.encapsulationPublicKey,\n },\n \"admin\",\n ),\n ];\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n version: 2,\n organizationId: input.organizationId,\n adminGroupId: input.adminGroupId,\n memberGroupId: input.memberGroupId,\n groupHeads: input.groupHeads.map((head) => {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n }),\n });\n const [memberEnvelope] = await wrapDekForRecipients(\n organizationKem.secretKey,\n [input.encapsulationPublicKey],\n );\n\n if (!memberEnvelope) {\n throw new Error(\"Failed to wrap organization key for registering user\");\n }\n const memberEnvelopes = [\n {\n userId: input.userId,\n memberKeyFingerprint: userEncapsulationKeyFingerprint,\n kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),\n },\n ];\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.organizationId,\n version: 1,\n prevStateHash: null,\n keyEpoch: 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: [{ userId: input.userId }],\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.userId,\n signerUserKeyFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n ciphertext: payloadCiphertext,\n },\n projection,\n grants: [],\n memberEnvelopes,\n };\n}\n"]}
@@ -87,9 +87,7 @@ export async function signedGroupPolicyRequest(input) {
87
87
  return {
88
88
  state,
89
89
  encryptedPayload: {
90
- cipherSuite: "aes-256-gcm",
91
90
  ciphertext: payloadCiphertext,
92
- ciphertextHash: state.payloadCiphertextHash,
93
91
  },
94
92
  projection,
95
93
  grants,