@tearleads/client-sdk 0.1.79 → 0.1.80

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 (143) 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 +4 -0
  30. package/data/keyingProjectionVerification/index.js +5 -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/principalPolicyVerification.d.ts +24 -0
  34. package/data/persistence/container-contents/documentPlacement.js +1 -1
  35. package/data/persistence/container-contents/documentPlacement.js.map +1 -1
  36. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
  37. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js.map +1 -1
  38. package/data/persistence/documents/documentsPersistence.d.ts +1 -1
  39. package/data/persistence/documents/documentsPersistence.js +2 -3
  40. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  41. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  42. package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
  43. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +1 -1
  44. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  45. package/data/persistence/documents/internal/documentDeletionPersistence.js +1 -1
  46. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  47. package/data/persistence/documents/internal/documentMutationPersistence.js +1 -1
  48. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  49. package/data/persistence/documents/internal/documentProjectionRows.js +1 -2
  50. package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
  51. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  52. package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
  53. package/data/persistence/documents/internal/documentRows.js +1 -2
  54. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  55. package/data/persistence/documents/internal/orphanSideRows.js +1 -1
  56. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  57. package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
  58. package/data/persistence/documents/internal/pendingCreateAdoption.js.map +1 -1
  59. package/data/persistence/documents/internal/rowQueryPersistence.js +1 -1
  60. package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
  61. package/package.json +1 -1
  62. package/stores/local-projection/localProjectionStore.d.ts +1 -1
  63. package/stores/local-projection/localProjectionStore.js +1 -1
  64. package/stores/local-projection/localProjectionStore.js.map +1 -1
  65. package/stores/local-projection/registry.d.ts +1 -1
  66. package/stores/local-projection/registry.js.map +1 -1
  67. package/stores/local-projection/types.d.ts +1 -1
  68. package/stores/local-projection/types.js.map +1 -1
  69. package/workflows/blobs/hydration/decrypt.js +1 -2
  70. package/workflows/blobs/hydration/decrypt.js.map +1 -1
  71. package/workflows/blobs/hydration/hydrate.d.ts +1 -1
  72. package/workflows/blobs/hydration/hydrate.js.map +1 -1
  73. package/workflows/container-contents/container-state/create/createAdoption.js +1 -2
  74. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  75. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -1
  76. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  77. package/workflows/container-contents/info/documentInfo.js +1 -1
  78. package/workflows/container-contents/info/documentInfo.js.map +1 -1
  79. package/workflows/container-contents/metadata/index.js +1 -2
  80. package/workflows/container-contents/metadata/index.js.map +1 -1
  81. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  82. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  83. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
  84. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
  85. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  86. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  87. package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
  88. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  89. package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
  90. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  91. package/workflows/container-contents/pendingWrites/index.js +1 -1
  92. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  93. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -3
  94. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  95. package/workflows/containers/child/create/index.js +1 -1
  96. package/workflows/containers/child/create/index.js.map +1 -1
  97. package/workflows/containers/child/move/moveRotation.js +1 -1
  98. package/workflows/containers/child/move/moveRotation.js.map +1 -1
  99. package/workflows/containers/child/move/moveWraps.js +1 -1
  100. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  101. package/workflows/containers/child/rekey/rekeyProjection.js +1 -1
  102. package/workflows/containers/child/rekey/rekeyProjection.js.map +1 -1
  103. package/workflows/containers/child/rotation/rotationContext.js +1 -2
  104. package/workflows/containers/child/rotation/rotationContext.js.map +1 -1
  105. package/workflows/containers/child/share/shareAncestorRepair.js +1 -2
  106. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -1
  107. package/workflows/containers/index.d.ts +2 -3
  108. package/workflows/containers/index.js +1 -2
  109. package/workflows/containers/index.js.map +1 -1
  110. package/workflows/containers/writeRefusal.js +1 -1
  111. package/workflows/containers/writeRefusal.js.map +1 -1
  112. package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
  113. package/workflows/documents/linkSet/linkSetProjectionSeed.js.map +1 -1
  114. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +1 -1
  115. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  116. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  117. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  118. package/workflows/organizations/provisioning/createOrganization.d.ts +1 -1
  119. package/workflows/organizations/provisioning/createOrganization.js +1 -1
  120. package/workflows/organizations/provisioning/createOrganization.js.map +1 -1
  121. package/workflows/organizations/provisioning/organizationProvisioningAttempt.d.ts +1 -1
  122. package/workflows/organizations/provisioning/organizationProvisioningAttempt.js.map +1 -1
  123. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  124. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
  125. package/workflows/registration/index.d.ts +2 -1
  126. package/workflows/registration/index.js +2 -1
  127. package/workflows/registration/index.js.map +1 -1
  128. package/workflows/registration/organizationProvisioning.d.ts +39 -0
  129. package/workflows/registration/organizationProvisioning.js +211 -0
  130. package/workflows/registration/organizationProvisioning.js.map +1 -0
  131. package/workflows/registration/organizationProvisioningArtifacts.d.ts +2 -3
  132. package/workflows/registration/organizationProvisioningArtifacts.js.map +1 -1
  133. package/workflows/registration/provisioningBootstrapBuilders.d.ts +3 -3
  134. package/workflows/registration/provisioningBootstrapBuilders.js +3 -4
  135. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  136. package/workflows/registration/registerIdentity.d.ts +2 -39
  137. package/workflows/registration/registerIdentity.js +2 -207
  138. package/workflows/registration/registerIdentity.js.map +1 -1
  139. package/workflows/sync/remoteResetPlans.js +2 -2
  140. package/workflows/sync/remoteResetPlans.js.map +1 -1
  141. package/data/persistence/documents/internal/constants.d.ts +0 -1
  142. package/data/persistence/documents/internal/constants.js +0 -2
  143. package/data/persistence/documents/internal/constants.js.map +0 -1
@@ -1,10 +1,9 @@
1
1
  import { base64ToBytes } from "../../internal/encoding/index.js";
2
2
  import { deriveStableDocumentId } from "../../data/documents/shared/stableDocumentId.js";
3
+ import { deriveContainerSystemSlot, } from "../container-contents/index.js";
3
4
  import { createInitializedContainerMetadataDocument } from "../container-contents/metadata/containerMetadataDocument.js";
4
- import { deriveContainerSystemSlot, } from "../container-contents/systemSlot.js";
5
- import { buildContainerCreatePlan, childContainerWriterProjectionFromCreatePlan, } from "../containers/child/create/index.js";
6
- import { buildRootContainerCreatePlan, rootContainerWriterProjectionFromCreatePlan, } from "../containers/root/create.js";
7
- import { buildMaterializedDocumentCreatePlan } from "../documents/create/index.js";
5
+ import { buildContainerCreatePlan, buildRootContainerCreatePlan, childContainerWriterProjectionFromCreatePlan, rootContainerWriterProjectionFromCreatePlan, } from "../containers/index.js";
6
+ import { buildMaterializedDocumentCreatePlan } from "../documents/index.js";
8
7
  import { buildInitialDocumentSyncRequest } from "../documents/sync/initialSync.js";
9
8
  import { getOrganizationProfileDocumentLocalId } from "../organizations/organizationProfile.js";
10
9
  import { deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationRosterProfileContainerSystemSlot, getRosterProfileDocumentLocalId, ORGANIZATION_METADATA_CONTAINER_NAME, ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME, } from "../organizations/rosterProfileContainer.js";
