@tearleads/client-sdk 0.1.79 → 0.1.81

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 (177) hide show
  1. package/client/deviceFirst/index.d.ts +1 -1
  2. package/client/deviceFirst/index.js +1 -1
  3. package/client/deviceFirst/index.js.map +1 -1
  4. package/client/runtime/principalMutationApi.js +1 -1
  5. package/client/runtime/principalMutationApi.js.map +1 -1
  6. package/client/runtime/principalMutationDispatch.js +1 -1
  7. package/client/runtime/principalMutationDispatch.js.map +1 -1
  8. package/client/runtime/rootContainerAdoption.js.map +1 -1
  9. package/client/runtime/workflowRuntime.d.ts +1 -1
  10. package/client/runtime/workflowRuntime.js.map +1 -1
  11. package/client/session/sessionPurgeRecovery.js +1 -1
  12. package/client/session/sessionPurgeRecovery.js.map +1 -1
  13. package/data/blobs/attachments/projection.js +2 -3
  14. package/data/blobs/attachments/projection.js.map +1 -1
  15. package/data/documents/documentConstants.d.ts +1 -0
  16. package/data/documents/documentConstants.js +1 -0
  17. package/data/documents/documentConstants.js.map +1 -1
  18. package/data/documents/shared/containerKek/containerKekEntryVerification.d.ts +3 -0
  19. package/data/documents/shared/containerKek/index.d.ts +5 -0
  20. package/data/documents/shared/containerKek/index.js +9 -0
  21. package/data/documents/shared/containerKek/index.js.map +1 -0
  22. package/data/documents/shared/projection/index.d.ts +1 -1
  23. package/data/documents/shared/projection/index.js +1 -1
  24. package/data/documents/shared/projection/index.js.map +1 -1
  25. package/data/documents/shared/sync/syncResponseAuthorization.js +1 -1
  26. package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -1
  27. package/data/keyingProjectionVerification/container/containerCreateManifest.d.ts +12 -0
  28. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +16 -0
  29. package/data/keyingProjectionVerification/index.d.ts +5 -0
  30. package/data/keyingProjectionVerification/index.js +6 -1
  31. package/data/keyingProjectionVerification/index.js.map +1 -1
  32. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.d.ts +3 -0
  33. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +1 -1
  34. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  35. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCheckpointSelection.d.ts +6 -0
  36. package/data/{persistence → keyingProjectionVerification}/principalPolicy/principalPolicyCheckpointSelection.js +1 -1
  37. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
  38. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.d.ts +24 -0
  39. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +1 -1
  40. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  41. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js +1 -1
  42. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -1
  43. package/data/persistence/container-contents/documentPlacement.js +1 -1
  44. package/data/persistence/container-contents/documentPlacement.js.map +1 -1
  45. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
  46. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js.map +1 -1
  47. package/data/persistence/documents/documentsPersistence.d.ts +1 -1
  48. package/data/persistence/documents/documentsPersistence.js +2 -3
  49. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  50. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  51. package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
  52. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +1 -1
  53. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  54. package/data/persistence/documents/internal/documentDeletionPersistence.js +1 -1
  55. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  56. package/data/persistence/documents/internal/documentMutationPersistence.js +1 -1
  57. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  58. package/data/persistence/documents/internal/documentProjectionRows.js +1 -2
  59. package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
  60. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  61. package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
  62. package/data/persistence/documents/internal/documentRows.js +1 -2
  63. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  64. package/data/persistence/documents/internal/orphanSideRows.js +1 -1
  65. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  66. package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
  67. package/data/persistence/documents/internal/pendingCreateAdoption.js.map +1 -1
  68. package/data/persistence/documents/internal/rowQueryPersistence.js +1 -1
  69. package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
  70. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +11 -51
  71. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
  72. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +1 -30
  73. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +4 -85
  74. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  75. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +88 -0
  76. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -0
  77. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js +53 -0
  78. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js.map +1 -0
  79. package/package.json +1 -1
  80. package/stores/local-projection/localProjectionStore.d.ts +1 -1
  81. package/stores/local-projection/localProjectionStore.js +1 -1
  82. package/stores/local-projection/localProjectionStore.js.map +1 -1
  83. package/stores/local-projection/registry.d.ts +1 -1
  84. package/stores/local-projection/registry.js.map +1 -1
  85. package/stores/local-projection/types.d.ts +1 -1
  86. package/stores/local-projection/types.js.map +1 -1
  87. package/workflows/blobs/hydration/decrypt.js +1 -2
  88. package/workflows/blobs/hydration/decrypt.js.map +1 -1
  89. package/workflows/blobs/hydration/hydrate.d.ts +1 -1
  90. package/workflows/blobs/hydration/hydrate.js.map +1 -1
  91. package/workflows/container-contents/container-state/create/createAdoption.js +1 -2
  92. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  93. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -1
  94. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  95. package/workflows/container-contents/info/documentInfo.js +1 -1
  96. package/workflows/container-contents/info/documentInfo.js.map +1 -1
  97. package/workflows/container-contents/metadata/index.js +1 -2
  98. package/workflows/container-contents/metadata/index.js.map +1 -1
  99. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  100. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  101. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
  102. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
  103. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  104. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  105. package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
  106. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  107. package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
  108. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  109. package/workflows/container-contents/pendingWrites/index.js +1 -1
  110. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  111. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -3
  112. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  113. package/workflows/containers/child/create/index.js +1 -1
  114. package/workflows/containers/child/create/index.js.map +1 -1
  115. package/workflows/containers/child/move/moveRotation.js +1 -1
  116. package/workflows/containers/child/move/moveRotation.js.map +1 -1
  117. package/workflows/containers/child/move/moveWraps.js +1 -1
  118. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  119. package/workflows/containers/child/rekey/rekeyProjection.js +1 -1
  120. package/workflows/containers/child/rekey/rekeyProjection.js.map +1 -1
  121. package/workflows/containers/child/rotation/rotationContext.js +1 -2
  122. package/workflows/containers/child/rotation/rotationContext.js.map +1 -1
  123. package/workflows/containers/child/share/shareAncestorRepair.js +1 -2
  124. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -1
  125. package/workflows/containers/index.d.ts +2 -3
  126. package/workflows/containers/index.js +1 -2
  127. package/workflows/containers/index.js.map +1 -1
  128. package/workflows/containers/writeRefusal.js +1 -1
  129. package/workflows/containers/writeRefusal.js.map +1 -1
  130. package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
  131. package/workflows/documents/linkSet/linkSetProjectionSeed.js.map +1 -1
  132. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +1 -1
  133. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  134. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  135. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  136. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
  137. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  138. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
  139. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  140. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  141. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  142. package/workflows/organizations/provisioning/createOrganization.d.ts +1 -1
  143. package/workflows/organizations/provisioning/createOrganization.js +1 -1
  144. package/workflows/organizations/provisioning/createOrganization.js.map +1 -1
  145. package/workflows/organizations/provisioning/organizationProvisioningAttempt.d.ts +1 -1
  146. package/workflows/organizations/provisioning/organizationProvisioningAttempt.js.map +1 -1
  147. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  148. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
  149. package/workflows/principals/externalAdminPolicy.js +1 -1
  150. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  151. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
  152. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  153. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +1 -1
  154. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  155. package/workflows/registration/index.d.ts +2 -1
  156. package/workflows/registration/index.js +2 -1
  157. package/workflows/registration/index.js.map +1 -1
  158. package/workflows/registration/organizationProvisioning.d.ts +39 -0
  159. package/workflows/registration/organizationProvisioning.js +211 -0
  160. package/workflows/registration/organizationProvisioning.js.map +1 -0
  161. package/workflows/registration/organizationProvisioningArtifacts.d.ts +2 -3
  162. package/workflows/registration/organizationProvisioningArtifacts.js.map +1 -1
  163. package/workflows/registration/provisioningBootstrapBuilders.d.ts +3 -3
  164. package/workflows/registration/provisioningBootstrapBuilders.js +3 -4
  165. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  166. package/workflows/registration/registerIdentity.d.ts +2 -39
  167. package/workflows/registration/registerIdentity.js +2 -207
  168. package/workflows/registration/registerIdentity.js.map +1 -1
  169. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
  170. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  171. package/workflows/sync/remoteResetPlans.js +2 -2
  172. package/workflows/sync/remoteResetPlans.js.map +1 -1
  173. package/data/persistence/documents/internal/constants.d.ts +0 -1
  174. package/data/persistence/documents/internal/constants.js +0 -2
  175. package/data/persistence/documents/internal/constants.js.map +0 -1
  176. package/data/persistence/principalKeys/principalGrantRetirementPersistence.d.ts +0 -9
  177. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +0 -1