@@ -1 +1 @@
1
- {"version":3,"file":"provisioningBootstrapBuilders.js","sourceRoot":"","sources":["provisioningBootstrapBuilders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAAE,0CAA0C,EAAE,MAAM,0DAA0D,CAAC;AACtH,OAAO,EAEL,yBAAyB,GAC1B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,wBAAwB,EACxB,4CAA4C,GAC7C,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,4BAA4B,EAC5B,2CAA2C,GAC5C,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,mCAAmC,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAAE,qCAAqC,EAAE,MAAM,sCAAsC,CAAC;AAC7F,OAAO,EACL,6CAA6C,EAC7C,kDAAkD,EAClD,+BAA+B,EAC/B,oCAAoC,EACpC,0CAA0C,GAC3C,MAAM,yCAAyC,CAAC;AAQjD,OAAO,EACL,mCAAmC,EACnC,6BAA6B,GAC9B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,8CAA8C,EAAE,MAAM,0CAA0C,CAAC;AAqE1G;;;;;;GAMG;AACH,KAAK,UAAU,kCAAkC,CAAC,KAmBjD;IACC,MAA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E,KAAK,CAAC,UAAU;QAC5B,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW,EAAE,KAAK,CAAC,eAAe;QAClC,kBAAkB,EAAE,KAAK,CAAC,SAAS,CAAC,kBAAkB;QACtD,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,MAAM,uBAAuB,GAAG,2CAA2C,CACzE,aAAa,CAAC,IAAI,CACnB,CAAC;IACF,MAAM,oBAAoB,GAAG,MAAM,mCAAmC,CAAC;QACrE,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,mBAAmB,EAAE,uBAAuB;QAC5C,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,kBAAkB;QAC9C,kBAAkB,EAAE,IAAI,GAAG,CAAC;YAC1B,CAAC,aAAa,CAAC,IAAI,CAAC,mBAAmB,EAAE,aAAa,CAAC,YAAY,CAAC;SACrE,CAAC;QACF,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,sBAAsB,EAAE,IAAI;KAC7B,CAAC,CAAC;IACH,OAAO;QACL,aAAa;QACb,uBAAuB;QACvB,oBAAoB;QACpB,2BAA2B,EAAE;YAC3B,GAAG,oBAAoB,CAAC,IAAI,CAAC,OAAO;YACpC,WAAW,EAAE,MAAM,+BAA+B,CAAC;gBACjD,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,mBAAmB,EAAE,uBAAuB;gBAC5C,aAAa,EAAE,KAAK,CAAC,SAAS,CAAC,aAAa;gBAC5C,oBAAoB,EAAE,oBAAoB;aAC3C,CAAC;SACH;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { CreateOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\nimport { createInitializedContainerMetadataDocument } from \"../container-contents/metadata/containerMetadataDocument\";\nimport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"../container-contents/systemSlot\";\nimport {\n buildContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n} from \"../containers/child/create\";\nimport {\n buildRootContainerCreatePlan,\n rootContainerWriterProjectionFromCreatePlan,\n} from \"../containers/root/create\";\nimport type { resolveDocumentCreateAuthor } from \"../documents/author\";\nimport { buildMaterializedDocumentCreatePlan } from \"../documents/create\";\nimport { buildInitialDocumentSyncRequest } from \"../documents/sync/initialSync\";\nimport { getOrganizationProfileDocumentLocalId } from \"../organizations/organizationProfile\";\nimport {\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n} from \"../organizations/rosterProfileContainer\";\nimport type {\n InitialOrganizationMetadataBootstrap,\n InitialRootContainerCreatePlan,\n InitialRosterProfileBootstrap,\n InitialSystemContainerBootstrap,\n InitialSystemContainerCreatePlan,\n} from \"./organizationProvisioningArtifacts\";\nimport {\n buildProvisionedOrganizationProfile,\n buildProvisionedRosterProfile,\n} from \"./provisionedProfileDocument\";\nimport { verifiedPrincipalPolicyFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nimport type { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\ntype InitialRootContainerProjection = ReturnType<\n typeof rootContainerWriterProjectionFromCreatePlan\n>;\n\n/**\n * An app-owned system container to provision atomically with a new organization\n * (e.g. a trash bin). The client-sdk is agnostic to what these are:\n * the caller (the app, which owns the mini-app slot namespaces) declares each\n * one, and the provisioning path derives its per-user system slot, builds a\n * signed Admins-scoped child of root, and links it into the same transaction as\n * the rest of the organization bootstrap. The behavioral rules that govern a\n * system container are resolved client-side by slot, so provisioning needs only\n * the slot definition, display name, and icon — no rules travel to the server.\n */\nexport interface ProvisionedSystemContainerSpec {\n readonly slotDefinition: ContainerSystemSlotDefinition;\n readonly name: string;\n readonly icon: string | null;\n}\n\ninterface InitialOrganizationMetadataBootstrapInput {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId: string;\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n organizationProfileName?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}\n\ninterface InitialRosterProfileInput {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n encapsulationPublicKey: Uint8Array;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n rosterProfileNickname?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\ninterface ProvisionedChildContainerCore {\n containerId: string;\n containerMetadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >;\n containerMetadataInitialUpdate: Uint8Array;\n containerPlan: InitialSystemContainerCreatePlan;\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n containerRequest: {\n systemSlot: ContainerSystemSlot;\n container: InitialSystemContainerCreatePlan[\"plan\"][\"request\"];\n initialMetadataSync: Awaited<\n ReturnType<typeof buildInitialDocumentSyncRequest>\n >;\n metadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >[\"plan\"][\"request\"];\n };\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n systemSlot: ContainerSystemSlot;\n}\n\n/**\n * The shared spine of every provisioned system child container: mint the\n * container and its metadata document under root, project the writer view,\n * and assemble the create request. Callers differ only in slot derivation,\n * display metadata, authorizing policies, an optional managed read grant, and\n * what they attach afterwards (roster/org profile documents).\n */\nasync function buildProvisionedChildContainerCore(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId?: string | undefined;\n icon: string | null;\n managedPrincipalGrant?: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"managedPrincipalGrant\"];\n name: string;\n principalPolicies: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"principalPolicies\"];\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n systemSlot: ContainerSystemSlot;\n targetSecretKey: Uint8Array;\n independentMetadataGroups?: {\n adminGroup: CreateOrganizationGroupRequest;\n memberGroup: CreateOrganizationGroupRequest;\n };\n}): Promise<ProvisionedChildContainerCore> {\n const containerId = input.containerId ?? crypto.randomUUID();\n const { initialUpdate } = await createInitializedContainerMetadataDocument(\n containerId,\n {\n icon: input.icon,\n name: input.name,\n },\n );\n const containerKey = crypto.getRandomValues(new Uint8Array(32));\n const containerPlan: InitialSystemContainerCreatePlan = {\n containerKey,\n plan: input.independentMetadataGroups\n ? (\n await buildRootContainerCreatePlan({\n ...input.independentMetadataGroups,\n author: input.author,\n containerId,\n containerKey,\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n recipientEncapsulationPublicKey: base64ToBytes(\n input.independentMetadataGroups.adminGroup.initialGroupPolicy\n .state.encapsulationPublicKey,\n ),\n })\n ).plan\n : await buildContainerCreatePlan({\n author: input.author,\n containerId,\n containerKey,\n ...(input.managedPrincipalGrant\n ? { managedPrincipalGrant: input.managedPrincipalGrant }\n : {}),\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n parentProjection: input.rootContainerProjection,\n principalPolicies: input.principalPolicies,\n }),\n };\n const containerProjection = input.independentMetadataGroups\n ? rootContainerWriterProjectionFromCreatePlan(containerPlan.plan)\n : childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.rootContainerProjection,\n });\n const knownContainerKeks = new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]);\n const containerMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection,\n documentId: containerPlan.plan.metadataDocumentId,\n knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const initialMetadataSync = await buildInitialDocumentSyncRequest({\n author: input.author,\n containerProjection,\n initialUpdate,\n materializedDocument: containerMetadataDocument,\n });\n return {\n containerId,\n containerMetadataDocument,\n containerMetadataInitialUpdate: initialUpdate,\n containerPlan,\n containerProjection,\n containerRequest: {\n systemSlot: input.systemSlot,\n container: containerPlan.plan.request,\n initialMetadataSync,\n metadataDocument: containerMetadataDocument.plan.request,\n },\n knownContainerKeks,\n systemSlot: input.systemSlot,\n };\n}\n\nexport async function buildInitialRosterProfileBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n encapsulationPublicKey: Uint8Array;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rosterProfileNickname?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}): Promise<InitialRosterProfileBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: null,\n name: ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationRosterProfileContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { profile, rosterProfileDocument } = await buildInitialRosterProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n knownContainerKeks: core.knownContainerKeks,\n rosterProfileNickname: input.rosterProfileNickname,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n profileDocument: rosterProfileDocument,\n profileDocumentInitialUpdate: profile.initialUpdate,\n profileDocumentRequest: profile.request,\n systemSlot: core.systemSlot,\n };\n}\n\nasync function buildInitialRosterProfile(input: InitialRosterProfileInput) {\n const rosterProfileDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await deriveStableDocumentId(\n getRosterProfileDocumentLocalId({\n organizationId: input.author.organizationId,\n userId: input.author.signerUserId,\n }),\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const profile = await buildProvisionedRosterProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n materializedDocument: rosterProfileDocument,\n nickname: input.rosterProfileNickname,\n });\n return { profile, rosterProfileDocument };\n}\n\nexport async function buildInitialSystemContainerBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n signingPrivateKey: Uint8Array;\n spec: ProvisionedSystemContainerSpec;\n targetSecretKey: Uint8Array;\n}): Promise<InitialSystemContainerBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: input.spec.icon,\n name: input.spec.name,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveContainerSystemSlot({\n definition: input.spec.slotDefinition,\n secretKey: input.signingPrivateKey,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n icon: input.spec.icon,\n name: input.spec.name,\n systemSlot: core.systemSlot,\n };\n}\n\nfunction stableOrganizationProfileId(organizationId: string): Promise<string> {\n return deriveStableDocumentId(\n getOrganizationProfileDocumentLocalId({ organizationId }),\n );\n}\n\nasync function buildInitialOrganizationProfile(input: {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n organizationProfileName?: string | undefined;\n targetSecretKey: Uint8Array;\n}) {\n const organizationProfileDocument = await buildMaterializedDocumentCreatePlan(\n {\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await stableOrganizationProfileId(\n input.author.organizationId,\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n },\n );\n const profile = await buildProvisionedOrganizationProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n materializedDocument: organizationProfileDocument,\n name: input.organizationProfileName,\n });\n return { organizationProfileDocument, profile };\n}\n\n/**\n * Organization labels use an independent system root with Admins/admin and\n * Members/read grants. Personal root shares and rotations cannot expose or\n * strand organization metadata; Members changes still rotate its own KEK.\n */\nexport async function buildInitialOrganizationMetadataBootstrap(\n input: InitialOrganizationMetadataBootstrapInput,\n): Promise<InitialOrganizationMetadataBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n containerId: input.containerId,\n icon: null,\n independentMetadataGroups: {\n adminGroup: input.initialAdminGroup,\n memberGroup: input.initialMemberGroup,\n },\n name: ORGANIZATION_METADATA_CONTAINER_NAME,\n // Both reserved groups receive explicit grants on the independent root.\n principalPolicies: await Promise.all([\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialAdminGroup),\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialMemberGroup),\n ]),\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { organizationProfileDocument, profile } =\n await buildInitialOrganizationProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n knownContainerKeks: core.knownContainerKeks,\n organizationProfileName: input.organizationProfileName,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n organizationProfileDocument,\n organizationProfileDocumentRequest: profile.request,\n organizationProfileSnapshot: profile.snapshot,\n systemSlot: core.systemSlot,\n };\n}\n\nexport async function buildInitialRootProvisioning(input: {\n adminGroup: CreateOrganizationGroupRequest;\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n bootstrap: Awaited<ReturnType<typeof createInitialRootMetadataBootstrap>>;\n recipientEncapsulationPublicKey: Uint8Array;\n rootContainerId: string;\n targetSecretKey: Uint8Array;\n}) {\n const rootContainer = await buildRootContainerCreatePlan({\n adminGroup: input.adminGroup,\n author: input.author,\n containerId: input.rootContainerId,\n metadataDocumentId: input.bootstrap.metadataDocumentId,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n });\n const rootContainerProjection = rootContainerWriterProjectionFromCreatePlan(\n rootContainer.plan,\n );\n const rootMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: rootContainerProjection,\n documentId: input.bootstrap.metadataDocumentId,\n knownContainerKeks: new Map([\n [rootContainer.plan.containerKeyEpochId, rootContainer.containerKey],\n ]),\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n return {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest: {\n ...rootMetadataDocument.plan.request,\n initialSync: await buildInitialDocumentSyncRequest({\n author: input.author,\n containerProjection: rootContainerProjection,\n initialUpdate: input.bootstrap.initialUpdate,\n materializedDocument: rootMetadataDocument,\n }),\n },\n };\n}\n"]}
1
+ {"version":3,"file":"provisioningBootstrap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AE,KAAK,CAAC,SAAS,CAAC,kBAAkB;QAC9C,kBAAkB,EAAE,IAAI,GAAG,CAAC;YAC1B,CAAC,aAAa,CAAC,IAAI,CAAC,mBAAmB,EAAE,aAAa,CAAC,YAAY,CAAC;SACrE,CAAC;QACF,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,sBAAsB,EAAE,IAAI;KAC7B,CAAC,CAAC;IACH,OAAO;QACL,aAAa;QACb,uBAAuB;QACvB,oBAAoB;QACpB,2BAA2B,EAAE;YAC3B,GAAG,oBAAoB,CAAC,IAAI,CAAC,OAAO;YACpC,WAAW,EAAE,MAAM,+BAA+B,CAAC;gBACjD,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,mBAAmB,EAAE,uBAAuB;gBAC5C,aAAa,EAAE,KAAK,CAAC,SAAS,CAAC,aAAa;gBAC5C,oBAAoB,EAAE,oBAAoB;aAC3C,CAAC;SACH;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { CreateOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\nimport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"../container-contents\";\nimport { createInitializedContainerMetadataDocument } from \"../container-contents/metadata/containerMetadataDocument\";\nimport {\n buildContainerCreatePlan,\n buildRootContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n rootContainerWriterProjectionFromCreatePlan,\n} from \"../containers\";\nimport type { resolveDocumentCreateAuthor } from \"../documents\";\nimport { buildMaterializedDocumentCreatePlan } from \"../documents\";\nimport { buildInitialDocumentSyncRequest } from \"../documents/sync/initialSync\";\nimport { getOrganizationProfileDocumentLocalId } from \"../organizations/organizationProfile\";\nimport {\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n} from \"../organizations/rosterProfileContainer\";\nimport type {\n InitialOrganizationMetadataBootstrap,\n InitialRootContainerCreatePlan,\n InitialRosterProfileBootstrap,\n InitialSystemContainerBootstrap,\n InitialSystemContainerCreatePlan,\n} from \"./organizationProvisioningArtifacts\";\nimport {\n buildProvisionedOrganizationProfile,\n buildProvisionedRosterProfile,\n} from \"./provisionedProfileDocument\";\nimport { verifiedPrincipalPolicyFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nimport type { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\ntype InitialRootContainerProjection = ReturnType<\n typeof rootContainerWriterProjectionFromCreatePlan\n>;\n\n/**\n * An app-owned system container to provision atomically with a new organization\n * (e.g. a trash bin). The client-sdk is agnostic to what these are:\n * the caller (the app, which owns the mini-app slot namespaces) declares each\n * one, and the provisioning path derives its per-user system slot, builds a\n * signed Admins-scoped child of root, and links it into the same transaction as\n * the rest of the organization bootstrap. The behavioral rules that govern a\n * system container are resolved client-side by slot, so provisioning needs only\n * the slot definition, display name, and icon — no rules travel to the server.\n */\nexport interface ProvisionedSystemContainerSpec {\n readonly slotDefinition: ContainerSystemSlotDefinition;\n readonly name: string;\n readonly icon: string | null;\n}\n\ninterface InitialOrganizationMetadataBootstrapInput {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId: string;\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n organizationProfileName?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}\n\ninterface InitialRosterProfileInput {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n encapsulationPublicKey: Uint8Array;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n rosterProfileNickname?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\ninterface ProvisionedChildContainerCore {\n containerId: string;\n containerMetadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >;\n containerMetadataInitialUpdate: Uint8Array;\n containerPlan: InitialSystemContainerCreatePlan;\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n containerRequest: {\n systemSlot: ContainerSystemSlot;\n container: InitialSystemContainerCreatePlan[\"plan\"][\"request\"];\n initialMetadataSync: Awaited<\n ReturnType<typeof buildInitialDocumentSyncRequest>\n >;\n metadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >[\"plan\"][\"request\"];\n };\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n systemSlot: ContainerSystemSlot;\n}\n\n/**\n * The shared spine of every provisioned system child container: mint the\n * container and its metadata document under root, project the writer view,\n * and assemble the create request. Callers differ only in slot derivation,\n * display metadata, authorizing policies, an optional managed read grant, and\n * what they attach afterwards (roster/org profile documents).\n */\nasync function buildProvisionedChildContainerCore(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId?: string | undefined;\n icon: string | null;\n managedPrincipalGrant?: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"managedPrincipalGrant\"];\n name: string;\n principalPolicies: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"principalPolicies\"];\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n systemSlot: ContainerSystemSlot;\n targetSecretKey: Uint8Array;\n independentMetadataGroups?: {\n adminGroup: CreateOrganizationGroupRequest;\n memberGroup: CreateOrganizationGroupRequest;\n };\n}): Promise<ProvisionedChildContainerCore> {\n const containerId = input.containerId ?? crypto.randomUUID();\n const { initialUpdate } = await createInitializedContainerMetadataDocument(\n containerId,\n {\n icon: input.icon,\n name: input.name,\n },\n );\n const containerKey = crypto.getRandomValues(new Uint8Array(32));\n const containerPlan: InitialSystemContainerCreatePlan = {\n containerKey,\n plan: input.independentMetadataGroups\n ? (\n await buildRootContainerCreatePlan({\n ...input.independentMetadataGroups,\n author: input.author,\n containerId,\n containerKey,\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n recipientEncapsulationPublicKey: base64ToBytes(\n input.independentMetadataGroups.adminGroup.initialGroupPolicy\n .state.encapsulationPublicKey,\n ),\n })\n ).plan\n : await buildContainerCreatePlan({\n author: input.author,\n containerId,\n containerKey,\n ...(input.managedPrincipalGrant\n ? { managedPrincipalGrant: input.managedPrincipalGrant }\n : {}),\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n parentProjection: input.rootContainerProjection,\n principalPolicies: input.principalPolicies,\n }),\n };\n const containerProjection = input.independentMetadataGroups\n ? rootContainerWriterProjectionFromCreatePlan(containerPlan.plan)\n : childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.rootContainerProjection,\n });\n const knownContainerKeks = new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]);\n const containerMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection,\n documentId: containerPlan.plan.metadataDocumentId,\n knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const initialMetadataSync = await buildInitialDocumentSyncRequest({\n author: input.author,\n containerProjection,\n initialUpdate,\n materializedDocument: containerMetadataDocument,\n });\n return {\n containerId,\n containerMetadataDocument,\n containerMetadataInitialUpdate: initialUpdate,\n containerPlan,\n containerProjection,\n containerRequest: {\n systemSlot: input.systemSlot,\n container: containerPlan.plan.request,\n initialMetadataSync,\n metadataDocument: containerMetadataDocument.plan.request,\n },\n knownContainerKeks,\n systemSlot: input.systemSlot,\n };\n}\n\nexport async function buildInitialRosterProfileBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n encapsulationPublicKey: Uint8Array;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rosterProfileNickname?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}): Promise<InitialRosterProfileBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: null,\n name: ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationRosterProfileContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { profile, rosterProfileDocument } = await buildInitialRosterProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n knownContainerKeks: core.knownContainerKeks,\n rosterProfileNickname: input.rosterProfileNickname,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n profileDocument: rosterProfileDocument,\n profileDocumentInitialUpdate: profile.initialUpdate,\n profileDocumentRequest: profile.request,\n systemSlot: core.systemSlot,\n };\n}\n\nasync function buildInitialRosterProfile(input: InitialRosterProfileInput) {\n const rosterProfileDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await deriveStableDocumentId(\n getRosterProfileDocumentLocalId({\n organizationId: input.author.organizationId,\n userId: input.author.signerUserId,\n }),\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const profile = await buildProvisionedRosterProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n materializedDocument: rosterProfileDocument,\n nickname: input.rosterProfileNickname,\n });\n return { profile, rosterProfileDocument };\n}\n\nexport async function buildInitialSystemContainerBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n signingPrivateKey: Uint8Array;\n spec: ProvisionedSystemContainerSpec;\n targetSecretKey: Uint8Array;\n}): Promise<InitialSystemContainerBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: input.spec.icon,\n name: input.spec.name,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveContainerSystemSlot({\n definition: input.spec.slotDefinition,\n secretKey: input.signingPrivateKey,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n icon: input.spec.icon,\n name: input.spec.name,\n systemSlot: core.systemSlot,\n };\n}\n\nfunction stableOrganizationProfileId(organizationId: string): Promise<string> {\n return deriveStableDocumentId(\n getOrganizationProfileDocumentLocalId({ organizationId }),\n );\n}\n\nasync function buildInitialOrganizationProfile(input: {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n organizationProfileName?: string | undefined;\n targetSecretKey: Uint8Array;\n}) {\n const organizationProfileDocument = await buildMaterializedDocumentCreatePlan(\n {\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await stableOrganizationProfileId(\n input.author.organizationId,\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n },\n );\n const profile = await buildProvisionedOrganizationProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n materializedDocument: organizationProfileDocument,\n name: input.organizationProfileName,\n });\n return { organizationProfileDocument, profile };\n}\n\n/**\n * Organization labels use an independent system root with Admins/admin and\n * Members/read grants. Personal root shares and rotations cannot expose or\n * strand organization metadata; Members changes still rotate its own KEK.\n */\nexport async function buildInitialOrganizationMetadataBootstrap(\n input: InitialOrganizationMetadataBootstrapInput,\n): Promise<InitialOrganizationMetadataBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n containerId: input.containerId,\n icon: null,\n independentMetadataGroups: {\n adminGroup: input.initialAdminGroup,\n memberGroup: input.initialMemberGroup,\n },\n name: ORGANIZATION_METADATA_CONTAINER_NAME,\n // Both reserved groups receive explicit grants on the independent root.\n principalPolicies: await Promise.all([\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialAdminGroup),\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialMemberGroup),\n ]),\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { organizationProfileDocument, profile } =\n await buildInitialOrganizationProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n knownContainerKeks: core.knownContainerKeks,\n organizationProfileName: input.organizationProfileName,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n organizationProfileDocument,\n organizationProfileDocumentRequest: profile.request,\n organizationProfileSnapshot: profile.snapshot,\n systemSlot: core.systemSlot,\n };\n}\n\nexport async function buildInitialRootProvisioning(input: {\n adminGroup: CreateOrganizationGroupRequest;\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n bootstrap: Awaited<ReturnType<typeof createInitialRootMetadataBootstrap>>;\n recipientEncapsulationPublicKey: Uint8Array;\n rootContainerId: string;\n targetSecretKey: Uint8Array;\n}) {\n const rootContainer = await buildRootContainerCreatePlan({\n adminGroup: input.adminGroup,\n author: input.author,\n containerId: input.rootContainerId,\n metadataDocumentId: input.bootstrap.metadataDocumentId,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n });\n const rootContainerProjection = rootContainerWriterProjectionFromCreatePlan(\n rootContainer.plan,\n );\n const rootMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: rootContainerProjection,\n documentId: input.bootstrap.metadataDocumentId,\n knownContainerKeks: new Map([\n [rootContainer.plan.containerKeyEpochId, rootContainer.containerKey],\n ]),\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n return {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest: {\n ...rootMetadataDocument.plan.request,\n initialSync: await buildInitialDocumentSyncRequest({\n author: input.author,\n containerProjection: rootContainerProjection,\n initialUpdate: input.bootstrap.initialUpdate,\n materializedDocument: rootMetadataDocument,\n }),\n },\n };\n}\n"]}
@@ -1,16 +1,11 @@
1
- import { type EncapsulationKeyPair, type ReferencedPrincipalHead, type SigningKeyPair } from "../../internal/crypto/index.js";
1
+ import { type EncapsulationKeyPair, type SigningKeyPair } from "../../internal/crypto/index.js";
2
2
  import type { ProvisionedDocumentRequest, ProvisionedSystemContainerRequest, RegistrationRequest } from "../../internal/validators/request/index.js";