@@ -1 +1 @@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E,KAAK,CAAC,IAAI;oBAChB,OAAO,EAAE,KAAK,CAAC,OAAO;oBACtB,EAAE,EAAE,KAAK;oBACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;oBACvB,MAAM,EAAE,KAAK,CAAC,MAAM;iBACrB,CAAC,CAAC;gBACH,MAAM,IAAI,oCAAoC,CAAC,SAAS,CAAC,CAAC;YAC5D,CAAC;YACD,qEAAqE;YACrE,uEAAuE;YACvE,uEAAuE;YACvE,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC;gBACtC,CAAC,CAAC,IAAI,mCAAmC,CACrC,kBAAkB,CAAC,WAAW,CAC/B;gBACH,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers/child/rekey\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
1
+ {"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":"","sources":["syncAutomaticContainerRekeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kEAAkE,CAAC;AACvH,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,kBAAkB,CAAC;AAEvE,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAQzE,SAAS,mBAAmB,CAC1B,UAA4C;IAE5C,KAAK,MAAM,IAAI,IAAI,4BAA4B,CAAC,UAAU,CAAC,EAAE,CAAC;QAC5D,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;YAClE,MAAM,MAAM,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;YAC7C,MAAM,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;YACxC,IAAI,CAAC,MAAM,IAAI,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EACD,CAAC;oBACD,MAAM,IAAI,mCAAmC,CAC3C,kBAAkB,CAAC,WAAW,CAC/B,CAAC;gBACJ,CAAC;gBACD,MAAM,IAAI,CAAC,uBAAuB,EAAE,CAAC;oBACnC,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,OAAO,EAAE,KAAK,CAAC,OAAO;oBACtB,EAAE,EAAE,KAAK;oBACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;oBACvB,MAAM,EAAE,KAAK,CAAC,MAAM;iBACrB,CAAC,CAAC;gBACH,MAAM,IAAI,oCAAoC,CAAC,SAAS,CAAC,CAAC;YAC5D,CAAC;YACD,qEAAqE;YACrE,uEAAuE;YACvE,uEAAuE;YACvE,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC;gBACtC,CAAC,CAAC,IAAI,mCAAmC,CACrC,kBAAkB,CAAC,WAAW,CAC/B;gBACH,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { decryptGroupMetadata, readGroupMetadata, } from "../../../internal/crypto/index.js";
2
2
  import { deriveOrganizationMetadataContainerSystemSlot } from "../../../internal/validators/containerSystemSlot.js";
3
3
  import { getTargetContainerContext, readContainerState, } from "../../../data/containers/shared/projection.js";
4
- import { unwrapContainerKekPath } from "../../../data/documents/shared/containerKek/containerKekPath.js";
4
+ import { unwrapContainerKekPath } from "../../../data/documents/shared/containerKek/index.js";
5
5
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
6
6
  import { loadContainers } from "../../../data/persistence/container-contents/containerPersistence.js";
7
7
  import { withMetadataRootReload } from "./groupMetadataErrors.js";
@@ -1 +1 @@
1
- {"version":3,"file":"groupMetadataAccess.js","sourceRoot":"","sources":["groupMetadataAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EAGpB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6CAA6C,EAAE,MAAM,2CAA2C,CAAC;AAE1G,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8DAA8D,CAAC;AAKtG,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,cAAc,EAAE,MAAM,mEAAmE,CAAC;AAGnG,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAuB/D;;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AAG,EAAE,EAAE,CACN,GAAG,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;gBAC3C,GAAG,CAAC,UAAU,KAAK,IAAI,CAC1B,CAAC;YACF,IAAI,CAAC,SAAS;gBACZ,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;YACJ,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YAC3C,IAAI,CAAC,OAAO;gBAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;YACzE,OAAO,OAAO,CAAC,OAAO,CAAC;QACzB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n decryptGroupMetadata,\n type GroupMetadataKey,\n type ReferencedPrincipalHead,\n readGroupMetadata,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport { unwrapContainerKekPath } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { loadContainers } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { GroupPolicyNameReader } from \"../principalPolicy/principalPolicyRequest\";\nimport { withMetadataRootReload } from \"./groupMetadataErrors\";\n\nexport interface GroupMetadataAccessInput {\n readonly apiClient: {\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n };\n readonly verifyMetadataContainer: (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead | undefined,\n ) => Promise<void>;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly targetSecretKey: Uint8Array;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/**\n * A group's signed name does not open under the metadata key it cites, or opens\n * to an invalid name. Every reader holding that key gets the same result. The\n * API checks the citation but can never check the ciphertext, so a dishonest\n * admin can sign such a name; directory walks isolate the group instead of\n * failing every name in the organization.\n */\nexport class GroupMetadataUnreadableError extends Error {\n constructor(groupId: string, cause: unknown) {\n super(`Group ${groupId} metadata cannot be decrypted`, { cause });\n this.name = \"GroupMetadataUnreadableError\";\n }\n}\n\nfunction loadMetadataKeyring(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n return withMetadataRootReload(\n () => loadMetadataKeyringOnce(input, containerId),\n () => input.apiClient.evictContainerWriterProjection(containerId),\n );\n}\n\nasync function loadMetadataKeyringOnce(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n const projection =\n await input.apiClient.getContainerWriterProjection(containerId);\n if (!projection) return null;\n if (\n projection.containerId !== containerId ||\n projection.organizationId !== input.organizationId\n )\n throw new Error(\"Group metadata container is unavailable\");\n const target = getTargetContainerContext(projection);\n const state = readContainerState(target.manifest);\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n if (\n state.organizationId !== input.organizationId ||\n state.systemSlot !== slot ||\n state.parentContainerId !== null\n )\n throw new Error(\n \"Group metadata requires the signed organization metadata container\",\n );\n await input.verifyMetadataContainer(\n state,\n projection.policyEvidence.organization?.head,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keys = await unwrapContainerKekPath({\n ...input,\n projection,\n secretKey: input.targetSecretKey,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keyMaterial = keys.get(target.kek.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata container key is unavailable\");\n return {\n current: {\n organizationId: input.organizationId,\n containerId,\n containerKeyEpochId: target.kek.containerKeyEpochId,\n keyMaterial,\n },\n keys,\n };\n}\n\n/** Uses the shared metadata container's authenticated keyring, including old epochs. */\nexport function createGroupMetadataAccess(input: GroupMetadataAccessInput) {\n const loads = new Map<\n string,\n Promise<{\n current: GroupMetadataKey;\n keys: ReadonlyMap<string, Uint8Array>;\n } | null>\n >();\n function loaded(containerId: string) {\n let pending = loads.get(containerId);\n if (!pending) {\n pending = loadMetadataKeyring(input, containerId);\n loads.set(containerId, pending);\n }\n return pending;\n }\n const readName: GroupPolicyNameReader = async (bundle) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n if (\"role\" in metadata)\n return metadata.role === \"admins\" ? \"Admins\" : \"Members\";\n if (\n metadata.organizationId !== input.organizationId ||\n metadata.groupId !== bundle.currentState.principalId ||\n bundle.currentState.principalType !== \"group\"\n )\n throw new Error(\"Group metadata scope does not match its signed group\");\n const keyring = await loaded(metadata.containerId);\n const keyMaterial = keyring?.keys.get(metadata.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata historical key is unavailable\");\n try {\n return await decryptGroupMetadata({\n key: { ...metadata, keyMaterial },\n groupId: bundle.currentState.principalId,\n payload: bundle.currentPayload.ciphertext,\n });\n } catch (cause) {\n throw new GroupMetadataUnreadableError(\n bundle.currentState.principalId,\n cause,\n );\n }\n };\n return {\n readName,\n async loadEncryptionKey(): Promise<GroupMetadataKey> {\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n const containers = await loadContainers(input.execSql);\n const container = containers.find(\n (row) =>\n row.organizationId === input.organizationId &&\n row.systemSlot === slot,\n );\n if (!container)\n throw new Error(\n \"Organization metadata container has not been discovered\",\n );\n const keyring = await loaded(container.id);\n if (!keyring) throw new Error(\"Group metadata container is unavailable\");\n return keyring.current;\n },\n };\n}\n"]}
1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EAAE,MAAM,CAAC,cAAc,CAAC,UAAU;aAC1C,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,4BAA4B,CACpC,MAAM,CAAC,YAAY,CAAC,WAAW,EAC/B,KAAK,CACN,CAAC;QACJ,CAAC;IACH,CAAC,CAAC;IACF,OAAO;QACL,QAAQ;QACR,KAAK,CAAC,iBAAiB;YACrB,MAAM,IAAI,GAAG,MAAM,6CAA6C,CAAC;gBAC/D,cAAc,EAAE,KAAK,CAAC,cAAc;aACrC,CAAC,CAAC;YACH,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACvD,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAC/B,CAAC,GAAG,EAAE,EAAE,CACN,GAAG,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;gBAC3C,GAAG,CAAC,UAAU,KAAK,IAAI,CAC1B,CAAC;YACF,IAAI,CAAC,SAAS;gBACZ,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;YACJ,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YAC3C,IAAI,CAAC,OAAO;gBAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;YACzE,OAAO,OAAO,CAAC,OAAO,CAAC;QACzB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n decryptGroupMetadata,\n type GroupMetadataKey,\n type ReferencedPrincipalHead,\n readGroupMetadata,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport { unwrapContainerKekPath } from \"../../../data/documents/shared/containerKek\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { loadContainers } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { GroupPolicyNameReader } from \"../principalPolicy/principalPolicyRequest\";\nimport { withMetadataRootReload } from \"./groupMetadataErrors\";\n\nexport interface GroupMetadataAccessInput {\n readonly apiClient: {\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n };\n readonly verifyMetadataContainer: (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead | undefined,\n ) => Promise<void>;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly targetSecretKey: Uint8Array;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/**\n * A group's signed name does not open under the metadata key it cites, or opens\n * to an invalid name. Every reader holding that key gets the same result. The\n * API checks the citation but can never check the ciphertext, so a dishonest\n * admin can sign such a name; directory walks isolate the group instead of\n * failing every name in the organization.\n */\nexport class GroupMetadataUnreadableError extends Error {\n constructor(groupId: string, cause: unknown) {\n super(`Group ${groupId} metadata cannot be decrypted`, { cause });\n this.name = \"GroupMetadataUnreadableError\";\n }\n}\n\nfunction loadMetadataKeyring(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n return withMetadataRootReload(\n () => loadMetadataKeyringOnce(input, containerId),\n () => input.apiClient.evictContainerWriterProjection(containerId),\n );\n}\n\nasync function loadMetadataKeyringOnce(\n input: GroupMetadataAccessInput,\n containerId: string,\n) {\n const projection =\n await input.apiClient.getContainerWriterProjection(containerId);\n if (!projection) return null;\n if (\n projection.containerId !== containerId ||\n projection.organizationId !== input.organizationId\n )\n throw new Error(\"Group metadata container is unavailable\");\n const target = getTargetContainerContext(projection);\n const state = readContainerState(target.manifest);\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n if (\n state.organizationId !== input.organizationId ||\n state.systemSlot !== slot ||\n state.parentContainerId !== null\n )\n throw new Error(\n \"Group metadata requires the signed organization metadata container\",\n );\n await input.verifyMetadataContainer(\n state,\n projection.policyEvidence.organization?.head,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keys = await unwrapContainerKekPath({\n ...input,\n projection,\n secretKey: input.targetSecretKey,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const keyMaterial = keys.get(target.kek.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata container key is unavailable\");\n return {\n current: {\n organizationId: input.organizationId,\n containerId,\n containerKeyEpochId: target.kek.containerKeyEpochId,\n keyMaterial,\n },\n keys,\n };\n}\n\n/** Uses the shared metadata container's authenticated keyring, including old epochs. */\nexport function createGroupMetadataAccess(input: GroupMetadataAccessInput) {\n const loads = new Map<\n string,\n Promise<{\n current: GroupMetadataKey;\n keys: ReadonlyMap<string, Uint8Array>;\n } | null>\n >();\n function loaded(containerId: string) {\n let pending = loads.get(containerId);\n if (!pending) {\n pending = loadMetadataKeyring(input, containerId);\n loads.set(containerId, pending);\n }\n return pending;\n }\n const readName: GroupPolicyNameReader = async (bundle) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n if (\"role\" in metadata)\n return metadata.role === \"admins\" ? \"Admins\" : \"Members\";\n if (\n metadata.organizationId !== input.organizationId ||\n metadata.groupId !== bundle.currentState.principalId ||\n bundle.currentState.principalType !== \"group\"\n )\n throw new Error(\"Group metadata scope does not match its signed group\");\n const keyring = await loaded(metadata.containerId);\n const keyMaterial = keyring?.keys.get(metadata.containerKeyEpochId);\n if (!keyMaterial)\n throw new Error(\"Group metadata historical key is unavailable\");\n try {\n return await decryptGroupMetadata({\n key: { ...metadata, keyMaterial },\n groupId: bundle.currentState.principalId,\n payload: bundle.currentPayload.ciphertext,\n });\n } catch (cause) {\n throw new GroupMetadataUnreadableError(\n bundle.currentState.principalId,\n cause,\n );\n }\n };\n return {\n readName,\n async loadEncryptionKey(): Promise<GroupMetadataKey> {\n const slot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.organizationId,\n });\n const containers = await loadContainers(input.execSql);\n const container = containers.find(\n (row) =>\n row.organizationId === input.organizationId &&\n row.systemSlot === slot,\n );\n if (!container)\n throw new Error(\n \"Organization metadata container has not been discovered\",\n );\n const keyring = await loaded(container.id);\n if (!keyring) throw new Error(\"Group metadata container is unavailable\");\n return keyring.current;\n },\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { persistVerifiedPrincipalPolicyBundlesAtomically } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js";
2
- import { retainLocallyAcknowledgedPrincipalPolicyBundles } from "../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
1
+ import { retainLocallyAcknowledgedPrincipalPolicyBundles } from "../../../data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js";
2
+ import { persistVerifiedPrincipalPolicyBundlesAtomically } from "../../../data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js";
3
3
  import { requireOrganizationGroupHead } from "../../../data/principals/organizationAuthorityDescriptor.js";
4
4
  import { externalAdminPolicyPersistenceEntries, loadOrganizationExternalAdminPolicy, } from "../../principals/externalAdminPolicy.js";
5
5
  import { assertGroupMetadataBinding } from "../groupMetadata/groupMetadataBinding.js";
@@ -1 +1 @@
1
- {"version":3,"file":"groupPolicyMutationContext.js","sourceRoot":"","sources":["groupPolicyMutationContext.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,+CAA+C,EAAE,MAAM,gFAAgF,CAAC;AACjJ,OAAO,EAAE,+CAA+C,EAAE,MAAM,sFAAs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ACD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC,CAAC;IACH,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import type {\n PrincipalPolicyCheckpoint,\n PrincipalPolicyExternalAuthority,\n ReferencedPrincipalHead,\n SigningKeyPair,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyBundleResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { persistVerifiedPrincipalPolicyBundlesAtomically } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence\";\nimport { retainLocallyAcknowledgedPrincipalPolicyBundles } from \"../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport { requireOrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../../principals/externalAdminPolicy\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport type {\n PrincipalPolicyReadApi,\n PrincipalPolicyReadWriteApi,\n} from \"../principalPolicy/principalPolicyApi\";\nimport { requireSignerCanManageGroup } from \"./groupMutationAuthorization\";\nimport {\n acknowledgeGroupPolicyState,\n assertGroupPolicyEnvelopesMatchAcknowledgement,\n buildAcknowledgedGroupPolicyBundle,\n} from \"./groupPolicyMutationAcknowledgement\";\nimport type { FullGroupMembershipMutationInput } from \"./groupPolicyMutationEvidence\";\nimport {\n assertPrincipalPolicyCurrentStateMatchesHead,\n groupPolicyMutationHead,\n} from \"./groupPolicyMutationHead\";\nimport {\n collectGroupPolicySignerPublicKeys,\n prepareGroupPolicyVerification,\n verifyGroupPolicy,\n verifyGroupPolicyWithExternalOrganizationAdmins,\n} from \"./groupPolicyVerification\";\nimport { submitGroupPolicyCommit } from \"./submitGroupPolicyCommit\";\n\nexport type {\n OrganizationPrincipalPolicyApi,\n PrincipalPolicyReadApi,\n PrincipalPolicyReadWriteApi,\n} from \"../principalPolicy/principalPolicyApi\";\nexport { submitGroupPolicyCommit } from \"./submitGroupPolicyCommit\";\n\ninterface LoadedGroupPolicyMutationContext\n extends FullGroupMembershipMutationInput {\n readonly adminGroupId: string;\n readonly adminPolicyBundle: PrincipalPolicyBundleResponse;\n readonly currentOrgAdminUserIds: readonly string[];\n readonly organizationDescriptor: VerifiedExternalAdminPolicy[\"descriptor\"];\n readonly organizationPolicyBundle: PrincipalPolicyBundleResponse;\n readonly memberGroupId: string;\n}\n\nexport async function cacheGroupPolicy(input: {\n readonly acknowledgedMemberEnvelopes?:\n | CurrentPrincipalMemberEnvelopesResponse\n | undefined;\n readonly apiClient: PrincipalPolicyReadApi;\n readonly externalAuthority?: PrincipalPolicyExternalAuthority | undefined;\n readonly execSql: ExecSql;\n readonly expectedCurrentHead?: ReferencedPrincipalHead | undefined;\n readonly groupId: string;\n readonly localPolicyCheckpoint?: PrincipalPolicyCheckpoint | null;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<PrincipalPolicyBundleResponse> {\n const bundle = await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n input.groupId,\n );\n\n if (!bundle) {\n throw new Error(\"Updated group policy could not be loaded\");\n }\n\n const signerPublicKeys = await collectGroupPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n const verified = await verifyGroupPolicy({\n currentPolicy: bundle,\n ...(input.externalAuthority\n ? { externalAuthority: input.externalAuthority }\n : {}),\n localPolicyCheckpoint: input.localPolicyCheckpoint ?? null,\n signerPublicKeys,\n });\n if (input.expectedCurrentHead) {\n assertPrincipalPolicyCurrentStateMatchesHead(\n bundle.currentState,\n input.expectedCurrentHead,\n );\n }\n if (input.acknowledgedMemberEnvelopes) {\n assertGroupPolicyEnvelopesMatchAcknowledgement(\n input.acknowledgedMemberEnvelopes,\n bundle.currentMemberEnvelopes,\n );\n }\n await persistVerifiedPrincipalPolicyBundlesAtomically({\n entries: [{ bundle, policy: verified }],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: new Date().toISOString(),\n });\n return bundle;\n}\n\nexport async function loadGroupPolicyMutationContext(input: {\n readonly apiClient: PrincipalPolicyReadApi;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<LoadedGroupPolicyMutationContext> {\n await input.apiClient.recoverPendingPrincipalMutation?.(input.organizationId);\n const adminPolicy = await loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.apiClient,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (!adminPolicy) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const expectedGroupHead = requireOrganizationGroupHead(\n adminPolicy.descriptor,\n input.groupId,\n );\n const currentPolicy =\n input.groupId === adminPolicy.adminGroupId\n ? adminPolicy.adminBundle\n : await input.apiClient.getCurrentPrincipalPolicy(\"group\", input.groupId);\n if (!currentPolicy) {\n throw new Error(\"Group policy could not be loaded\");\n }\n assertPrincipalPolicyCurrentStateMatchesHead(\n currentPolicy.currentState,\n expectedGroupHead,\n );\n const verification = await prepareGroupPolicyVerification({\n currentPolicy,\n execSql: input.execSql,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n const isOrganizationAdminsGroup = adminPolicy.adminGroupId === input.groupId;\n const currentOrgAdminUserIds = adminPolicy.signerUserIds;\n const externalAuthority = adminPolicy.externalAuthority;\n if (!currentOrgAdminUserIds.includes(input.signerUserId)) {\n throw new Error(\"Organization admin authority is required\");\n }\n const verified = isOrganizationAdminsGroup\n ? await verifyGroupPolicy({\n currentPolicy,\n localPolicyCheckpoint: verification.localPolicyCheckpoint,\n signerPublicKeys: verification.currentPolicySignerPublicKeys,\n })\n : await verifyGroupPolicyWithExternalOrganizationAdmins({\n currentPolicy,\n loadExternalAuthority: async () => externalAuthority,\n localPolicyCheckpoint: verification.localPolicyCheckpoint,\n signerPublicKeys: verification.currentPolicySignerPublicKeys,\n });\n assertGroupMetadataBinding(currentPolicy, adminPolicy.descriptor);\n requireSignerCanManageGroup(\n currentPolicy,\n currentOrgAdminUserIds,\n input.signerUserId,\n );\n await persistVerifiedPrincipalPolicyBundlesAtomically({\n entries: [\n ...externalAdminPolicyPersistenceEntries(adminPolicy).filter(\n (entry) =>\n entry.policy.principalType !== verified.principalType ||\n entry.policy.principalId !== verified.principalId,\n ),\n { bundle: currentPolicy, policy: verified },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n });\n\n return {\n adminGroupId: adminPolicy.adminGroupId,\n adminPolicyBundle: adminPolicy.adminBundle,\n currentPolicy,\n currentOrgAdminUserIds,\n externalAuthority,\n isOrganizationAdminsGroup,\n memberGroupId: adminPolicy.memberGroupId,\n organizationDescriptor: adminPolicy.descriptor,\n organizationPolicyBundle: adminPolicy.bundle,\n ...verification,\n localPolicyCheckpoint: verified.checkpoint,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n };\n}\n\nexport async function commitGroupPolicyMutation(input: {\n readonly retiredContainerIds?: (() => readonly string[]) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly expectedHead: ReferencedPrincipalHead;\n readonly groupId: string;\n readonly organizationId: string;\n readonly organizationPolicy: PrincipalPolicyBundleResponse;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n /**\n * Re-sign the batch with the descendant rekeys a refusal named woven in; the\n * result replaces `containerMutations` and the commit is retried once.\n */\n readonly carryDescendantRekeys?:\n | ((\n requiredContainerIds: readonly string[],\n ) => Promise<readonly ContainerMutationRequest[]>)\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const stored = await submitGroupPolicyCommit(input);\n if (!stored) {\n throw new Error(\"Group policy update failed\");\n }\n const storedPolicy = stored.groupPolicy;\n const acknowledgedPolicy = await acknowledgeGroupPolicyState({\n currentPolicy: input.currentPolicy,\n expectedHead: input.expectedHead,\n request: input.request,\n response: storedPolicy.currentState,\n });\n const groupBundle = buildAcknowledgedGroupPolicyBundle({\n currentPolicy: input.currentPolicy,\n expectedHead: input.expectedHead,\n request: input.request,\n response: storedPolicy,\n });\n const organizationHead = await groupPolicyMutationHead(\n input.organizationRequest,\n );\n const acknowledgedOrganization = await acknowledgeGroupPolicyState({\n currentPolicy: input.organizationPolicy,\n expectedHead: organizationHead,\n request: input.organizationRequest,\n response: stored.organizationPolicy.currentState,\n });\n const organizationBundle = buildAcknowledgedGroupPolicyBundle({\n currentPolicy: input.organizationPolicy,\n expectedHead: organizationHead,\n request: input.organizationRequest,\n response: stored.organizationPolicy,\n });\n await retainLocallyAcknowledgedPrincipalPolicyBundles({\n retiredContainers: {\n containerIds: input.retiredContainerIds?.() ?? [],\n organizationId: input.organizationId,\n policy: acknowledgedPolicy,\n },\n entries: [\n { bundle: groupBundle, policy: acknowledgedPolicy },\n {\n bundle: organizationBundle,\n policy: acknowledgedOrganization,\n },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: new Date().toISOString(),\n });\n return groupBundle;\n}\n"]}
1
+ {"version":3,"file":"groupPolicyMutationContext.js","sourceRoot":"","sources":["groupPolicyMutationContext.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,+CAA+C,EAAE,MAAM,yFAAyF,CAAC;AAC1J,OAAO,EAAE,+CAA+C,EAAE,MAAM,oFAAoF,CAAC;AACrJ,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AAGxG,OAAO,EACL,qCAAqC,EACrC,mCAAmC,GAEpC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AAKnF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EACL,2BAA2B,EAC3B,8CAA8C,EAC9C,kCAAkC,GACnC,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EACL,4CAA4C,EAC5C,uBAAuB,GACxB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAC9B,iBAAiB,EACjB,+CAA+C,GAChD,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAOpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAYpE,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,KAatC;IACC,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,yBAAyB,CAC5D,OAAO,EACP,KAAK,CAAC,OAAO,CACd,CAAC;IAEF,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;IAC9D,CAAC;IAED,MAAM,gBAAgB,GAAG,MAAM,kCAAkC,CAAC;QAChE,MAAM;QACN,0BAA0B,EAAE,KAAK,CAAC,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AE;YACjB,YAAY,EAAE,KAAK,CAAC,mBAAmB,EAAE,EAAE,IAAI,EAAE;YACjD,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,MAAM,EAAE,kBAAkB;SAC3B;QACD,OAAO,EAAE;YACP,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,kBAAkB,EAAE;YACnD;gBACE,MAAM,EAAE,kBAAkB;gBAC1B,MAAM,EAAE,wBAAwB;aACjC;SACF;QACD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC,CAAC;IACH,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import type {\n PrincipalPolicyCheckpoint,\n PrincipalPolicyExternalAuthority,\n ReferencedPrincipalHead,\n SigningKeyPair,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyBundleResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { retainLocallyAcknowledgedPrincipalPolicyBundles } from \"../../../data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence\";\nimport { persistVerifiedPrincipalPolicyBundlesAtomically } from \"../../../data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence\";\nimport { requireOrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../../principals/externalAdminPolicy\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport type {\n PrincipalPolicyReadApi,\n PrincipalPolicyReadWriteApi,\n} from \"../principalPolicy/principalPolicyApi\";\nimport { requireSignerCanManageGroup } from \"./groupMutationAuthorization\";\nimport {\n acknowledgeGroupPolicyState,\n assertGroupPolicyEnvelopesMatchAcknowledgement,\n buildAcknowledgedGroupPolicyBundle,\n} from \"./groupPolicyMutationAcknowledgement\";\nimport type { FullGroupMembershipMutationInput } from \"./groupPolicyMutationEvidence\";\nimport {\n assertPrincipalPolicyCurrentStateMatchesHead,\n groupPolicyMutationHead,\n} from \"./groupPolicyMutationHead\";\nimport {\n collectGroupPolicySignerPublicKeys,\n prepareGroupPolicyVerification,\n verifyGroupPolicy,\n verifyGroupPolicyWithExternalOrganizationAdmins,\n} from \"./groupPolicyVerification\";\nimport { submitGroupPolicyCommit } from \"./submitGroupPolicyCommit\";\n\nexport type {\n OrganizationPrincipalPolicyApi,\n PrincipalPolicyReadApi,\n PrincipalPolicyReadWriteApi,\n} from \"../principalPolicy/principalPolicyApi\";\nexport { submitGroupPolicyCommit } from \"./submitGroupPolicyCommit\";\n\ninterface LoadedGroupPolicyMutationContext\n extends FullGroupMembershipMutationInput {\n readonly adminGroupId: string;\n readonly adminPolicyBundle: PrincipalPolicyBundleResponse;\n readonly currentOrgAdminUserIds: readonly string[];\n readonly organizationDescriptor: VerifiedExternalAdminPolicy[\"descriptor\"];\n readonly organizationPolicyBundle: PrincipalPolicyBundleResponse;\n readonly memberGroupId: string;\n}\n\nexport async function cacheGroupPolicy(input: {\n readonly acknowledgedMemberEnvelopes?:\n | CurrentPrincipalMemberEnvelopesResponse\n | undefined;\n readonly apiClient: PrincipalPolicyReadApi;\n readonly externalAuthority?: PrincipalPolicyExternalAuthority | undefined;\n readonly execSql: ExecSql;\n readonly expectedCurrentHead?: ReferencedPrincipalHead | undefined;\n readonly groupId: string;\n readonly localPolicyCheckpoint?: PrincipalPolicyCheckpoint | null;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<PrincipalPolicyBundleResponse> {\n const bundle = await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n input.groupId,\n );\n\n if (!bundle) {\n throw new Error(\"Updated group policy could not be loaded\");\n }\n\n const signerPublicKeys = await collectGroupPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n const verified = await verifyGroupPolicy({\n currentPolicy: bundle,\n ...(input.externalAuthority\n ? { externalAuthority: input.externalAuthority }\n : {}),\n localPolicyCheckpoint: input.localPolicyCheckpoint ?? null,\n signerPublicKeys,\n });\n if (input.expectedCurrentHead) {\n assertPrincipalPolicyCurrentStateMatchesHead(\n bundle.currentState,\n input.expectedCurrentHead,\n );\n }\n if (input.acknowledgedMemberEnvelopes) {\n assertGroupPolicyEnvelopesMatchAcknowledgement(\n input.acknowledgedMemberEnvelopes,\n bundle.currentMemberEnvelopes,\n );\n }\n await persistVerifiedPrincipalPolicyBundlesAtomically({\n entries: [{ bundle, policy: verified }],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: new Date().toISOString(),\n });\n return bundle;\n}\n\nexport async function loadGroupPolicyMutationContext(input: {\n readonly apiClient: PrincipalPolicyReadApi;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<LoadedGroupPolicyMutationContext> {\n await input.apiClient.recoverPendingPrincipalMutation?.(input.organizationId);\n const adminPolicy = await loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.apiClient,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (!adminPolicy) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const expectedGroupHead = requireOrganizationGroupHead(\n adminPolicy.descriptor,\n input.groupId,\n );\n const currentPolicy =\n input.groupId === adminPolicy.adminGroupId\n ? adminPolicy.adminBundle\n : await input.apiClient.getCurrentPrincipalPolicy(\"group\", input.groupId);\n if (!currentPolicy) {\n throw new Error(\"Group policy could not be loaded\");\n }\n assertPrincipalPolicyCurrentStateMatchesHead(\n currentPolicy.currentState,\n expectedGroupHead,\n );\n const verification = await prepareGroupPolicyVerification({\n currentPolicy,\n execSql: input.execSql,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n const isOrganizationAdminsGroup = adminPolicy.adminGroupId === input.groupId;\n const currentOrgAdminUserIds = adminPolicy.signerUserIds;\n const externalAuthority = adminPolicy.externalAuthority;\n if (!currentOrgAdminUserIds.includes(input.signerUserId)) {\n throw new Error(\"Organization admin authority is required\");\n }\n const verified = isOrganizationAdminsGroup\n ? await verifyGroupPolicy({\n currentPolicy,\n localPolicyCheckpoint: verification.localPolicyCheckpoint,\n signerPublicKeys: verification.currentPolicySignerPublicKeys,\n })\n : await verifyGroupPolicyWithExternalOrganizationAdmins({\n currentPolicy,\n loadExternalAuthority: async () => externalAuthority,\n localPolicyCheckpoint: verification.localPolicyCheckpoint,\n signerPublicKeys: verification.currentPolicySignerPublicKeys,\n });\n assertGroupMetadataBinding(currentPolicy, adminPolicy.descriptor);\n requireSignerCanManageGroup(\n currentPolicy,\n currentOrgAdminUserIds,\n input.signerUserId,\n );\n await persistVerifiedPrincipalPolicyBundlesAtomically({\n entries: [\n ...externalAdminPolicyPersistenceEntries(adminPolicy).filter(\n (entry) =>\n entry.policy.principalType !== verified.principalType ||\n entry.policy.principalId !== verified.principalId,\n ),\n { bundle: currentPolicy, policy: verified },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n });\n\n return {\n adminGroupId: adminPolicy.adminGroupId,\n adminPolicyBundle: adminPolicy.adminBundle,\n currentPolicy,\n currentOrgAdminUserIds,\n externalAuthority,\n isOrganizationAdminsGroup,\n memberGroupId: adminPolicy.memberGroupId,\n organizationDescriptor: adminPolicy.descriptor,\n organizationPolicyBundle: adminPolicy.bundle,\n ...verification,\n localPolicyCheckpoint: verified.checkpoint,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n };\n}\n\nexport async function commitGroupPolicyMutation(input: {\n readonly retiredContainerIds?: (() => readonly string[]) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly expectedHead: ReferencedPrincipalHead;\n readonly groupId: string;\n readonly organizationId: string;\n readonly organizationPolicy: PrincipalPolicyBundleResponse;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n /**\n * Re-sign the batch with the descendant rekeys a refusal named woven in; the\n * result replaces `containerMutations` and the commit is retried once.\n */\n readonly carryDescendantRekeys?:\n | ((\n requiredContainerIds: readonly string[],\n ) => Promise<readonly ContainerMutationRequest[]>)\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const stored = await submitGroupPolicyCommit(input);\n if (!stored) {\n throw new Error(\"Group policy update failed\");\n }\n const storedPolicy = stored.groupPolicy;\n const acknowledgedPolicy = await acknowledgeGroupPolicyState({\n currentPolicy: input.currentPolicy,\n expectedHead: input.expectedHead,\n request: input.request,\n response: storedPolicy.currentState,\n });\n const groupBundle = buildAcknowledgedGroupPolicyBundle({\n currentPolicy: input.currentPolicy,\n expectedHead: input.expectedHead,\n request: input.request,\n response: storedPolicy,\n });\n const organizationHead = await groupPolicyMutationHead(\n input.organizationRequest,\n );\n const acknowledgedOrganization = await acknowledgeGroupPolicyState({\n currentPolicy: input.organizationPolicy,\n expectedHead: organizationHead,\n request: input.organizationRequest,\n response: stored.organizationPolicy.currentState,\n });\n const organizationBundle = buildAcknowledgedGroupPolicyBundle({\n currentPolicy: input.organizationPolicy,\n expectedHead: organizationHead,\n request: input.organizationRequest,\n response: stored.organizationPolicy,\n });\n await retainLocallyAcknowledgedPrincipalPolicyBundles({\n retiredContainers: {\n containerIds: input.retiredContainerIds?.() ?? [],\n organizationId: input.organizationId,\n policy: acknowledgedPolicy,\n },\n entries: [\n { bundle: groupBundle, policy: acknowledgedPolicy },\n {\n bundle: organizationBundle,\n policy: acknowledgedOrganization,\n },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: new Date().toISOString(),\n });\n return groupBundle;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
- import { persistLocallyAcknowledgedPrincipalPolicyBundles } from "../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
2
+ import { persistLocallyAcknowledgedPrincipalPolicyBundles } from "../../../data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js";
3
3
  import { loadOrganizationExternalAdminPolicy } from "../../principals/externalAdminPolicy.js";
4
4
  import { acknowledgeGroupPolicyState, buildAcknowledgedGroupPolicyBundle, } from "../groupPolicy/groupPolicyMutationAcknowledgement.js";
5
5
  import { groupPolicyMutationHead } from "../groupPolicy/groupPolicyMutationHead.js";
@@ -1 +1 @@
1
- {"version":3,"file":"deleteOrganizationGroup.js","sourceRoot":"","sources":["deleteOrganizationGroup.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,gDAAgD,EAAE,MAAM,sFAAsF,CAAC;AAGxJ,OAAO,EAAE,mCAAmC,EAAE,MAAM,sCAAsC,CAAC;AAC3F,OAAO,EACL,2BAA2B,EAC3B,kCAAkC,GACnC,MAAM,mDAAmD,CAAC;AAE3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF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C,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,EAAE,kBAAkB,EAAE,CAAC;QACrE,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QACnC,YAAY;KACb,CAAC,CAAC;IACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { DeleteOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport type { DeleteOrganizationGroupResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { persistLocallyAcknowledgedPrincipalPolicyBundles } from \"../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport {\n acknowledgeGroupPolicyState,\n buildAcknowledgedGroupPolicyBundle,\n} from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n removeOrganizationGroupHead,\n} from \"./organizationGroupDirectory\";\n\nexport async function deleteOrganizationGroup(input: {\n readonly apiClient: PrincipalPolicyReadApi & {\n deleteOrganizationGroup: (\n organizationId: string,\n groupId: string,\n request: DeleteOrganizationGroupRequest,\n ) => Promise<DeleteOrganizationGroupResponse | null>;\n };\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<DeleteOrganizationGroupResponse> {\n const stillCurrent = input.stillCurrent;\n assertProjectionVerificationCurrent(stillCurrent);\n await input.apiClient.recoverPendingPrincipalMutation?.(input.organizationId);\n assertProjectionVerificationCurrent(stillCurrent);\n const externalAdminPolicy = await loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.apiClient,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n if (!externalAdminPolicy?.signerUserIds.includes(input.signerUserId)) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const adminProjection = externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: externalAdminPolicy.bundle,\n descriptor: externalAdminPolicy.descriptor,\n groupHeads: removeOrganizationGroupHead({\n descriptor: externalAdminPolicy.descriptor,\n groupId: input.groupId,\n }),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const stored = await input.apiClient.deleteOrganizationGroup(\n input.organizationId,\n input.groupId,\n { organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be deleted\");\n }\n if (\n stored.organizationId !== input.organizationId ||\n stored.groupId !== input.groupId\n ) {\n throw new Error(\"Group deletion response target mismatch\");\n }\n const organizationHead = await groupPolicyMutationHead(organizationRequest);\n const organizationPolicy = await acknowledgeGroupPolicyState({\n currentPolicy: externalAdminPolicy.bundle,\n expectedHead: organizationHead,\n request: organizationRequest,\n response: stored.organizationPolicy.currentState,\n });\n const organizationBundle = buildAcknowledgedGroupPolicyBundle({\n currentPolicy: externalAdminPolicy.bundle,\n expectedHead: organizationHead,\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [{ bundle: organizationBundle, policy: organizationPolicy }],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return stored;\n}\n"]}
1
+ {"version":3,"file":"deleteOrganizationGroup.js","sourceRoot":"","sources":["deleteOrganizationGroup.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,gDAAgD,EAAE,MAAM,yFAAyF,CAAC;AAG3J,OAAO,EAAE,mCAAmC,EAAE,MAAM,sCAAsC,CAAC;AAC3F,OAAO,EACL,2BAA2B,EAC3B,kCAAkC,GACnC,MAAM,mDAAmD,CAAC;AAE3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,4CAA4C,EAC5C,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AAEtC,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,KAgB7C;IACC,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IACxC,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,MAAM,KAAK,CAAC,SAAS,CAAC,+BAA+B,EAAE,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;IAC9E,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,MAAM,mBAAmB,GAAG,MAAM,mCAAmC,CAAC;QACpE,mBAAmB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MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAChD,CAAC;IACD,IACE,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC9C,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,EAChC,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC7D,CAAC;IACD,MAAM,gBAAgB,GAAG,MAAM,uBAAuB,CAAC,mBAAmB,CAAC,CAAC;IAC5E,MAAM,kBAAkB,GAAG,MAAM,2BAA2B,CAAC;QAC3D,aAAa,EAAE,mBAAmB,CAAC,MAAM;QACzC,YAAY,EAAE,gBAAgB;QAC9B,OAAO,EAAE,mBAAmB;QAC5B,QAAQ,EAAE,MAAM,CAAC,kBAAkB,CAAC,YAAY;KACjD,CAAC,CAAC;IACH,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;QAC5D,aAAa,EAAE,mBAAmB,CAAC,MAAM;QACzC,YAAY,EAAE,gBAAgB;QAC9B,OAAO,EAAE,mBAAmB;QAC5B,QAAQ,EAAE,MAAM,CAAC,kBAAkB;KACpC,CAAC,CAAC;IACH,MAAM,gDAAgD,CAAC;QACrD,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,EAAE,kBAAkB,EAAE,CAAC;QACrE,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QACnC,YAAY;KACb,CAAC,CAAC;IACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { DeleteOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport type { DeleteOrganizationGroupResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { persistLocallyAcknowledgedPrincipalPolicyBundles } from \"../../../data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport {\n acknowledgeGroupPolicyState,\n buildAcknowledgedGroupPolicyBundle,\n} from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n removeOrganizationGroupHead,\n} from \"./organizationGroupDirectory\";\n\nexport async function deleteOrganizationGroup(input: {\n readonly apiClient: PrincipalPolicyReadApi & {\n deleteOrganizationGroup: (\n organizationId: string,\n groupId: string,\n request: DeleteOrganizationGroupRequest,\n ) => Promise<DeleteOrganizationGroupResponse | null>;\n };\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<DeleteOrganizationGroupResponse> {\n const stillCurrent = input.stillCurrent;\n assertProjectionVerificationCurrent(stillCurrent);\n await input.apiClient.recoverPendingPrincipalMutation?.(input.organizationId);\n assertProjectionVerificationCurrent(stillCurrent);\n const externalAdminPolicy = await loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.apiClient,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n if (!externalAdminPolicy?.signerUserIds.includes(input.signerUserId)) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const adminProjection = externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: externalAdminPolicy.bundle,\n descriptor: externalAdminPolicy.descriptor,\n groupHeads: removeOrganizationGroupHead({\n descriptor: externalAdminPolicy.descriptor,\n groupId: input.groupId,\n }),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const stored = await input.apiClient.deleteOrganizationGroup(\n input.organizationId,\n input.groupId,\n { organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be deleted\");\n }\n if (\n stored.organizationId !== input.organizationId ||\n stored.groupId !== input.groupId\n ) {\n throw new Error(\"Group deletion response target mismatch\");\n }\n const organizationHead = await groupPolicyMutationHead(organizationRequest);\n const organizationPolicy = await acknowledgeGroupPolicyState({\n currentPolicy: externalAdminPolicy.bundle,\n expectedHead: organizationHead,\n request: organizationRequest,\n response: stored.organizationPolicy.currentState,\n });\n const organizationBundle = buildAcknowledgedGroupPolicyBundle({\n currentPolicy: externalAdminPolicy.bundle,\n expectedHead: organizationHead,\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [{ bundle: organizationBundle, policy: organizationPolicy }],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return stored;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { buildPrincipalStateSigningInput, generateKemSeedAndKeyPair, normalizePrincipalProjectionMembers, signPrincipalState, toFingerprint, } from "../../../internal/crypto/index.js";
2
2
  import { bytesToBase64 } from "../../../internal/encoding/index.js";
3
3
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
4
- import { persistLocallyAcknowledgedPrincipalPolicyBundles } from "../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
4
+ import { persistLocallyAcknowledgedPrincipalPolicyBundles } from "../../../data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js";
5
5
  import { encodeOrganizationAuthorityDescriptor, normalizeOrganizationGroupHeads, } from "../../../data/principals/organizationAuthorityDescriptor.js";
6
6
  import { assertGroupNameUniqueInDirectory } from "../groupNames/groupNameUniqueness.js";
7
7
  import { acknowledgeGroupPolicyState, acknowledgeInitialGroupPolicy, buildAcknowledgedGroupPolicyBundle, } from "../groupPolicy/groupPolicyMutationAcknowledgement.js";
@@ -1 +1 @@
1
- {"version":3,"file":"organizationGroupDirectory.js","sourceRoot":"","sources":["organizationGroupDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,mCAAmC,EAGnC,kBAAkB,EAClB,aAAa,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AASpD,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,gDAAgD,EAAE,MAAM,sFAAsF,CAAC;AACxJ,OAAO,EACL,qCAAqC,EACrC,+BAA+B,GAGhC,MAAM,0DAA0D,CAAC;AAQlE,OAAO,EAAE,gCAAgC,EAAE,MAAM,mCAAmC,CAAC;AACrF,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,EAC7B,kCAAkC,GACnC,MAAM,mDAAmD,CAAC;AAE3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,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,GAAG,MAAM,2BAA2B,CAAC;QAC3D,aAAa,EAAE,KAAK,CAAC,mBAAmB,CAAC,MAAM;QAC/C,YAAY,EAAE,gBAAgB;QAC9B,OAAO,EAAE,mBAAmB;QAC5B,QAAQ,EAAE,MAAM,CAAC,kBAAkB,CAAC,YAAY;KACjD,CAAC,CAAC;IACH,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;QAC5D,aAAa,EAAE,KAAK,CAAC,mBAAmB,CAAC,MAAM;QAC/C,YAAY,EAAE,gBAAgB;QAC9B,OAAO,EAAE,mBAAmB;QAC5B,QAAQ,EAAE,MAAM,CAAC,kBAAkB;KACpC,CAAC,CAAC;IACH,MAAM,gDAAgD,CAAC;QACrD,OAAO,EAAE;YACP,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE;YAC5D,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,EAAE,kBAAkB,EAAE;SAC3D;QACD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QACnC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;AACrD,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n OrganizationGroupSummaryResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { persistLocallyAcknowledgedPrincipalPolicyBundles } from \"../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport type { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport { assertGroupNameUniqueInDirectory } from \"../groupNames/groupNameUniqueness\";\nimport {\n acknowledgeGroupPolicyState,\n acknowledgeInitialGroupPolicy,\n buildAcknowledgedGroupPolicyBundle,\n} from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { OrganizationPrincipalPolicyApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport { rewrapProjectionMemberEnvelopes } from \"../principalPolicy/principalPolicyRecipients\";\nimport type {\n buildInitialGroupPolicyRequest,\n GroupPolicyNameReader,\n} from \"../principalPolicy/principalPolicyRequest\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\nfunction 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\nexport function removeOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupId: string;\n}): OrganizationGroupHead[] {\n if (\n input.groupId === input.descriptor.adminGroupId ||\n input.groupId === input.descriptor.memberGroupId\n ) {\n throw new Error(\"Built-in groups cannot be removed from the directory\");\n }\n const groupHeads = input.descriptor.groupHeads.filter(\n (head) => head.principalId !== input.groupId,\n );\n if (groupHeads.length === input.descriptor.groupHeads.length) {\n throw new Error(\"Organization directory does not commit the deleted group\");\n }\n return normalizeOrganizationGroupHeads(groupHeads);\n}\n\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\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 organizationKem = generateKemSeedAndKeyPair();\n const memberEnvelopes = await rewrapProjectionMemberEnvelopes({\n projection,\n secretKey: organizationKem.secretKey,\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: input.currentPolicy.currentState.keyEpoch + 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: projection.map((member) => ({ userId: member.userId })),\n 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,\n projection,\n state,\n };\n}\n\nexport async function commitCreatedGroupToDirectory(input: {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly name: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly apiClient: OrganizationPrincipalPolicyApi;\n readonly execSql: ExecSql;\n readonly externalAdminPolicy: NonNullable<\n Awaited<ReturnType<typeof loadOrganizationExternalAdminPolicy>>\n >;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly request: Awaited<ReturnType<typeof buildInitialGroupPolicyRequest>>;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<{\n readonly group: OrganizationGroupSummaryResponse;\n readonly head: ReferencedPrincipalHead;\n}> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Signed group names are unique per organization; refuse a collision before\n // anything reaches the server.\n await assertGroupNameUniqueInDirectory({\n apiClient: input.apiClient,\n descriptor: input.externalAdminPolicy.descriptor,\n execSql: input.execSql,\n externalAuthority: input.externalAdminPolicy.externalAuthority,\n name: input.name,\n readEncryptedName: input.readEncryptedName,\n organizationId: input.organizationId,\n reportSecurityIncident: input.reportSecurityIncident,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n const expectedHead = await groupPolicyMutationHead(\n input.request.initialGroupPolicy,\n );\n const adminProjection =\n input.externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: input.externalAdminPolicy.bundle,\n descriptor: input.externalAdminPolicy.descriptor,\n groupHeads: [\n ...input.externalAdminPolicy.descriptor.groupHeads,\n organizationGroupHead(expectedHead),\n ],\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const stored = await input.apiClient.createOrganizationGroup(\n input.organizationId,\n { ...input.request, organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be created\");\n }\n const acknowledged = await acknowledgeInitialGroupPolicy({\n organizationId: input.organizationId,\n request: input.request,\n response: stored.group,\n stateHash: expectedHead.stateHash,\n });\n const organizationHead = await groupPolicyMutationHead(organizationRequest);\n const organizationPolicy = await acknowledgeGroupPolicyState({\n currentPolicy: input.externalAdminPolicy.bundle,\n expectedHead: organizationHead,\n request: organizationRequest,\n response: stored.organizationPolicy.currentState,\n });\n const organizationBundle = buildAcknowledgedGroupPolicyBundle({\n currentPolicy: input.externalAdminPolicy.bundle,\n expectedHead: organizationHead,\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [\n { bundle: acknowledged.bundle, policy: acknowledged.policy },\n { bundle: organizationBundle, policy: organizationPolicy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { group: stored.group, head: expectedHead };\n}\n"]}
1
+ {"version":3,"file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AAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QACnC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;AACrD,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n OrganizationGroupSummaryResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { persistLocallyAcknowledgedPrincipalPolicyBundles } from \"../../../data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport type { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport { assertGroupNameUniqueInDirectory } from \"../groupNames/groupNameUniqueness\";\nimport {\n acknowledgeGroupPolicyState,\n acknowledgeInitialGroupPolicy,\n buildAcknowledgedGroupPolicyBundle,\n} from \"../groupPolicy/groupPolicyMutationAcknowledgement\";\nimport type { OrganizationPrincipalPolicyApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"../groupPolicy/groupPolicyMutationHead\";\nimport { rewrapProjectionMemberEnvelopes } from \"../principalPolicy/principalPolicyRecipients\";\nimport type {\n buildInitialGroupPolicyRequest,\n GroupPolicyNameReader,\n} from \"../principalPolicy/principalPolicyRequest\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../trustedOrganizationUsers\";\n\nfunction 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\nexport function removeOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupId: string;\n}): OrganizationGroupHead[] {\n if (\n input.groupId === input.descriptor.adminGroupId ||\n input.groupId === input.descriptor.memberGroupId\n ) {\n throw new Error(\"Built-in groups cannot be removed from the directory\");\n }\n const groupHeads = input.descriptor.groupHeads.filter(\n (head) => head.principalId !== input.groupId,\n );\n if (groupHeads.length === input.descriptor.groupHeads.length) {\n throw new Error(\"Organization directory does not commit the deleted group\");\n }\n return normalizeOrganizationGroupHeads(groupHeads);\n}\n\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\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 organizationKem = generateKemSeedAndKeyPair();\n const memberEnvelopes = await rewrapProjectionMemberEnvelopes({\n projection,\n secretKey: organizationKem.secretKey,\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: input.currentPolicy.currentState.keyEpoch + 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: projection.map((member) => ({ userId: member.userId })),\n 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,\n projection,\n state,\n };\n}\n\nexport async function commitCreatedGroupToDirectory(input: {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly name: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly apiClient: OrganizationPrincipalPolicyApi;\n readonly execSql: ExecSql;\n readonly externalAdminPolicy: NonNullable<\n Awaited<ReturnType<typeof loadOrganizationExternalAdminPolicy>>\n >;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly request: Awaited<ReturnType<typeof buildInitialGroupPolicyRequest>>;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<{\n readonly group: OrganizationGroupSummaryResponse;\n readonly head: ReferencedPrincipalHead;\n}> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Signed group names are unique per organization; refuse a collision before\n // anything reaches the server.\n await assertGroupNameUniqueInDirectory({\n apiClient: input.apiClient,\n descriptor: input.externalAdminPolicy.descriptor,\n execSql: input.execSql,\n externalAuthority: input.externalAdminPolicy.externalAuthority,\n name: input.name,\n readEncryptedName: input.readEncryptedName,\n organizationId: input.organizationId,\n reportSecurityIncident: input.reportSecurityIncident,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n const expectedHead = await groupPolicyMutationHead(\n input.request.initialGroupPolicy,\n );\n const adminProjection =\n input.externalAdminPolicy.adminBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: input.externalAdminPolicy.bundle,\n descriptor: input.externalAdminPolicy.descriptor,\n groupHeads: [\n ...input.externalAdminPolicy.descriptor.groupHeads,\n organizationGroupHead(expectedHead),\n ],\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const stored = await input.apiClient.createOrganizationGroup(\n input.organizationId,\n { ...input.request, organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!stored) {\n throw new Error(\"Group could not be created\");\n }\n const acknowledged = await acknowledgeInitialGroupPolicy({\n organizationId: input.organizationId,\n request: input.request,\n response: stored.group,\n stateHash: expectedHead.stateHash,\n });\n const organizationHead = await groupPolicyMutationHead(organizationRequest);\n const organizationPolicy = await acknowledgeGroupPolicyState({\n currentPolicy: input.externalAdminPolicy.bundle,\n expectedHead: organizationHead,\n request: organizationRequest,\n response: stored.organizationPolicy.currentState,\n });\n const organizationBundle = buildAcknowledgedGroupPolicyBundle({\n currentPolicy: input.externalAdminPolicy.bundle,\n expectedHead: organizationHead,\n request: organizationRequest,\n response: stored.organizationPolicy,\n });\n await persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [\n { bundle: acknowledged.bundle, policy: acknowledged.policy },\n { bundle: organizationBundle, policy: organizationPolicy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { group: stored.group, head: expectedHead };\n}\n"]}
@@ -3,8 +3,8 @@ import type { CreateOrganizationRequest } from "../../../internal/validators/req
3
3
  import type { CreateOrganizationResponse } from "../../../internal/validators/response/index.js";
4
4
  import type { DocumentProjectorRegistryInput } from "../../../data/documents/documentKinds.js";
5
5
  import type { ExecSqlClientLike } from "../../../data/sqlite/sqlSchema.js";
6
+ import { type ProvisionedSystemContainerSpec } from "../../registration/organizationProvisioning.js";
6
7
  import type { ProvisionedPrincipalHistoryPrimer } from "../../registration/provisionedPrincipalHistory.js";
7
- import { type ProvisionedSystemContainerSpec } from "../../registration/registerIdentity.js";
8
8
  import { removeNativeSubscriptionRestoreProvisioningAttempt } from "./organizationProvisioningAttempt.js";
9
9
  export { removeNativeSubscriptionRestoreProvisioningAttempt };
10
10
  export interface CreateOrganizationApi {
@@ -1,6 +1,6 @@
1
1
  import { signOrganizationReplacementAuthorization, } from "../../../internal/crypto/index.js";
2
2
  import { createExecSql } from "../../../data/sqlite/sqlSchema.js";
3
- import { buildOrganizationProvisioningArtifacts, persistOrganizationProvisioningState, } from "../../registration/registerIdentity.js";
3
+ import { buildOrganizationProvisioningArtifacts, persistOrganizationProvisioningState, } from "../../registration/organizationProvisioning.js";
4
4
  import { makeOrganizationProvisioningAttemptDurable, removeNativeSubscriptionRestoreProvisioningAttempt, } from "./organizationProvisioningAttempt.js";
5
5
  import { pinOrganizationReplacementResponse } from "./organizationReplacementVerification.js";
6
6
  export { removeNativeSubscriptionRestoreProvisioningAttempt };
@@ -1 +1 @@
1
- {"version":3,"file":"createOrganization.js","sourceRoot":"","sources":["createOrganization.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAE/D,OAAO,EACL,sCAAsC,EAItC,oCAAoC,GACrC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,0CAA0C,EAC1C,kDAAkD,GACnD,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,kCAAkC,EAAE,MAAM,uCAAuC,CAAC;AAE3F,OAAO,EAAE,kDAAkD,EAAE,CAAC;AAoD9D,SAAS,4BAA4B,CAAC,KAIrC;IACC,IACE,KAAK,CAAC,QAAQ,CAAC,cAAc,KAAK,KAAK,CAAC,OAAO,CAAC,cAAc;QAC9D,KAAK,CAAC,QAAQ,CAAC,eAAe,KAAK,KAAK,CAAC,OAAO,CAAC,eAAe,EAChE,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IACE,CAAC,KAAK,CAAC,QAAQ,CAAC,sBAAsB;QACtC,KAAK,CAAC,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,QAAQ,CAAC,MAAM,EAC/C,CAAC;QACD,MAAM,IAAI,KAAK,CACb,+DAA+D,CAChE,CAAC;IACJ,CAAC;IACD,KAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,CAClB,qCAAqC,KAAK,CAAC,QAAQ,CAAC,cAAc,GAAG,CACtE,CAAC;IACF,OAAO,IAA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eyPair,\n signOrganizationReplacementAuthorization,\n} from \"@tearleads/crypto\";\nimport type { CreateOrganizationRequest } from \"@tearleads/validators/request\";\nimport type { CreateOrganizationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { ProvisionedPrincipalHistoryPrimer } from \"../../registration/provisionedPrincipalHistory\";\nimport {\n buildOrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifactsInput,\n type ProvisionedSystemContainerSpec,\n persistOrganizationProvisioningState,\n} from \"../../registration/registerIdentity\";\nimport {\n makeOrganizationProvisioningAttemptDurable,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationProvisioningAttempt\";\nimport { pinOrganizationReplacementResponse } from \"./organizationReplacementVerification\";\n\nexport { removeNativeSubscriptionRestoreProvisioningAttempt };\n\nexport interface CreateOrganizationApi {\n createOrganization(\n request: CreateOrganizationRequest,\n ): Promise<CreateOrganizationResponse | null>;\n}\n\nexport interface CreateOrganizationInput {\n apiClient: CreateOrganizationApi;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n /**\n * Returns false once the identity that supplied the key pairs is no longer\n * active. Checked before the remote create (so a stale request is never\n * submitted) and again before local persistence: an identity switch closes\n * or renews the captured database client, so persisting would write another\n * identity's bootstrap — or throw — after the org already exists remotely.\n * The caller discards the result.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /** Overrides the seeded organization profile name; see registration. */\n organizationProfileName?: string | undefined;\n /** Seeds verified recovery progress for the founding policy heads. */\n primePrincipalHistory?: ProvisionedPrincipalHistoryPrimer | undefined;\n /**\n * App-owned system containers to provision atomically with the new\n * organization (e.g. a trash bin). See registration.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /** Purged organization whose personal-org generation this replaces. */\n replacesOrganizationId?: string | undefined;\n /** Marks and durably replays a fresh native-subscription restore target. */\n nativeSubscriptionRestore?: boolean | undefined;\n /** Overrides the seeded self roster-profile nickname; see registration. */\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n /**\n * The already-registered user creating the organization; they become its\n * founding admin. The server independently requires this to match the\n * authenticated session.\n */\n userId: string;\n}\n\nfunction isAdoptedReplacementResponse(input: {\n creation: CreateOrganizationInput;\n request: CreateOrganizationRequest;\n response: CreateOrganizationResponse;\n}): boolean {\n if (\n input.response.organizationId === input.request.organizationId &&\n input.response.rootContainerId === input.request.rootContainerId\n ) {\n return false;\n }\n if (\n !input.creation.replacesOrganizationId ||\n input.response.userId !== input.creation.userId\n ) {\n throw new Error(\n \"Organization provisioning returned an unexpected organization\",\n );\n }\n input.creation.log?.(\n `Organization replacement adopted (${input.response.organizationId})`,\n );\n return true;\n}\n\nasync function buildOrganizationCandidate(\n input: CreateOrganizationInput,\n rootContainerId: string,\n): Promise<OrganizationProvisioningArtifacts | null> {\n const artifactsInput: OrganizationProvisioningArtifactsInput = {\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n };\n const artifacts: OrganizationProvisioningArtifacts =\n await buildOrganizationProvisioningArtifacts(artifactsInput);\n\n if (input.replacesOrganizationId) {\n artifacts.replacementAuthorization =\n await signOrganizationReplacementAuthorization(\n {\n ...artifacts,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n },\n input.signingKeyPair,\n );\n }\n\n if (\n input.replacesOrganizationId &&\n input.isIdentityCurrent &&\n !input.isIdentityCurrent()\n ) {\n input.log?.(\n \"Organization creation aborted: identity changed while building artifacts\",\n );\n return null;\n }\n\n return artifacts;\n}\n\n/**\n * Provisions an additional organization for an already-registered user, reusing\n * the exact artifact-build and local-persistence path as registration\n * ({@link buildOrganizationProvisioningArtifacts} /\n * {@link persistOrganizationProvisioningState}). Unlike registration it mints a\n * fresh root container id, signs with the caller's existing identity, and needs\n * no auth challenge — the user is already authenticated.\n */\nexport async function createOrganization(\n input: CreateOrganizationInput,\n): Promise<CreateOrganizationResponse | null> {\n input.log?.(\"Creating organization...\");\n\n const rootContainerId = crypto.randomUUID();\n const candidateArtifacts = await buildOrganizationCandidate(\n input,\n rootContainerId,\n );\n\n if (!candidateArtifacts) return null;\n\n const durableAttempt = await makeOrganizationProvisioningAttemptDurable({\n artifacts: candidateArtifacts,\n canStartDurableMutation: input.isIdentityCurrent,\n dbClient: input.dbClient,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n });\n if (!durableAttempt) {\n input.log?.(\n \"Organization creation aborted: identity changed before saving artifacts\",\n );\n return null;\n }\n const {\n artifacts,\n request,\n rootContainerId: durableRootContainerId,\n } = durableAttempt;\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation aborted: identity changed before provisioning\",\n );\n return null;\n }\n\n const response = await input.apiClient.createOrganization(request);\n if (!response) {\n return null;\n }\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation discarded: identity changed while provisioning\",\n );\n return null;\n }\n\n if (\n input.replacesOrganizationId &&\n !(await pinOrganizationReplacementResponse({\n replacesOrganizationId: input.replacesOrganizationId,\n response,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n userId: input.userId,\n execSql: createExecSql(input.dbClient),\n stillCurrent: input.isIdentityCurrent,\n }))\n )\n return null;\n\n if (isAdoptedReplacementResponse({ creation: input, request, response })) {\n // Another device authorized this winning genesis with the same identity.\n // Its encrypted bootstrap will hydrate normally; persisting\n // this device's losing candidate would instead create an unrelated local\n // root. The session reset rebinds retained local data to the winning ids.\n return response;\n }\n\n input.log?.(`Organization created (${response.organizationId})`);\n await persistOrganizationProvisioningState({\n bootstrap: artifacts.bootstrap,\n canStartDurableMutation: input.isIdentityCurrent,\n onPersistQueued: input.onPersistQueued,\n containerId: durableRootContainerId,\n dbClient: input.dbClient,\n documentProjectors: input.documentProjectors,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n log: input.log,\n logError: input.logError,\n organizationMetadataBootstrap: artifacts.organizationMetadataBootstrap,\n primePrincipalHistory: input.primePrincipalHistory,\n response,\n rootContainer: artifacts.rootContainer,\n rootMetadataDocument: artifacts.rootMetadataDocument,\n rootMetadataDocumentRequest: artifacts.rootMetadataDocumentRequest,\n rosterProfileBootstrap: artifacts.rosterProfileBootstrap,\n systemContainerBootstraps: artifacts.systemContainerBootstraps,\n });\n\n return response;\n}\n"]}
1
+ {"version":3,"file":"createOrganization.js","sourceRoot":"","sources":["createOrganization.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EACL,sCAAsC,EAItC,oCAAoC,GACrC,MAAM,6CAA6C,CAAC;AAErD,OAAO,EACL,0CAA0C,EAC1C,kDAAkD,GACnD,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,kCAAkC,EAAE,MAAM,uCAAuC,CAAC;AAE3F,OAAO,EAAE,kDAAkD,EAAE,CAAC;AAoD9D,SAAS,4BAA4B,CAAC,KAIrC;IACC,IACE,KAAK,CAAC,QAAQ,CAAC,cAAc,K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,yBAAyB;QAC9D,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,6BAA6B,EAAE,SAAS,CAAC,6BAA6B;QACtE,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,QAAQ;QACR,aAAa,EAAE,SAAS,CAAC,aAAa;QACtC,oBAAoB,EAAE,SAAS,CAAC,oBAAoB;QACpD,2BAA2B,EAAE,SAAS,CAAC,2BAA2B;QAClE,sBAAsB,EAAE,SAAS,CAAC,sBAAsB;QACxD,yBAAyB,EAAE,SAAS,CAAC,yBAAyB;KAC/D,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n type EncapsulationKeyPair,\n type SigningKeyPair,\n signOrganizationReplacementAuthorization,\n} from \"@tearleads/crypto\";\nimport type { CreateOrganizationRequest } from \"@tearleads/validators/request\";\nimport type { CreateOrganizationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifactsInput,\n type ProvisionedSystemContainerSpec,\n persistOrganizationProvisioningState,\n} from \"../../registration/organizationProvisioning\";\nimport type { ProvisionedPrincipalHistoryPrimer } from \"../../registration/provisionedPrincipalHistory\";\nimport {\n makeOrganizationProvisioningAttemptDurable,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationProvisioningAttempt\";\nimport { pinOrganizationReplacementResponse } from \"./organizationReplacementVerification\";\n\nexport { removeNativeSubscriptionRestoreProvisioningAttempt };\n\nexport interface CreateOrganizationApi {\n createOrganization(\n request: CreateOrganizationRequest,\n ): Promise<CreateOrganizationResponse | null>;\n}\n\nexport interface CreateOrganizationInput {\n apiClient: CreateOrganizationApi;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n /**\n * Returns false once the identity that supplied the key pairs is no longer\n * active. Checked before the remote create (so a stale request is never\n * submitted) and again before local persistence: an identity switch closes\n * or renews the captured database client, so persisting would write another\n * identity's bootstrap — or throw — after the org already exists remotely.\n * The caller discards the result.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /** Overrides the seeded organization profile name; see registration. */\n organizationProfileName?: string | undefined;\n /** Seeds verified recovery progress for the founding policy heads. */\n primePrincipalHistory?: ProvisionedPrincipalHistoryPrimer | undefined;\n /**\n * App-owned system containers to provision atomically with the new\n * organization (e.g. a trash bin). See registration.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /** Purged organization whose personal-org generation this replaces. */\n replacesOrganizationId?: string | undefined;\n /** Marks and durably replays a fresh native-subscription restore target. */\n nativeSubscriptionRestore?: boolean | undefined;\n /** Overrides the seeded self roster-profile nickname; see registration. */\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n /**\n * The already-registered user creating the organization; they become its\n * founding admin. The server independently requires this to match the\n * authenticated session.\n */\n userId: string;\n}\n\nfunction isAdoptedReplacementResponse(input: {\n creation: CreateOrganizationInput;\n request: CreateOrganizationRequest;\n response: CreateOrganizationResponse;\n}): boolean {\n if (\n input.response.organizationId === input.request.organizationId &&\n input.response.rootContainerId === input.request.rootContainerId\n ) {\n return false;\n }\n if (\n !input.creation.replacesOrganizationId ||\n input.response.userId !== input.creation.userId\n ) {\n throw new Error(\n \"Organization provisioning returned an unexpected organization\",\n );\n }\n input.creation.log?.(\n `Organization replacement adopted (${input.response.organizationId})`,\n );\n return true;\n}\n\nasync function buildOrganizationCandidate(\n input: CreateOrganizationInput,\n rootContainerId: string,\n): Promise<OrganizationProvisioningArtifacts | null> {\n const artifactsInput: OrganizationProvisioningArtifactsInput = {\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n };\n const artifacts: OrganizationProvisioningArtifacts =\n await buildOrganizationProvisioningArtifacts(artifactsInput);\n\n if (input.replacesOrganizationId) {\n artifacts.replacementAuthorization =\n await signOrganizationReplacementAuthorization(\n {\n ...artifacts,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n },\n input.signingKeyPair,\n );\n }\n\n if (\n input.replacesOrganizationId &&\n input.isIdentityCurrent &&\n !input.isIdentityCurrent()\n ) {\n input.log?.(\n \"Organization creation aborted: identity changed while building artifacts\",\n );\n return null;\n }\n\n return artifacts;\n}\n\n/**\n * Provisions an additional organization for an already-registered user, reusing\n * the exact artifact-build and local-persistence path as registration\n * ({@link buildOrganizationProvisioningArtifacts} /\n * {@link persistOrganizationProvisioningState}). Unlike registration it mints a\n * fresh root container id, signs with the caller's existing identity, and needs\n * no auth challenge — the user is already authenticated.\n */\nexport async function createOrganization(\n input: CreateOrganizationInput,\n): Promise<CreateOrganizationResponse | null> {\n input.log?.(\"Creating organization...\");\n\n const rootContainerId = crypto.randomUUID();\n const candidateArtifacts = await buildOrganizationCandidate(\n input,\n rootContainerId,\n );\n\n if (!candidateArtifacts) return null;\n\n const durableAttempt = await makeOrganizationProvisioningAttemptDurable({\n artifacts: candidateArtifacts,\n canStartDurableMutation: input.isIdentityCurrent,\n dbClient: input.dbClient,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n });\n if (!durableAttempt) {\n input.log?.(\n \"Organization creation aborted: identity changed before saving artifacts\",\n );\n return null;\n }\n const {\n artifacts,\n request,\n rootContainerId: durableRootContainerId,\n } = durableAttempt;\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation aborted: identity changed before provisioning\",\n );\n return null;\n }\n\n const response = await input.apiClient.createOrganization(request);\n if (!response) {\n return null;\n }\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation discarded: identity changed while provisioning\",\n );\n return null;\n }\n\n if (\n input.replacesOrganizationId &&\n !(await pinOrganizationReplacementResponse({\n replacesOrganizationId: input.replacesOrganizationId,\n response,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n userId: input.userId,\n execSql: createExecSql(input.dbClient),\n stillCurrent: input.isIdentityCurrent,\n }))\n )\n return null;\n\n if (isAdoptedReplacementResponse({ creation: input, request, response })) {\n // Another device authorized this winning genesis with the same identity.\n // Its encrypted bootstrap will hydrate normally; persisting\n // this device's losing candidate would instead create an unrelated local\n // root. The session reset rebinds retained local data to the winning ids.\n return response;\n }\n\n input.log?.(`Organization created (${response.organizationId})`);\n await persistOrganizationProvisioningState({\n bootstrap: artifacts.bootstrap,\n canStartDurableMutation: input.isIdentityCurrent,\n onPersistQueued: input.onPersistQueued,\n containerId: durableRootContainerId,\n dbClient: input.dbClient,\n documentProjectors: input.documentProjectors,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n log: input.log,\n logError: input.logError,\n organizationMetadataBootstrap: artifacts.organizationMetadataBootstrap,\n primePrincipalHistory: input.primePrincipalHistory,\n response,\n rootContainer: artifacts.rootContainer,\n rootMetadataDocument: artifacts.rootMetadataDocument,\n rootMetadataDocumentRequest: artifacts.rootMetadataDocumentRequest,\n rosterProfileBootstrap: artifacts.rosterProfileBootstrap,\n systemContainerBootstraps: artifacts.systemContainerBootstraps,\n });\n\n return response;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { type CreateOrganizationRequest } from "../../../internal/validators/request/index.js";
2
2
  import type { ExecSql, ExecSqlClientLike } from "../../../data/sqlite/sqlSchema.js";
3
- import type { OrganizationProvisioningArtifacts } from "../../registration/registerIdentity.js";
3
+ import type { OrganizationProvisioningArtifacts } from "../../registration/organizationProvisioning.js";
4
4
  interface DurableOrganizationProvisioningAttempt {
5
5
  readonly artifacts: OrganizationProvisioningArtifacts;
6
6
  readonly request: CreateOrganizationRequest;
@@ -1 +1 @@
1
- {"version":3,"file":"organizationProvisioningAttempt.js","sourceRoot":"","sources":["organizationProvisioningAttempt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAEL,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sCAAsC,EAAE,MAAM,4BAA4B,CAAC;AACpF,OAAO,EAAE,6CAA6C,EAAE,MAAM,oFAAoF,CAAC;AAKnJ,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAG/D,MAAM,WAAW,GAAG,8BAA8B,CAAC;AAQnD,SAAS,8BAA8B,CAAC,KAOvC;IACC,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;IAC5B,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,GAAG,CAAC,SAAS,CAAC,wBAAwB;YACpC,CAAC,CAAC,EAAE,wBAAwB,EAAE,SAAS,CAAC,wBAAwB,EAAE;YAClE,CAAC,CAAC,EAAE,CAAC;QACP,cAAc,EAAE,SAAS,CAAC,cAAc;QACxC,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;QAC9C,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;QAChD,yBAAyB,EAAE,SAAS,CAAC,yBAAyB;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AM,UAAU,GAAG,+BAA+B,KAAK,CAAC,MAAM,EAAE,CAAC;IACjE,MAAM,OAAO,GAAG,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC9C,MAAM,MAAM,GAAG,MAAM,6CAA6C,CAAC,IAAI,CACrE,OAAO,EACP,UAAU,CACX,CAAC;IACF,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,IACE,MAAM,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QAC9B,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc,EAC9C,CAAC;QACD,MAAM,IAAI,KAAK,CACb,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO,qCAAqC,CAAC;QAC3C,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,sBAAsB,EAAE,UAAU;QAClC,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAM3D;IACC,OAAO,6CAA6C,CAAC,MAAM,CACzD,KAAK,CAAC,OAAO,EACb,KAAK,EACL,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject } from \"@tearleads/validators/isPlainObject\";\nimport {\n type CreateOrganizationRequest,\n isCreateOrganizationRequest,\n} from \"@tearleads/validators/request\";\nimport { isOrganizationReplacementAuthorization } from \"@tearleads/validators/util\";\nimport { sqlOrganizationProvisioningAttemptPersistence } from \"../../../data/persistence/organizations/organizationProvisioningAttemptPersistence\";\nimport type {\n ExecSql,\n ExecSqlClientLike,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationProvisioningArtifacts } from \"../../registration/registerIdentity\";\n\nconst BYTE_MARKER = \"__tearleadsProvisioningBytes\";\n\ninterface DurableOrganizationProvisioningAttempt {\n readonly artifacts: OrganizationProvisioningArtifacts;\n readonly request: CreateOrganizationRequest;\n readonly rootContainerId: string;\n}\n\nfunction buildCreateOrganizationRequest(input: {\n artifacts: OrganizationProvisioningArtifacts;\n finalizeReplacement?: boolean | undefined;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): CreateOrganizationRequest {\n const { artifacts } = input;\n return {\n userId: input.userId,\n ...(artifacts.replacementAuthorization\n ? { replacementAuthorization: artifacts.replacementAuthorization }\n : {}),\n organizationId: artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n initialRootContainer: artifacts.initialRootContainer,\n initialRootMetadataDocument: artifacts.rootMetadataDocumentRequest,\n initialRosterProfileContainer:\n artifacts.rosterProfileBootstrap.containerRequest,\n initialRosterProfileDocument:\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n initialOrganizationMetadataContainer:\n artifacts.organizationMetadataBootstrap.containerRequest,\n initialOrganizationProfileDocument:\n artifacts.organizationMetadataBootstrap\n .organizationProfileDocumentRequest,\n initialSystemContainers: artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n ...(input.finalizeReplacement ? { finalizeReplacement: true } : {}),\n ...(input.nativeSubscriptionRestore\n ? { nativeSubscriptionRestore: true as const }\n : {}),\n ...(input.replacesOrganizationId\n ? { replacesOrganizationId: input.replacesOrganizationId }\n : {}),\n };\n}\n\nexport async function loadOrganizationReplacementFinalizationRequest(input: {\n execSql: ExecSql;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<CreateOrganizationRequest> {\n const stored = await sqlOrganizationProvisioningAttemptPersistence.load(\n input.execSql,\n input.replacedOrganizationId,\n );\n if (!stored) {\n throw new Error(\"Organization replacement attempt is unavailable\");\n }\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n finalizeReplacement: true,\n replacesOrganizationId: input.replacedOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return request;\n}\n\nfunction serializeArtifacts(artifacts: OrganizationProvisioningArtifacts) {\n return JSON.stringify(artifacts, (_key, value: unknown) => {\n if (value instanceof Uint8Array) {\n return { [BYTE_MARKER]: bytesToBase64(value) };\n }\n return value;\n });\n}\n\nfunction hasRecord(value: Record<string, unknown>, key: string): boolean {\n return isPlainObject(Reflect.get(value, key));\n}\n\nfunction hasBytes(value: Record<string, unknown>, key: string): boolean {\n return Reflect.get(value, key) instanceof Uint8Array;\n}\n\nfunction isMaterializedDocument(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"contentKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction isMaterializedContainer(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"containerKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction hasContainerBootstrapCore(value: Record<string, unknown>): boolean {\n return (\n typeof Reflect.get(value, \"containerId\") === \"string\" &&\n isMaterializedDocument(Reflect.get(value, \"containerMetadataDocument\")) &&\n hasBytes(value, \"containerMetadataInitialUpdate\") &&\n isMaterializedContainer(Reflect.get(value, \"containerPlan\")) &&\n hasRecord(value, \"containerRequest\") &&\n Reflect.get(value, \"systemSlot\") !== undefined\n );\n}\n\nfunction isOrganizationProvisioningArtifacts(\n value: unknown,\n): value is OrganizationProvisioningArtifacts {\n if (!isPlainObject(value)) return false;\n const bootstrap = Reflect.get(value, \"bootstrap\");\n const roster = Reflect.get(value, \"rosterProfileBootstrap\");\n const metadata = Reflect.get(value, \"organizationMetadataBootstrap\");\n const systemContainers = Reflect.get(value, \"systemContainerBootstraps\");\n return (\n (Reflect.get(value, \"replacementAuthorization\") === null ||\n isOrganizationReplacementAuthorization(\n Reflect.get(value, \"replacementAuthorization\"),\n )) &&\n typeof Reflect.get(value, \"organizationId\") === \"string\" &&\n isPlainObject(bootstrap) &&\n hasBytes(bootstrap, \"initialUpdate\") &&\n typeof Reflect.get(bootstrap, \"metadataDocumentId\") === \"string\" &&\n hasRecord(value, \"initialAdminGroup\") &&\n hasRecord(value, \"initialMemberGroup\") &&\n hasRecord(value, \"initialOrganizationPolicy\") &&\n hasRecord(value, \"initialRootContainer\") &&\n isMaterializedContainer(Reflect.get(value, \"rootContainer\")) &&\n isMaterializedDocument(Reflect.get(value, \"rootMetadataDocument\")) &&\n hasRecord(value, \"rootMetadataDocumentRequest\") &&\n isPlainObject(roster) &&\n hasContainerBootstrapCore(roster) &&\n isMaterializedDocument(Reflect.get(roster, \"profileDocument\")) &&\n hasBytes(roster, \"profileDocumentInitialUpdate\") &&\n hasRecord(roster, \"profileDocumentRequest\") &&\n isPlainObject(metadata) &&\n hasContainerBootstrapCore(metadata) &&\n isMaterializedDocument(\n Reflect.get(metadata, \"organizationProfileDocument\"),\n ) &&\n hasRecord(metadata, \"organizationProfileDocumentRequest\") &&\n typeof Reflect.get(metadata, \"organizationProfileSnapshot\") === \"string\" &&\n Array.isArray(systemContainers) &&\n systemContainers.every(\n (container) =>\n isPlainObject(container) && hasContainerBootstrapCore(container),\n )\n );\n}\n\nfunction deserializeArtifacts(\n value: string,\n): OrganizationProvisioningArtifacts {\n const parsed: unknown = JSON.parse(value, (_key, candidate: unknown) => {\n if (\n typeof candidate === \"object\" &&\n candidate !== null &&\n Object.keys(candidate).length === 1 &&\n BYTE_MARKER in candidate\n ) {\n const encoded = Reflect.get(candidate, BYTE_MARKER);\n if (typeof encoded === \"string\") {\n return base64ToBytes(encoded);\n }\n }\n return candidate;\n });\n if (!isOrganizationProvisioningArtifacts(parsed)) {\n throw new Error(\"Stored organization provisioning attempt is invalid\");\n }\n return parsed;\n}\n\nexport async function makeOrganizationProvisioningAttemptDurable(input: {\n artifacts: OrganizationProvisioningArtifacts;\n canStartDurableMutation?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): Promise<DurableOrganizationProvisioningAttempt | null> {\n const attemptKey =\n input.replacesOrganizationId ??\n (input.nativeSubscriptionRestore\n ? `native-subscription-restore:${input.userId}`\n : null);\n if (!attemptKey) {\n return {\n artifacts: input.artifacts,\n request: buildCreateOrganizationRequest(input),\n rootContainerId: input.rootContainerId,\n };\n }\n const stored = await sqlOrganizationProvisioningAttemptPersistence.loadOrSave(\n createExecSql(input.dbClient),\n {\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n organizationId: input.artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n serializedArtifacts: serializeArtifacts(input.artifacts),\n },\n input.canStartDurableMutation,\n );\n if (!stored) return null;\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return { artifacts, request, rootContainerId: stored.rootContainerId };\n}\n\nexport async function removeNativeSubscriptionRestoreProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n organizationId: string;\n userId: string;\n}): Promise<boolean> {\n const attemptKey = `native-subscription-restore:${input.userId}`;\n const execSql = createExecSql(input.dbClient);\n const stored = await sqlOrganizationProvisioningAttemptPersistence.load(\n execSql,\n attemptKey,\n );\n if (!stored) return true;\n if (\n stored.userId !== input.userId ||\n stored.organizationId !== input.organizationId\n ) {\n throw new Error(\n \"Stored native restore organization provisioning attempt is inconsistent\",\n );\n }\n return removeOrganizationProvisioningAttempt({\n canCommit: input.canCommit,\n execSql,\n organizationId: input.organizationId,\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n });\n}\n\nexport async function removeOrganizationProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n execSql: ExecSql;\n organizationId?: string | undefined;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<boolean> {\n return sqlOrganizationProvisioningAttemptPersistence.remove(\n input.execSql,\n input,\n input.canCommit,\n );\n}\n"]}
1
+ {"version":3,"file":"organizationProvisioningAttempt.js","sourceRoot":"","sources":["organizationProvisioningAttempt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAEL,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sCAAsC,EAAE,MAAM,4BAA4B,CAAC;AACpF,OAAO,EAAE,6CAA6C,EAAE,MAAM,oFAAoF,CAAC;AAKnJ,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAG/D,MAAM,WAAW,GAAG,8BAA8B,CAAC;AAQnD,SAAS,8BAA8B,CAAC,KAOvC;IACC,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;IAC5B,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,GAAG,CAAC,SAAS,CAAC,wB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eAAe,KAAK,MAAM,CAAC,eAAe;QAClD,CAAC,2BAA2B,CAAC,OAAO,CAAC,EACrC,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,CAAC,eAAe,EAAE,CAAC;AACzE,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kDAAkD,CAAC,KAKxE;IACC,MAAM,UAAU,GAAG,+BAA+B,KAAK,CAAC,MAAM,EAAE,CAAC;IACjE,MAAM,OAAO,GAAG,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC9C,MAAM,MAAM,GAAG,MAAM,6CAA6C,CAAC,IAAI,CACrE,OAAO,EACP,UAAU,CACX,CAAC;IACF,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,IACE,MAAM,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QAC9B,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc,EAC9C,CAAC;QACD,MAAM,IAAI,KAAK,CACb,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO,qCAAqC,CAAC;QAC3C,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,sBAAsB,EAAE,UAAU;QAClC,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAM3D;IACC,OAAO,6CAA6C,CAAC,MAAM,CACzD,KAAK,CAAC,OAAO,EACb,KAAK,EACL,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject } from \"@tearleads/validators/isPlainObject\";\nimport {\n type CreateOrganizationRequest,\n isCreateOrganizationRequest,\n} from \"@tearleads/validators/request\";\nimport { isOrganizationReplacementAuthorization } from \"@tearleads/validators/util\";\nimport { sqlOrganizationProvisioningAttemptPersistence } from \"../../../data/persistence/organizations/organizationProvisioningAttemptPersistence\";\nimport type {\n ExecSql,\n ExecSqlClientLike,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationProvisioningArtifacts } from \"../../registration/organizationProvisioning\";\n\nconst BYTE_MARKER = \"__tearleadsProvisioningBytes\";\n\ninterface DurableOrganizationProvisioningAttempt {\n readonly artifacts: OrganizationProvisioningArtifacts;\n readonly request: CreateOrganizationRequest;\n readonly rootContainerId: string;\n}\n\nfunction buildCreateOrganizationRequest(input: {\n artifacts: OrganizationProvisioningArtifacts;\n finalizeReplacement?: boolean | undefined;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): CreateOrganizationRequest {\n const { artifacts } = input;\n return {\n userId: input.userId,\n ...(artifacts.replacementAuthorization\n ? { replacementAuthorization: artifacts.replacementAuthorization }\n : {}),\n organizationId: artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n initialRootContainer: artifacts.initialRootContainer,\n initialRootMetadataDocument: artifacts.rootMetadataDocumentRequest,\n initialRosterProfileContainer:\n artifacts.rosterProfileBootstrap.containerRequest,\n initialRosterProfileDocument:\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n initialOrganizationMetadataContainer:\n artifacts.organizationMetadataBootstrap.containerRequest,\n initialOrganizationProfileDocument:\n artifacts.organizationMetadataBootstrap\n .organizationProfileDocumentRequest,\n initialSystemContainers: artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n ...(input.finalizeReplacement ? { finalizeReplacement: true } : {}),\n ...(input.nativeSubscriptionRestore\n ? { nativeSubscriptionRestore: true as const }\n : {}),\n ...(input.replacesOrganizationId\n ? { replacesOrganizationId: input.replacesOrganizationId }\n : {}),\n };\n}\n\nexport async function loadOrganizationReplacementFinalizationRequest(input: {\n execSql: ExecSql;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<CreateOrganizationRequest> {\n const stored = await sqlOrganizationProvisioningAttemptPersistence.load(\n input.execSql,\n input.replacedOrganizationId,\n );\n if (!stored) {\n throw new Error(\"Organization replacement attempt is unavailable\");\n }\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n finalizeReplacement: true,\n replacesOrganizationId: input.replacedOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return request;\n}\n\nfunction serializeArtifacts(artifacts: OrganizationProvisioningArtifacts) {\n return JSON.stringify(artifacts, (_key, value: unknown) => {\n if (value instanceof Uint8Array) {\n return { [BYTE_MARKER]: bytesToBase64(value) };\n }\n return value;\n });\n}\n\nfunction hasRecord(value: Record<string, unknown>, key: string): boolean {\n return isPlainObject(Reflect.get(value, key));\n}\n\nfunction hasBytes(value: Record<string, unknown>, key: string): boolean {\n return Reflect.get(value, key) instanceof Uint8Array;\n}\n\nfunction isMaterializedDocument(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"contentKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction isMaterializedContainer(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"containerKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction hasContainerBootstrapCore(value: Record<string, unknown>): boolean {\n return (\n typeof Reflect.get(value, \"containerId\") === \"string\" &&\n isMaterializedDocument(Reflect.get(value, \"containerMetadataDocument\")) &&\n hasBytes(value, \"containerMetadataInitialUpdate\") &&\n isMaterializedContainer(Reflect.get(value, \"containerPlan\")) &&\n hasRecord(value, \"containerRequest\") &&\n Reflect.get(value, \"systemSlot\") !== undefined\n );\n}\n\nfunction isOrganizationProvisioningArtifacts(\n value: unknown,\n): value is OrganizationProvisioningArtifacts {\n if (!isPlainObject(value)) return false;\n const bootstrap = Reflect.get(value, \"bootstrap\");\n const roster = Reflect.get(value, \"rosterProfileBootstrap\");\n const metadata = Reflect.get(value, \"organizationMetadataBootstrap\");\n const systemContainers = Reflect.get(value, \"systemContainerBootstraps\");\n return (\n (Reflect.get(value, \"replacementAuthorization\") === null ||\n isOrganizationReplacementAuthorization(\n Reflect.get(value, \"replacementAuthorization\"),\n )) &&\n typeof Reflect.get(value, \"organizationId\") === \"string\" &&\n isPlainObject(bootstrap) &&\n hasBytes(bootstrap, \"initialUpdate\") &&\n typeof Reflect.get(bootstrap, \"metadataDocumentId\") === \"string\" &&\n hasRecord(value, \"initialAdminGroup\") &&\n hasRecord(value, \"initialMemberGroup\") &&\n hasRecord(value, \"initialOrganizationPolicy\") &&\n hasRecord(value, \"initialRootContainer\") &&\n isMaterializedContainer(Reflect.get(value, \"rootContainer\")) &&\n isMaterializedDocument(Reflect.get(value, \"rootMetadataDocument\")) &&\n hasRecord(value, \"rootMetadataDocumentRequest\") &&\n isPlainObject(roster) &&\n hasContainerBootstrapCore(roster) &&\n isMaterializedDocument(Reflect.get(roster, \"profileDocument\")) &&\n hasBytes(roster, \"profileDocumentInitialUpdate\") &&\n hasRecord(roster, \"profileDocumentRequest\") &&\n isPlainObject(metadata) &&\n hasContainerBootstrapCore(metadata) &&\n isMaterializedDocument(\n Reflect.get(metadata, \"organizationProfileDocument\"),\n ) &&\n hasRecord(metadata, \"organizationProfileDocumentRequest\") &&\n typeof Reflect.get(metadata, \"organizationProfileSnapshot\") === \"string\" &&\n Array.isArray(systemContainers) &&\n systemContainers.every(\n (container) =>\n isPlainObject(container) && hasContainerBootstrapCore(container),\n )\n );\n}\n\nfunction deserializeArtifacts(\n value: string,\n): OrganizationProvisioningArtifacts {\n const parsed: unknown = JSON.parse(value, (_key, candidate: unknown) => {\n if (\n typeof candidate === \"object\" &&\n candidate !== null &&\n Object.keys(candidate).length === 1 &&\n BYTE_MARKER in candidate\n ) {\n const encoded = Reflect.get(candidate, BYTE_MARKER);\n if (typeof encoded === \"string\") {\n return base64ToBytes(encoded);\n }\n }\n return candidate;\n });\n if (!isOrganizationProvisioningArtifacts(parsed)) {\n throw new Error(\"Stored organization provisioning attempt is invalid\");\n }\n return parsed;\n}\n\nexport async function makeOrganizationProvisioningAttemptDurable(input: {\n artifacts: OrganizationProvisioningArtifacts;\n canStartDurableMutation?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): Promise<DurableOrganizationProvisioningAttempt | null> {\n const attemptKey =\n input.replacesOrganizationId ??\n (input.nativeSubscriptionRestore\n ? `native-subscription-restore:${input.userId}`\n : null);\n if (!attemptKey) {\n return {\n artifacts: input.artifacts,\n request: buildCreateOrganizationRequest(input),\n rootContainerId: input.rootContainerId,\n };\n }\n const stored = await sqlOrganizationProvisioningAttemptPersistence.loadOrSave(\n createExecSql(input.dbClient),\n {\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n organizationId: input.artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n serializedArtifacts: serializeArtifacts(input.artifacts),\n },\n input.canStartDurableMutation,\n );\n if (!stored) return null;\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return { artifacts, request, rootContainerId: stored.rootContainerId };\n}\n\nexport async function removeNativeSubscriptionRestoreProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n organizationId: string;\n userId: string;\n}): Promise<boolean> {\n const attemptKey = `native-subscription-restore:${input.userId}`;\n const execSql = createExecSql(input.dbClient);\n const stored = await sqlOrganizationProvisioningAttemptPersistence.load(\n execSql,\n attemptKey,\n );\n if (!stored) return true;\n if (\n stored.userId !== input.userId ||\n stored.organizationId !== input.organizationId\n ) {\n throw new Error(\n \"Stored native restore organization provisioning attempt is inconsistent\",\n );\n }\n return removeOrganizationProvisioningAttempt({\n canCommit: input.canCommit,\n execSql,\n organizationId: input.organizationId,\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n });\n}\n\nexport async function removeOrganizationProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n execSql: ExecSql;\n organizationId?: string | undefined;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<boolean> {\n return sqlOrganizationProvisioningAttemptPersistence.remove(\n input.execSql,\n input,\n input.canCommit,\n );\n}\n"]}
@@ -3,7 +3,7 @@ import { sqlContainerContentsPersistence } from "../../../data/persistence/conta
3
3
  import { DOCUMENTS_APP_KIND, sqlDocumentsPersistence, } from "../../../data/persistence/documents/documentsPersistence.js";
4
4
  import { loadOrganizationProfileDocumentIds } from "../../../data/persistence/organizations/organizationProfileDocumentPointers.js";
5
5
  import { findLocalIdByDocumentId } from "../../../data/sqlite/documentPersistence/index.js";
6
- import { loadPersistedDocumentContent } from "../../documents/historyContent.js";
6
+ import { loadPersistedDocumentContent } from "../../documents/index.js";
7
7
  import { getOrganizationProfileDocumentLocalId, readOrganizationProfileName, } from "../organizationProfile.js";
8
8
  import { deriveOrganizationMetadataContainerSystemSlot } from "../rosterProfileContainer.js";
9
9
  // Reads and decrypts the `name` field of the organization_profile document