3
3
  import type { RegistrationResponse } 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
6
  import type { LocalUserIdentityCandidate } from "../../data/trustedUserIdentity/index.js";
7
- import type { OrganizationProvisioningArtifacts } from "./organizationProvisioningArtifacts.js";
8
- import { persistOrganizationProvisioningState } from "./organizationProvisioningPersistence.js";
9
7
  import type { ProvisionedPrincipalHistoryPrimer } from "./provisionedPrincipalHistory.js";
10
- import { type ProvisionedSystemContainerSpec } from "./provisioningBootstrapBuilders.js";
11
- export type { OrganizationProvisioningArtifacts } from "./organizationProvisioningArtifacts.js";
12
- export type { ProvisionedSystemContainerSpec } from "./provisioningBootstrapBuilders.js";
13
- export { persistOrganizationProvisioningState };
8
+ import type { ProvisionedSystemContainerSpec } from "./provisioningBootstrapBuilders.js";
14
9
  export interface RegistrationApi {
15
10
  registerUser(userId: string, organizationId: string, rootContainerId: string, signingPublicKey: Uint8Array, encapsulationPublicKey: Uint8Array, initialAdminGroup: RegistrationRequest["initialAdminGroup"], initialMemberGroup: RegistrationRequest["initialMemberGroup"], initialOrganizationPolicy: RegistrationRequest["initialOrganizationPolicy"], initialRootContainer: RegistrationRequest["initialRootContainer"], initialRootMetadataDocument: ProvisionedDocumentRequest, initialRosterProfileContainer: RegistrationRequest["initialRosterProfileContainer"], initialRosterProfileDocument: ProvisionedDocumentRequest | undefined, initialOrganizationMetadataContainer: ProvisionedSystemContainerRequest, initialOrganizationProfileDocument?: ProvisionedDocumentRequest | undefined, initialSystemContainers?: ProvisionedSystemContainerRequest[] | undefined): Promise<RegistrationResponse | null>;
16
11
  }
@@ -51,36 +46,4 @@ export interface RegisterIdentityInput {
51
46
  signingKeyFingerprint?: string | null | undefined;
52
47
  signingKeyPair: SigningKeyPair;
53
48
  }
54
- /**
55
- * The freshly built provisioning artifacts, shared by registration and
56
- * additional-organization creation. `registerIdentity` generates a new
57
- * `userId`; creating an additional organization reuses the caller's existing
58
- * one. Everything here is derived purely from the caller's key material, so it
59
- * is identical for both flows.
60
- */
61
- export interface OrganizationProvisioningArtifactsInput {
62
- encapsulationKeyPair: EncapsulationKeyPair;
63
- organizationProfileName?: string | undefined;
64
- /**
65
- * App-owned system containers to provision atomically with the organization
66
- * (e.g. a trash bin). Omitted/empty leaves the org with only the roster and
67
- * organization-metadata system containers.
68
- */
69
- provisionedSystemContainers?: ReadonlyArray<ProvisionedSystemContainerSpec> | undefined;
70
- rootContainerId: string;
71
- rosterProfileNickname?: string | undefined;
72
- signingKeyPair: SigningKeyPair;
73
- userId: string;
74
- }
75
- export declare function buildInitialOrganizationPolicyRequest(input: {
76
- adminGroupId: string;
77
- groupHeads: readonly ReferencedPrincipalHead[];
78
- encapsulationPublicKey: Uint8Array;
79
- memberGroupId: string;
80
- organizationId: string;
81
- signingKeyPair: SigningKeyPair;
82
- userId: string;
83
- }): Promise<RegistrationRequest["initialOrganizationPolicy"]>;
84
- /** Builds the signed artifacts shared by registration and org creation. */
85
- export declare function buildOrganizationProvisioningArtifacts(input: OrganizationProvisioningArtifactsInput): Promise<OrganizationProvisioningArtifacts>;
86
49
  export declare function registerIdentity(input: RegisterIdentityInput): Promise<RegistrationResponse | null>;
@@ -1,212 +1,7 @@
1
- import { buildPrincipalStateSigningInput, generateKemSeedAndKeyPair, KeyingVerificationError, signPrincipalState, toFingerprint, wrapDekForRecipients, } from "../../internal/crypto/index.js";
2
- import { bytesToBase64 } from "../../internal/encoding/index.js";
3
- import { encodeOrganizationAuthorityDescriptor } from "../../data/principals/organizationAuthorityDescriptor.js";
1
+ import { KeyingVerificationError, } from "../../internal/crypto/index.js";
4
2
  import { validateUserIdentityKeys } from "../../data/trustedUserIdentity/index.js";
5
- import { resolveDocumentCreateAuthor } from "../documents/author.js";
6
- import { groupPolicyMutationHead } from "../organizations/groupPolicy/groupPolicyMutationHead.js";
7
- import { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, } from "../organizations/principalPolicy/index.js";
3
+ import { buildOrganizationProvisioningArtifacts } from "./organizationProvisioning.js";
8
4
  import { persistOrganizationProvisioningState } from "./organizationProvisioningPersistence.js";
9
- import { buildInitialOrganizationMetadataBootstrap, buildInitialRootProvisioning, buildInitialRosterProfileBootstrap, buildInitialSystemContainerBootstrap, } from "./provisioningBootstrapBuilders.js";
10
- import { createInitialRootMetadataBootstrap } from "./rootMetadataBootstrap.js";
11
- export { persistOrganizationProvisioningState };
12
- export async function buildInitialOrganizationPolicyRequest(input) {
13
- const organizationKem = generateKemSeedAndKeyPair();
14
- const signerUserKeyFingerprint = await toFingerprint(input.signingKeyPair.signingPublicKey);
15
- const userEncapsulationKeyFingerprint = await toFingerprint(input.encapsulationPublicKey);
16
- const projection = [
17
- {
18
- userId: input.userId,
19
- role: "admin",
20
- },
21
- ];
22
- const payloadCiphertext = encodeOrganizationAuthorityDescriptor({
23
- version: 2,
24
- organizationId: input.organizationId,
25
- adminGroupId: input.adminGroupId,
26
- memberGroupId: input.memberGroupId,
27
- groupHeads: input.groupHeads.map((head) => {
28
- if (head.principalType !== "group") {
29
- throw new Error("Organization directory can contain only group heads");
30
- }
31
- return { ...head, principalType: "group" };
32
- }),
33
- });
34
- const [memberEnvelope] = await wrapDekForRecipients(organizationKem.secretKey, [input.encapsulationPublicKey]);
35
- if (!memberEnvelope) {
36
- throw new Error("Failed to wrap organization key for registering user");
37
- }
38
- const memberEnvelopes = [
39
- {
40
- userId: input.userId,
41
- memberKeyFingerprint: userEncapsulationKeyFingerprint,
42
- kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),
43
- wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),
44
- },
45
- ];
46
- const state = await signPrincipalState(await buildPrincipalStateSigningInput({
47
- principalType: "organization",
48
- principalId: input.organizationId,
49
- version: 1,
50
- prevStateHash: null,
51
- keyEpoch: 1,
52
- encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),
53
- keyFingerprint: await toFingerprint(organizationKem.publicKey),
54
- members: [{ userId: input.userId }],
55
- memberEnvelopes,
56
- projection,
57
- grants: [],
58
- payloadCiphertext,
59
- externalAuthority: null,
60
- signedAt: new Date().toISOString(),
61
- signerUserId: input.userId,
62
- signerUserKeyFingerprint,
63
- }), input.signingKeyPair.signingPrivateKey);
64
- return {
65
- state,
66
- encryptedPayload: {
67
- cipherSuite: "aes-256-gcm",
68
- ciphertext: payloadCiphertext,
69
- ciphertextHash: state.payloadCiphertextHash,
70
- },
71
- projection,
72
- grants: [],
73
- memberEnvelopes,
74
- };
75
- }
76
- async function createOrganizationPrincipalPolicies(input) {
77
- const organizationId = crypto.randomUUID();
78
- const signingFingerprint = await toFingerprint(input.signingKeyPair.signingPublicKey);
79
- const initialAdminGroup = await buildInitialGroupPolicyRequest({
80
- creatorEncapsulationKeyPair: input.encapsulationKeyPair,
81
- groupId: crypto.randomUUID(),
82
- grants: [
83
- { containerId: input.rootContainerId, accessLevel: "admin" },
84
- {
85
- containerId: input.organizationMetadataContainerId,
86
- accessLevel: "admin",
87
- },
88
- ],
89
- name: "Admins",
90
- builtinRole: "admins",
91
- signerUserId: input.userId,
92
- signingFingerprint,
93
- signingKeyPair: input.signingKeyPair,
94
- });
95
- const initialMemberGroup = await buildInitialMemberGroupPolicyRequest({
96
- creatorEncapsulationKeyPair: input.encapsulationKeyPair,
97
- groupId: crypto.randomUUID(),
98
- grants: [
99
- {
100
- containerId: input.organizationMetadataContainerId,
101
- accessLevel: "read",
102
- },
103
- ],
104
- signerUserId: input.userId,
105
- signingFingerprint,
106
- signingKeyPair: input.signingKeyPair,
107
- });
108
- const initialOrganizationPolicy = await buildInitialOrganizationPolicyRequest({
109
- adminGroupId: initialAdminGroup.groupId,
110
- encapsulationPublicKey: input.encapsulationKeyPair.publicKey,
111
- groupHeads: await Promise.all([
112
- groupPolicyMutationHead(initialAdminGroup.initialGroupPolicy),
113
- groupPolicyMutationHead(initialMemberGroup.initialGroupPolicy),
114
- ]),
115
- memberGroupId: initialMemberGroup.groupId,
116
- organizationId,
117
- signingKeyPair: input.signingKeyPair,
118
- userId: input.userId,
119
- });
120
- return {
121
- initialAdminGroup,
122
- initialMemberGroup,
123
- initialOrganizationPolicy,
124
- organizationId,
125
- signingFingerprint,
126
- };
127
- }
128
- function requireOrganizationProvisioningAuthor(input) {
129
- const author = resolveDocumentCreateAuthor({
130
- auth: { organizationId: input.organizationId, userId: input.userId },
131
- crypto: {
132
- signingFingerprint: input.signingFingerprint,
133
- signingKeyPair: input.signingKeyPair,
134
- },
135
- });
136
- if (!author) {
137
- throw new Error(`Organization provisioning document author context is unavailable for user ${input.userId} in organization ${input.organizationId}.`);
138
- }
139
- return author;
140
- }
141
- /** Builds the signed artifacts shared by registration and org creation. */
142
- export async function buildOrganizationProvisioningArtifacts(input) {
143
- const bootstrap = await createInitialRootMetadataBootstrap(input.rootContainerId);
144
- const organizationMetadataContainerId = crypto.randomUUID();
145
- const { initialAdminGroup, initialMemberGroup, initialOrganizationPolicy, organizationId, signingFingerprint, } = await createOrganizationPrincipalPolicies({
146
- encapsulationKeyPair: input.encapsulationKeyPair,
147
- organizationMetadataContainerId,
148
- rootContainerId: input.rootContainerId,
149
- signingKeyPair: input.signingKeyPair,
150
- userId: input.userId,
151
- });
152
- const author = requireOrganizationProvisioningAuthor({
153
- organizationId,
154
- signingFingerprint,
155
- signingKeyPair: input.signingKeyPair,
156
- userId: input.userId,
157
- });
158
- const { rootContainer, rootContainerProjection, rootMetadataDocument, rootMetadataDocumentRequest, } = await buildInitialRootProvisioning({
159
- adminGroup: initialAdminGroup,
160
- author,
161
- bootstrap,
162
- recipientEncapsulationPublicKey: input.encapsulationKeyPair.publicKey,
163
- rootContainerId: input.rootContainerId,
164
- targetSecretKey: input.encapsulationKeyPair.secretKey,
165
- });
166
- const rosterProfileBootstrap = await buildInitialRosterProfileBootstrap({
167
- author,
168
- encapsulationPublicKey: input.encapsulationKeyPair.publicKey,
169
- initialAdminGroup,
170
- rosterProfileNickname: input.rosterProfileNickname,
171
- rootContainer,
172
- rootContainerProjection,
173
- targetSecretKey: input.encapsulationKeyPair.secretKey,
174
- });
175
- const organizationMetadataBootstrap = await buildInitialOrganizationMetadataBootstrap({
176
- author,
177
- containerId: organizationMetadataContainerId,
178
- initialAdminGroup,
179
- initialMemberGroup,
180
- organizationProfileName: input.organizationProfileName,
181
- rootContainer,
182
- rootContainerProjection,
183
- targetSecretKey: input.encapsulationKeyPair.secretKey,
184
- });
185
- const systemContainerBootstraps = await Promise.all((input.provisionedSystemContainers ?? []).map((spec) => buildInitialSystemContainerBootstrap({
186
- author,
187
- initialAdminGroup,
188
- rootContainer,
189
- rootContainerProjection,
190
- signingPrivateKey: input.signingKeyPair.signingPrivateKey,
191
- spec,
192
- targetSecretKey: input.encapsulationKeyPair.secretKey,
193
- })));
194
- return {
195
- replacementAuthorization: null,
196
- bootstrap,
197
- initialAdminGroup,
198
- initialMemberGroup,
199
- initialOrganizationPolicy,
200
- initialRootContainer: rootContainer.plan.request,
201
- organizationId,
202
- organizationMetadataBootstrap,
203
- rootContainer,
204
- rootMetadataDocument,
205
- rootMetadataDocumentRequest,
206
- rosterProfileBootstrap,
207
- systemContainerBootstraps,
208
- };
209
- }
210
5
  export async function registerIdentity(input) {
211
6
  input.log?.("Registering identity...");
212
7
  await validateUserIdentityKeys({
@@ -1 +1 @@
1
- {"version":3,"file":"registerIdentity.js","sourceRoot":"","sources":["registerIdentity.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAE/B,yBAAyB,EACzB,uBAAuB,EAGvB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AASpD,OAAO,EAAE,qCAAqC,EAAE,MAAM,uDAAuD,CAAC;AAG9G,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,uBAAuB,EAAE,MAAM,sDAAsD,CAAC;AAC/F,OAAO,EACL,8BAA8B,EAC9B,oCAAoC,GACrC,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAAE,oCAAoC,EAAE,MAAM,uCAAuC,CAAC;AAE7F,OAAO,EACL,yCAAyC,EACzC,4BAA4B,EAC5B,kCAAkC,EAClC,oC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AChD,yBAAyB,EAAE,SAAS,CAAC,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 buildPrincipalStateSigningInput,\n type EncapsulationKeyPair,\n generateKemSeedAndKeyPair,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n CreateOrganizationGroupRequest,\n ProvisionedDocumentRequest,\n ProvisionedSystemContainerRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { RegistrationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { encodeOrganizationAuthorityDescriptor } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type { LocalUserIdentityCandidate } from \"../../data/trustedUserIdentity\";\nimport { validateUserIdentityKeys } from \"../../data/trustedUserIdentity\";\nimport { resolveDocumentCreateAuthor } from \"../documents/author\";\nimport { groupPolicyMutationHead } from \"../organizations/groupPolicy/groupPolicyMutationHead\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../organizations/principalPolicy\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nimport type { ProvisionedPrincipalHistoryPrimer } from \"./provisionedPrincipalHistory\";\nimport {\n buildInitialOrganizationMetadataBootstrap,\n buildInitialRootProvisioning,\n buildInitialRosterProfileBootstrap,\n buildInitialSystemContainerBootstrap,\n type ProvisionedSystemContainerSpec,\n} from \"./provisioningBootstrapBuilders\";\nimport { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\nexport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nexport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\nexport { persistOrganizationProvisioningState };\n\nexport interface RegistrationApi {\n registerUser(\n userId: string,\n organizationId: string,\n rootContainerId: string,\n signingPublicKey: Uint8Array,\n encapsulationPublicKey: Uint8Array,\n initialAdminGroup: RegistrationRequest[\"initialAdminGroup\"],\n initialMemberGroup: RegistrationRequest[\"initialMemberGroup\"],\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"],\n initialRootContainer: RegistrationRequest[\"initialRootContainer\"],\n initialRootMetadataDocument: ProvisionedDocumentRequest,\n initialRosterProfileContainer: RegistrationRequest[\"initialRosterProfileContainer\"],\n initialRosterProfileDocument: ProvisionedDocumentRequest | undefined,\n initialOrganizationMetadataContainer: ProvisionedSystemContainerRequest,\n initialOrganizationProfileDocument?: ProvisionedDocumentRequest | undefined,\n initialSystemContainers?: ProvisionedSystemContainerRequest[] | undefined,\n ): Promise<RegistrationResponse | null>;\n}\n\ninterface OrganizationProvisioningPrincipalPolicies {\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"];\n organizationId: string;\n signingFingerprint: string;\n}\n\nexport interface RegisterIdentityInput {\n apiClient: RegistrationApi;\n containerId: string;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n /**\n * Reports whether the identity that started this registration is still\n * current. Forwarded to the bootstrap persist's in-mutex currency check,\n * so an identity replaced while the persist waits for the mutation queue\n * cannot write its bootstrap through a client the replacement owns.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /**\n * Overrides the seeded personal-org profile name; defaults to \"Personal Org\".\n */\n organizationProfileName?: string | undefined;\n pinLocalUserIdentity: (\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ) => Promise<void>;\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 personal\n * organization (e.g. a trash bin). See {@link ProvisionedSystemContainerSpec}.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /**\n * Overrides the seeded self roster-profile nickname; defaults to \"You\". The\n * demo host passes each pane's peer-labeled self name (\"Peer 1 (You)\").\n */\n rosterProfileNickname?: string | undefined;\n signingKeyFingerprint?: string | null | undefined;\n signingKeyPair: SigningKeyPair;\n}\n\n/**\n * The freshly built provisioning artifacts, shared by registration and\n * additional-organization creation. `registerIdentity` generates a new\n * `userId`; creating an additional organization reuses the caller's existing\n * one. Everything here is derived purely from the caller's key material, so it\n * is identical for both flows.\n */\nexport interface OrganizationProvisioningArtifactsInput {\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationProfileName?: string | undefined;\n /**\n * App-owned system containers to provision atomically with the organization\n * (e.g. a trash bin). Omitted/empty leaves the org with only the roster and\n * organization-metadata system containers.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n rootContainerId: string;\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}\n\nexport async function buildInitialOrganizationPolicyRequest(input: {\n adminGroupId: string;\n groupHeads: readonly ReferencedPrincipalHead[];\n encapsulationPublicKey: Uint8Array;\n memberGroupId: string;\n organizationId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<RegistrationRequest[\"initialOrganizationPolicy\"]> {\n const organizationKem = generateKemSeedAndKeyPair();\n const signerUserKeyFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const userEncapsulationKeyFingerprint = await toFingerprint(\n input.encapsulationPublicKey,\n );\n const projection = [\n {\n userId: input.userId,\n role: \"admin\" as const,\n },\n ];\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n version: 2,\n organizationId: input.organizationId,\n adminGroupId: input.adminGroupId,\n memberGroupId: input.memberGroupId,\n groupHeads: input.groupHeads.map((head) => {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n }),\n });\n const [memberEnvelope] = await wrapDekForRecipients(\n organizationKem.secretKey,\n [input.encapsulationPublicKey],\n );\n\n if (!memberEnvelope) {\n throw new Error(\"Failed to wrap organization key for registering user\");\n }\n const memberEnvelopes = [\n {\n userId: input.userId,\n memberKeyFingerprint: userEncapsulationKeyFingerprint,\n kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),\n },\n ];\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.organizationId,\n version: 1,\n prevStateHash: null,\n keyEpoch: 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: [{ userId: input.userId }],\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.userId,\n signerUserKeyFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants: [],\n memberEnvelopes,\n };\n}\n\nasync function createOrganizationPrincipalPolicies(input: {\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationMetadataContainerId: string;\n rootContainerId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<OrganizationProvisioningPrincipalPolicies> {\n const organizationId = crypto.randomUUID();\n const signingFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const initialAdminGroup = await buildInitialGroupPolicyRequest({\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n { containerId: input.rootContainerId, accessLevel: \"admin\" },\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"admin\",\n },\n ],\n name: \"Admins\",\n builtinRole: \"admins\",\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialMemberGroup = await buildInitialMemberGroupPolicyRequest({\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"read\",\n },\n ],\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialOrganizationPolicy = await buildInitialOrganizationPolicyRequest(\n {\n adminGroupId: initialAdminGroup.groupId,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n groupHeads: await Promise.all([\n groupPolicyMutationHead(initialAdminGroup.initialGroupPolicy),\n groupPolicyMutationHead(initialMemberGroup.initialGroupPolicy),\n ]),\n memberGroupId: initialMemberGroup.groupId,\n organizationId,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n },\n );\n\n return {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n };\n}\n\nfunction requireOrganizationProvisioningAuthor(input: {\n readonly organizationId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}) {\n const author = resolveDocumentCreateAuthor({\n auth: { organizationId: input.organizationId, userId: input.userId },\n crypto: {\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n },\n });\n if (!author) {\n throw new Error(\n `Organization provisioning document author context is unavailable for user ${input.userId} in organization ${input.organizationId}.`,\n );\n }\n return author;\n}\n\n/** Builds the signed artifacts shared by registration and org creation. */\nexport async function buildOrganizationProvisioningArtifacts(\n input: OrganizationProvisioningArtifactsInput,\n): Promise<OrganizationProvisioningArtifacts> {\n const bootstrap = await createInitialRootMetadataBootstrap(\n input.rootContainerId,\n );\n const organizationMetadataContainerId = crypto.randomUUID();\n const {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n } = await createOrganizationPrincipalPolicies({\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationMetadataContainerId,\n rootContainerId: input.rootContainerId,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n });\n const author = requireOrganizationProvisioningAuthor({\n organizationId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n });\n\n const {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n } = await buildInitialRootProvisioning({\n adminGroup: initialAdminGroup,\n author,\n bootstrap,\n recipientEncapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n rootContainerId: input.rootContainerId,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const rosterProfileBootstrap = await buildInitialRosterProfileBootstrap({\n author,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n initialAdminGroup,\n rosterProfileNickname: input.rosterProfileNickname,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const organizationMetadataBootstrap =\n await buildInitialOrganizationMetadataBootstrap({\n author,\n containerId: organizationMetadataContainerId,\n initialAdminGroup,\n initialMemberGroup,\n organizationProfileName: input.organizationProfileName,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const systemContainerBootstraps = await Promise.all(\n (input.provisionedSystemContainers ?? []).map((spec) =>\n buildInitialSystemContainerBootstrap({\n author,\n initialAdminGroup,\n rootContainer,\n rootContainerProjection,\n signingPrivateKey: input.signingKeyPair.signingPrivateKey,\n spec,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n }),\n ),\n );\n\n return {\n replacementAuthorization: null,\n bootstrap,\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer: rootContainer.plan.request,\n organizationId,\n organizationMetadataBootstrap,\n rootContainer,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n rosterProfileBootstrap,\n systemContainerBootstraps,\n };\n}\n\nexport async function registerIdentity(\n input: RegisterIdentityInput,\n): Promise<RegistrationResponse | null> {\n input.log?.(\"Registering identity...\");\n await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingKeyFingerprint: input.signingKeyFingerprint,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n },\n });\n\n const newUserId = crypto.randomUUID();\n const artifacts = await buildOrganizationProvisioningArtifacts({\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId: input.containerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: newUserId,\n });\n\n const response = await input.apiClient.registerUser(\n newUserId,\n artifacts.organizationId,\n input.containerId,\n input.signingKeyPair.signingPublicKey,\n input.encapsulationKeyPair.publicKey,\n artifacts.initialAdminGroup,\n artifacts.initialMemberGroup,\n artifacts.initialOrganizationPolicy,\n artifacts.initialRootContainer,\n artifacts.rootMetadataDocumentRequest,\n artifacts.rosterProfileBootstrap.containerRequest,\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n artifacts.organizationMetadataBootstrap.containerRequest,\n artifacts.organizationMetadataBootstrap.organizationProfileDocumentRequest,\n artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n );\n if (!response) {\n return null;\n }\n if (response.userId !== newUserId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Registration response user does not match the requested identity\",\n );\n }\n // Pinned only once the server has confirmed this user, and before anything\n // is persisted under it. The trust store binds each signing key to one user,\n // so a pin for an id the server never accepted — a retry after a lost\n // response, or a restored key that is already registered — would later\n // refuse the key's real user at login. Like the persistence below, it is a\n // durable write, so it is skipped once the registering identity has been\n // replaced: the caller discards this result.\n if (input.isIdentityCurrent?.() ?? true) {\n await input.pinLocalUserIdentity(newUserId, {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n }\n\n input.log?.(`Key registered (${response.userId})`);\n await persistOrganizationProvisioningState({\n bootstrap: artifacts.bootstrap,\n canStartDurableMutation: input.isIdentityCurrent,\n onPersistQueued: input.onPersistQueued,\n containerId: input.containerId,\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":"registerIdentity.js","sourceRoot":"","sources":["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5C,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;QAC9C,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;QAChD,yBAAyB,EAAE,SAAS,CAAC,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 KeyingVerificationError,\n type SigningKeyPair,\n} from \"@tearleads/crypto\";\nimport type {\n ProvisionedDocumentRequest,\n ProvisionedSystemContainerRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { RegistrationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type { LocalUserIdentityCandidate } from \"../../data/trustedUserIdentity\";\nimport { validateUserIdentityKeys } from \"../../data/trustedUserIdentity\";\nimport { buildOrganizationProvisioningArtifacts } from \"./organizationProvisioning\";\nimport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nimport type { ProvisionedPrincipalHistoryPrimer } from \"./provisionedPrincipalHistory\";\nimport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\nexport interface RegistrationApi {\n registerUser(\n userId: string,\n organizationId: string,\n rootContainerId: string,\n signingPublicKey: Uint8Array,\n encapsulationPublicKey: Uint8Array,\n initialAdminGroup: RegistrationRequest[\"initialAdminGroup\"],\n initialMemberGroup: RegistrationRequest[\"initialMemberGroup\"],\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"],\n initialRootContainer: RegistrationRequest[\"initialRootContainer\"],\n initialRootMetadataDocument: ProvisionedDocumentRequest,\n initialRosterProfileContainer: RegistrationRequest[\"initialRosterProfileContainer\"],\n initialRosterProfileDocument: ProvisionedDocumentRequest | undefined,\n initialOrganizationMetadataContainer: ProvisionedSystemContainerRequest,\n initialOrganizationProfileDocument?: ProvisionedDocumentRequest | undefined,\n initialSystemContainers?: ProvisionedSystemContainerRequest[] | undefined,\n ): Promise<RegistrationResponse | null>;\n}\n\nexport interface RegisterIdentityInput {\n apiClient: RegistrationApi;\n containerId: string;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n /**\n * Reports whether the identity that started this registration is still\n * current. Forwarded to the bootstrap persist's in-mutex currency check,\n * so an identity replaced while the persist waits for the mutation queue\n * cannot write its bootstrap through a client the replacement owns.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /**\n * Overrides the seeded personal-org profile name; defaults to \"Personal Org\".\n */\n organizationProfileName?: string | undefined;\n pinLocalUserIdentity: (\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ) => Promise<void>;\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 personal\n * organization (e.g. a trash bin). See {@link ProvisionedSystemContainerSpec}.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /**\n * Overrides the seeded self roster-profile nickname; defaults to \"You\". The\n * demo host passes each pane's peer-labeled self name (\"Peer 1 (You)\").\n */\n rosterProfileNickname?: string | undefined;\n signingKeyFingerprint?: string | null | undefined;\n signingKeyPair: SigningKeyPair;\n}\n\nexport async function registerIdentity(\n input: RegisterIdentityInput,\n): Promise<RegistrationResponse | null> {\n input.log?.(\"Registering identity...\");\n await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingKeyFingerprint: input.signingKeyFingerprint,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n },\n });\n\n const newUserId = crypto.randomUUID();\n const artifacts = await buildOrganizationProvisioningArtifacts({\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId: input.containerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: newUserId,\n });\n\n const response = await input.apiClient.registerUser(\n newUserId,\n artifacts.organizationId,\n input.containerId,\n input.signingKeyPair.signingPublicKey,\n input.encapsulationKeyPair.publicKey,\n artifacts.initialAdminGroup,\n artifacts.initialMemberGroup,\n artifacts.initialOrganizationPolicy,\n artifacts.initialRootContainer,\n artifacts.rootMetadataDocumentRequest,\n artifacts.rosterProfileBootstrap.containerRequest,\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n artifacts.organizationMetadataBootstrap.containerRequest,\n artifacts.organizationMetadataBootstrap.organizationProfileDocumentRequest,\n artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n );\n if (!response) {\n return null;\n }\n if (response.userId !== newUserId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Registration response user does not match the requested identity\",\n );\n }\n // Pinned only once the server has confirmed this user, and before anything\n // is persisted under it. The trust store binds each signing key to one user,\n // so a pin for an id the server never accepted — a retry after a lost\n // response, or a restored key that is already registered — would later\n // refuse the key's real user at login. Like the persistence below, it is a\n // durable write, so it is skipped once the registering identity has been\n // replaced: the caller discards this result.\n if (input.isIdentityCurrent?.() ?? true) {\n await input.pinLocalUserIdentity(newUserId, {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n }\n\n input.log?.(`Key registered (${response.userId})`);\n await persistOrganizationProvisioningState({\n bootstrap: artifacts.bootstrap,\n canStartDurableMutation: input.isIdentityCurrent,\n onPersistQueued: input.onPersistQueued,\n containerId: input.containerId,\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,10 +1,10 @@
1
1
  import { createDocument, exportAllUpdates } from "../../internal/loro/index.js";
2
2
  import { and, eq, ne, or, sql } from "drizzle-orm";
3
- import { getDocumentAttachments, } from "../../data/documents/documentContent.js";
3
+ import { getDocumentAttachments, } from "../../data/documents/index.js";
4
4
  import { createPendingUpdateFields } from "../../data/documents/documentSync.js";
5
5
  import { DOCUMENTS_APP_KIND } from "../../data/persistence/documents/documentsPersistence.js";
6
6
  import { documentAttachmentBlobProjection, documentHistoryCheckpoints, documentHistoryUpdates, documentPendingAttachments, documents, } from "../../data/sqlite/schema/index.js";
7
- import { importDocumentHistoryTailUpdates } from "../documents/historyContent.js";
7
+ import { importDocumentHistoryTailUpdates } from "../documents/index.js";
8
8
  import { remoteResetBatches } from "./remoteResetBatches.js";
9
9
  function historyScopeKey(appKind, localId) {
10
10
  return `${appKind} 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AAiB,EAAE,eAAe,EAAE,CAAC;AAChD,CAAC","sourcesContent":["import { createDocument, exportAllUpdates } from \"@tearleads/loro\";\nimport { and, eq, ne, or, sql } from \"drizzle-orm\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n} from \"../../data/documents/documentContent\";\nimport { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport { DOCUMENTS_APP_KIND } from \"../../data/persistence/documents/documentsPersistence\";\nimport {\n documentAttachmentBlobProjection,\n documentHistoryCheckpoints,\n documentHistoryUpdates,\n documentPendingAttachments,\n documents,\n} from \"../../data/sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport { importDocumentHistoryTailUpdates } from \"../documents/historyContent\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\n\nexport interface ResetDocumentUpdate {\n readonly appKind: string;\n readonly localId: string;\n readonly updateData: string;\n readonly partialStartVersionVector: string;\n readonly partialEndVersionVector: string;\n readonly sourceVersionVector: string | null;\n}\n\nexport interface ResetAttachmentUpload {\n readonly byteLength: number;\n readonly contentSha256: string;\n readonly localId: string;\n readonly mimeType: string | null;\n readonly name: string;\n readonly slotId: string;\n readonly storageKey: string;\n}\n\ntype ResetContentDoc = Awaited<ReturnType<typeof createDocument>>;\n\nfunction historyScopeKey(appKind: string, localId: string): string {\n return `${appKind} ${localId}`;\n}\n\nfunction attachmentScopeKey(localId: string, slotId: string): string {\n return `${localId}\\0${slotId}`;\n}\n\nfunction buildResetUpdate(input: {\n appKind: string;\n doc: ResetContentDoc;\n localId: string;\n}): ResetDocumentUpdate | null {\n const fields = createPendingUpdateFields(exportAllUpdates(input.doc));\n if (!fields) {\n return null;\n }\n\n return {\n appKind: input.appKind,\n localId: input.localId,\n updateData: fields.updateData,\n partialStartVersionVector: fields.partialStartVersionVector,\n partialEndVersionVector: fields.partialEndVersionVector,\n sourceVersionVector: fields.sourceVersionVector ?? null,\n };\n}\n\ninterface ResetHistoryRows {\n checkpointRows: Array<{\n appKind: string;\n localId: string;\n snapshot: string;\n }>;\n tailRows: Array<{\n appKind: string;\n localId: string;\n updateData: string;\n }>;\n}\n\nasync function loadResetHistoryRows(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<ResetHistoryRows> {\n const rows: ResetHistoryRows = { checkpointRows: [], tailRows: [] };\n const scopes = documentScopes\n ? [\n ...new Map(\n documentScopes.map((scope) => [\n historyScopeKey(scope.appKind, scope.localId),\n scope,\n ]),\n ).values(),\n ]\n : null;\n for (const scopeBatch of scopes ? remoteResetBatches(scopes) : [null]) {\n // An outbox row only waits to be sent; the content lives in the\n // checkpoint and tail rows (see `documentHistoryUpdates`).\n const notOutbox = ne(documentHistoryUpdates.origin, \"outbox\");\n const scopeTail = scopeBatch\n ? and(\n notOutbox,\n or(\n ...scopeBatch.map((scope) =>\n and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n ),\n ),\n ),\n )\n : notOutbox;\n const scopeCheckpoints = scopeBatch\n ? or(\n ...scopeBatch.map((scope) =>\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n ),\n )\n : undefined;\n const tailBatch = await db\n .select({\n appKind: documentHistoryUpdates.appKind,\n localId: documentHistoryUpdates.localId,\n updateData: documentHistoryUpdates.updateData,\n })\n .from(documentHistoryUpdates)\n .where(scopeTail)\n .orderBy(sql`rowid`);\n const checkpointBatch = await db\n .select({\n appKind: documentHistoryCheckpoints.appKind,\n localId: documentHistoryCheckpoints.localId,\n snapshot: documentHistoryCheckpoints.snapshot,\n })\n .from(documentHistoryCheckpoints)\n .where(scopeCheckpoints);\n rows.tailRows.push(...tailBatch);\n rows.checkpointRows.push(...checkpointBatch);\n }\n return rows;\n}\n\n/**\n * Reconstruct every persisted document's content from the durable-history\n * tables (checkpoint + tail) — the only content source. A scope without a\n * checkpoint (a discovered shell that never hydrated) gets no doc: it has no\n * content to republish and no attachments to requeue. The mode-sniffing tail\n * import handles both content kinds — full-history snapshots (documents) and\n * exported-updates blobs (container metadata).\n */\nasync function buildResetContentDocs(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<Map<string, ResetContentDoc>> {\n // Read the TAIL before the checkpoints (the same order the restore path\n // uses): a compaction landing between the two reads then yields old-tail +\n // new-checkpoint — a safe superset, since replay is idempotent by op\n // identity — whereas the reverse order could yield an old checkpoint plus\n // an already-emptied tail and republish stale content.\n const { checkpointRows, tailRows } = await loadResetHistoryRows(\n db,\n documentScopes,\n );\n\n const tailByScope = new Map<string, string[]>();\n for (const row of tailRows) {\n const key = historyScopeKey(row.appKind, row.localId);\n const tail = tailByScope.get(key);\n if (tail) {\n tail.push(row.updateData);\n } else {\n tailByScope.set(key, [row.updateData]);\n }\n }\n\n // Rebuild the UNION of checkpoint and tail scopes: a tail-only scope (a\n // crash landed the first edit's tail row before the birth checkpoint) may\n // hold the only durable copy of that edit, and dropping it from the reset\n // would discard it.\n const checkpointByScope = new Map(\n checkpointRows.map((row) => [\n historyScopeKey(row.appKind, row.localId),\n row,\n ]),\n );\n const historyScopes = new Map<string, { appKind: string; localId: string }>();\n for (const row of [...checkpointRows, ...tailRows]) {\n historyScopes.set(historyScopeKey(row.appKind, row.localId), {\n appKind: row.appKind,\n localId: row.localId,\n });\n }\n\n const contentDocByScope = new Map<string, ResetContentDoc>();\n await Promise.all(\n [...historyScopes.entries()].map(async ([key, scope]) => {\n const doc = await createDocument(\n `remote-reset:${scope.appKind}:${scope.localId}`,\n );\n const checkpoint = checkpointByScope.get(key);\n // An empty checkpoint blob (e.g. container metadata saved before any\n // update existed) carries no ops — importing it would throw and fail\n // the whole reset.\n importDocumentHistoryTailUpdates(\n doc,\n [\n ...(checkpoint ? [checkpoint.snapshot] : []),\n ...(tailByScope.get(key) ?? []),\n ].filter((blob) => blob.length > 0),\n );\n contentDocByScope.set(key, doc);\n }),\n );\n return contentDocByScope;\n}\n\nexport interface ResetDocumentScope {\n readonly appKind: string;\n readonly localId: string;\n}\n\nasync function loadResetPlanRows(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n) {\n const selectedScopeKeys = documentScopes\n ? new Set(\n documentScopes.map((scope) =>\n historyScopeKey(scope.appKind, scope.localId),\n ),\n )\n : null;\n const allDocumentRows = await db\n .select({ appKind: documents.appKind, localId: documents.localId })\n .from(documents);\n const documentRows = selectedScopeKeys\n ? allDocumentRows.filter((row) =>\n selectedScopeKeys.has(historyScopeKey(row.appKind, row.localId)),\n )\n : allDocumentRows;\n const [allAttachmentRows, pendingAttachmentRows] = await Promise.all([\n db\n .select({\n byteLength: documentAttachmentBlobProjection.byteLength,\n localId: documentAttachmentBlobProjection.localId,\n mimeType: documentAttachmentBlobProjection.mimeType,\n slotId: documentAttachmentBlobProjection.slotId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n })\n .from(documentAttachmentBlobProjection),\n db\n .select({\n byteLength: documentPendingAttachments.byteLength,\n localId: documentPendingAttachments.localId,\n mimeType: documentPendingAttachments.mimeType,\n slotId: documentPendingAttachments.slotId,\n storageKey: documentPendingAttachments.storageKey,\n })\n .from(documentPendingAttachments),\n ]);\n const selectedDocumentLocalIds = new Set(\n documentRows\n .filter((row) => row.appKind === DOCUMENTS_APP_KIND)\n .map((row) => row.localId),\n );\n const attachmentRows = new Map(\n allAttachmentRows\n .filter((row) => selectedDocumentLocalIds.has(row.localId))\n .map((row) => [attachmentScopeKey(row.localId, row.slotId), row]),\n );\n for (const row of pendingAttachmentRows) {\n if (selectedDocumentLocalIds.has(row.localId)) {\n attachmentRows.set(attachmentScopeKey(row.localId, row.slotId), row);\n }\n }\n return {\n attachmentRows: [...attachmentRows.values()],\n documentRows,\n };\n}\n\nexport async function buildResetPlans(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<{\n readonly attachmentUploads: ResetAttachmentUpload[];\n readonly documentUpdates: ResetDocumentUpdate[];\n}> {\n const { attachmentRows, documentRows } = await loadResetPlanRows(\n db,\n documentScopes,\n );\n const contentDocByScope = await buildResetContentDocs(db, documentScopes);\n const documentUpdates = documentRows.flatMap((row) => {\n const doc = contentDocByScope.get(\n historyScopeKey(row.appKind, row.localId),\n );\n if (!doc) {\n return [];\n }\n const update = buildResetUpdate({\n appKind: row.appKind,\n doc,\n localId: row.localId,\n });\n return update ? [update] : [];\n });\n const attachmentIntentMaps = new Map<\n string,\n Map<string, DocumentAttachment>\n >();\n const attachmentLocalIds = [\n ...new Set(attachmentRows.map((attachment) => attachment.localId)),\n ];\n for (const localId of attachmentLocalIds) {\n const doc = contentDocByScope.get(\n historyScopeKey(DOCUMENTS_APP_KIND, localId),\n );\n if (!doc) {\n continue;\n }\n attachmentIntentMaps.set(\n localId,\n new Map(\n getDocumentAttachments(doc).map((attachment) => [\n attachment.slotId,\n attachment,\n ]),\n ),\n );\n }\n\n // A reset re-uploads the local attachments as pending work, and the durable\n // document decides which rows those are: a row whose slot the snapshot no\n // longer advertises belongs to an unlink, and re-queueing it would resurrect\n // an attachment the document dropped. Reading the snapshot rather than the\n // detach marker keeps the two halves of an interrupted unlink consistent —\n // there the marker is set but the snapshot still advertises the slot, and the\n // reset has to upload it to match the document it is about to republish.\n const attachmentUploads = attachmentRows.flatMap((attachment) => {\n const intent = attachmentIntentMaps\n .get(attachment.localId)\n ?.get(attachment.slotId);\n if (intent === undefined) {\n return [];\n }\n\n return [\n {\n byteLength: attachment.byteLength,\n contentSha256: intent.contentSha256,\n localId: attachment.localId,\n mimeType: attachment.mimeType,\n name: intent.name,\n slotId: attachment.slotId,\n storageKey: attachment.storageKey,\n },\n ];\n });\n\n return { attachmentUploads, documentUpdates };\n}\n"]}
1
+ {"version":3,"file":"remoteResetPlans.js","sourceRoot":"","sources":["remoteResetPlans.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MA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,GAAG,iBAAiB,CAAC,GAAG,CAC/B,eAAe,CAAC,kBAAkB,EAAE,OAAO,CAAC,CAC7C,CAAC;QACF,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,SAAS;QACX,CAAC;QACD,oBAAoB,CAAC,GAAG,CACtB,OAAO,EACP,IAAI,GAAG,CACL,sBAAsB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC;YAC9C,UAAU,CAAC,MAAM;YACjB,UAAU;SACX,CAAC,CACH,CACF,CAAC;IACJ,CAAC;IAED,4EAA4E;IAC5E,0EAA0E;IAC1E,6EAA6E;IAC7E,2EAA2E;IAC3E,2EAA2E;IAC3E,8EAA8E;IAC9E,yEAAyE;IACzE,MAAM,iBAAiB,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;QAC9D,MAAM,MAAM,GAAG,oBAAoB;aAChC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC;YACxB,EAAE,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QAC3B,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,OAAO;YACL;gBACE,UAAU,EAAE,UAAU,CAAC,UAAU;gBACjC,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,OAAO,EAAE,UAAU,CAAC,OAAO;gBAC3B,QAAQ,EAAE,UAAU,CAAC,QAAQ;gBAC7B,IAAI,EAAE,MAAM,CAAC,IAAI;gBACjB,MAAM,EAAE,UAAU,CAAC,MAAM;gBACzB,UAAU,EAAE,UAAU,CAAC,UAAU;aAClC;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,CAAC;AAChD,CAAC","sourcesContent":["import { createDocument, exportAllUpdates } from \"@tearleads/loro\";\nimport { and, eq, ne, or, sql } from \"drizzle-orm\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n} from \"../../data/documents\";\nimport { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport { DOCUMENTS_APP_KIND } from \"../../data/persistence/documents/documentsPersistence\";\nimport {\n documentAttachmentBlobProjection,\n documentHistoryCheckpoints,\n documentHistoryUpdates,\n documentPendingAttachments,\n documents,\n} from \"../../data/sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport { importDocumentHistoryTailUpdates } from \"../documents\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\n\nexport interface ResetDocumentUpdate {\n readonly appKind: string;\n readonly localId: string;\n readonly updateData: string;\n readonly partialStartVersionVector: string;\n readonly partialEndVersionVector: string;\n readonly sourceVersionVector: string | null;\n}\n\nexport interface ResetAttachmentUpload {\n readonly byteLength: number;\n readonly contentSha256: string;\n readonly localId: string;\n readonly mimeType: string | null;\n readonly name: string;\n readonly slotId: string;\n readonly storageKey: string;\n}\n\ntype ResetContentDoc = Awaited<ReturnType<typeof createDocument>>;\n\nfunction historyScopeKey(appKind: string, localId: string): string {\n return `${appKind} ${localId}`;\n}\n\nfunction attachmentScopeKey(localId: string, slotId: string): string {\n return `${localId}\\0${slotId}`;\n}\n\nfunction buildResetUpdate(input: {\n appKind: string;\n doc: ResetContentDoc;\n localId: string;\n}): ResetDocumentUpdate | null {\n const fields = createPendingUpdateFields(exportAllUpdates(input.doc));\n if (!fields) {\n return null;\n }\n\n return {\n appKind: input.appKind,\n localId: input.localId,\n updateData: fields.updateData,\n partialStartVersionVector: fields.partialStartVersionVector,\n partialEndVersionVector: fields.partialEndVersionVector,\n sourceVersionVector: fields.sourceVersionVector ?? null,\n };\n}\n\ninterface ResetHistoryRows {\n checkpointRows: Array<{\n appKind: string;\n localId: string;\n snapshot: string;\n }>;\n tailRows: Array<{\n appKind: string;\n localId: string;\n updateData: string;\n }>;\n}\n\nasync function loadResetHistoryRows(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<ResetHistoryRows> {\n const rows: ResetHistoryRows = { checkpointRows: [], tailRows: [] };\n const scopes = documentScopes\n ? [\n ...new Map(\n documentScopes.map((scope) => [\n historyScopeKey(scope.appKind, scope.localId),\n scope,\n ]),\n ).values(),\n ]\n : null;\n for (const scopeBatch of scopes ? remoteResetBatches(scopes) : [null]) {\n // An outbox row only waits to be sent; the content lives in the\n // checkpoint and tail rows (see `documentHistoryUpdates`).\n const notOutbox = ne(documentHistoryUpdates.origin, \"outbox\");\n const scopeTail = scopeBatch\n ? and(\n notOutbox,\n or(\n ...scopeBatch.map((scope) =>\n and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n ),\n ),\n ),\n )\n : notOutbox;\n const scopeCheckpoints = scopeBatch\n ? or(\n ...scopeBatch.map((scope) =>\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n ),\n )\n : undefined;\n const tailBatch = await db\n .select({\n appKind: documentHistoryUpdates.appKind,\n localId: documentHistoryUpdates.localId,\n updateData: documentHistoryUpdates.updateData,\n })\n .from(documentHistoryUpdates)\n .where(scopeTail)\n .orderBy(sql`rowid`);\n const checkpointBatch = await db\n .select({\n appKind: documentHistoryCheckpoints.appKind,\n localId: documentHistoryCheckpoints.localId,\n snapshot: documentHistoryCheckpoints.snapshot,\n })\n .from(documentHistoryCheckpoints)\n .where(scopeCheckpoints);\n rows.tailRows.push(...tailBatch);\n rows.checkpointRows.push(...checkpointBatch);\n }\n return rows;\n}\n\n/**\n * Reconstruct every persisted document's content from the durable-history\n * tables (checkpoint + tail) — the only content source. A scope without a\n * checkpoint (a discovered shell that never hydrated) gets no doc: it has no\n * content to republish and no attachments to requeue. The mode-sniffing tail\n * import handles both content kinds — full-history snapshots (documents) and\n * exported-updates blobs (container metadata).\n */\nasync function buildResetContentDocs(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<Map<string, ResetContentDoc>> {\n // Read the TAIL before the checkpoints (the same order the restore path\n // uses): a compaction landing between the two reads then yields old-tail +\n // new-checkpoint — a safe superset, since replay is idempotent by op\n // identity — whereas the reverse order could yield an old checkpoint plus\n // an already-emptied tail and republish stale content.\n const { checkpointRows, tailRows } = await loadResetHistoryRows(\n db,\n documentScopes,\n );\n\n const tailByScope = new Map<string, string[]>();\n for (const row of tailRows) {\n const key = historyScopeKey(row.appKind, row.localId);\n const tail = tailByScope.get(key);\n if (tail) {\n tail.push(row.updateData);\n } else {\n tailByScope.set(key, [row.updateData]);\n }\n }\n\n // Rebuild the UNION of checkpoint and tail scopes: a tail-only scope (a\n // crash landed the first edit's tail row before the birth checkpoint) may\n // hold the only durable copy of that edit, and dropping it from the reset\n // would discard it.\n const checkpointByScope = new Map(\n checkpointRows.map((row) => [\n historyScopeKey(row.appKind, row.localId),\n row,\n ]),\n );\n const historyScopes = new Map<string, { appKind: string; localId: string }>();\n for (const row of [...checkpointRows, ...tailRows]) {\n historyScopes.set(historyScopeKey(row.appKind, row.localId), {\n appKind: row.appKind,\n localId: row.localId,\n });\n }\n\n const contentDocByScope = new Map<string, ResetContentDoc>();\n await Promise.all(\n [...historyScopes.entries()].map(async ([key, scope]) => {\n const doc = await createDocument(\n `remote-reset:${scope.appKind}:${scope.localId}`,\n );\n const checkpoint = checkpointByScope.get(key);\n // An empty checkpoint blob (e.g. container metadata saved before any\n // update existed) carries no ops — importing it would throw and fail\n // the whole reset.\n importDocumentHistoryTailUpdates(\n doc,\n [\n ...(checkpoint ? [checkpoint.snapshot] : []),\n ...(tailByScope.get(key) ?? []),\n ].filter((blob) => blob.length > 0),\n );\n contentDocByScope.set(key, doc);\n }),\n );\n return contentDocByScope;\n}\n\nexport interface ResetDocumentScope {\n readonly appKind: string;\n readonly localId: string;\n}\n\nasync function loadResetPlanRows(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n) {\n const selectedScopeKeys = documentScopes\n ? new Set(\n documentScopes.map((scope) =>\n historyScopeKey(scope.appKind, scope.localId),\n ),\n )\n : null;\n const allDocumentRows = await db\n .select({ appKind: documents.appKind, localId: documents.localId })\n .from(documents);\n const documentRows = selectedScopeKeys\n ? allDocumentRows.filter((row) =>\n selectedScopeKeys.has(historyScopeKey(row.appKind, row.localId)),\n )\n : allDocumentRows;\n const [allAttachmentRows, pendingAttachmentRows] = await Promise.all([\n db\n .select({\n byteLength: documentAttachmentBlobProjection.byteLength,\n localId: documentAttachmentBlobProjection.localId,\n mimeType: documentAttachmentBlobProjection.mimeType,\n slotId: documentAttachmentBlobProjection.slotId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n })\n .from(documentAttachmentBlobProjection),\n db\n .select({\n byteLength: documentPendingAttachments.byteLength,\n localId: documentPendingAttachments.localId,\n mimeType: documentPendingAttachments.mimeType,\n slotId: documentPendingAttachments.slotId,\n storageKey: documentPendingAttachments.storageKey,\n })\n .from(documentPendingAttachments),\n ]);\n const selectedDocumentLocalIds = new Set(\n documentRows\n .filter((row) => row.appKind === DOCUMENTS_APP_KIND)\n .map((row) => row.localId),\n );\n const attachmentRows = new Map(\n allAttachmentRows\n .filter((row) => selectedDocumentLocalIds.has(row.localId))\n .map((row) => [attachmentScopeKey(row.localId, row.slotId), row]),\n );\n for (const row of pendingAttachmentRows) {\n if (selectedDocumentLocalIds.has(row.localId)) {\n attachmentRows.set(attachmentScopeKey(row.localId, row.slotId), row);\n }\n }\n return {\n attachmentRows: [...attachmentRows.values()],\n documentRows,\n };\n}\n\nexport async function buildResetPlans(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<{\n readonly attachmentUploads: ResetAttachmentUpload[];\n readonly documentUpdates: ResetDocumentUpdate[];\n}> {\n const { attachmentRows, documentRows } = await loadResetPlanRows(\n db,\n documentScopes,\n );\n const contentDocByScope = await buildResetContentDocs(db, documentScopes);\n const documentUpdates = documentRows.flatMap((row) => {\n const doc = contentDocByScope.get(\n historyScopeKey(row.appKind, row.localId),\n );\n if (!doc) {\n return [];\n }\n const update = buildResetUpdate({\n appKind: row.appKind,\n doc,\n localId: row.localId,\n });\n return update ? [update] : [];\n });\n const attachmentIntentMaps = new Map<\n string,\n Map<string, DocumentAttachment>\n >();\n const attachmentLocalIds = [\n ...new Set(attachmentRows.map((attachment) => attachment.localId)),\n ];\n for (const localId of attachmentLocalIds) {\n const doc = contentDocByScope.get(\n historyScopeKey(DOCUMENTS_APP_KIND, localId),\n );\n if (!doc) {\n continue;\n }\n attachmentIntentMaps.set(\n localId,\n new Map(\n getDocumentAttachments(doc).map((attachment) => [\n attachment.slotId,\n attachment,\n ]),\n ),\n );\n }\n\n // A reset re-uploads the local attachments as pending work, and the durable\n // document decides which rows those are: a row whose slot the snapshot no\n // longer advertises belongs to an unlink, and re-queueing it would resurrect\n // an attachment the document dropped. Reading the snapshot rather than the\n // detach marker keeps the two halves of an interrupted unlink consistent —\n // there the marker is set but the snapshot still advertises the slot, and the\n // reset has to upload it to match the document it is about to republish.\n const attachmentUploads = attachmentRows.flatMap((attachment) => {\n const intent = attachmentIntentMaps\n .get(attachment.localId)\n ?.get(attachment.slotId);\n if (intent === undefined) {\n return [];\n }\n\n return [\n {\n byteLength: attachment.byteLength,\n contentSha256: intent.contentSha256,\n localId: attachment.localId,\n mimeType: attachment.mimeType,\n name: intent.name,\n slotId: attachment.slotId,\n storageKey: attachment.storageKey,\n },\n ];\n });\n\n return { attachmentUploads, documentUpdates };\n}\n"]}
@@ -1 +0,0 @@
1
- export declare const DOCUMENTS_APP_KIND = "documents";