@tearleads/client-sdk 0.1.75 → 0.1.77

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 (164) hide show
  1. package/data/containers/shared/mutationAcknowledgement.d.ts +38 -0
  2. package/data/{containers → persistence/container-contents}/containerBinding.js +1 -1
  3. package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
  4. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  5. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -2
  6. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  7. package/data/persistence/container-contents/containerDeletionPersistence.js +2 -2
  8. package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
  9. package/data/persistence/container-contents/containerHydrationPersistence.js +2 -2
  10. package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
  11. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +2 -2
  12. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  13. package/data/persistence/container-contents/containerMetadataRows.js +1 -1
  14. package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
  15. package/data/persistence/container-contents/containerRebindPersistence.js.map +1 -1
  16. package/data/persistence/container-contents/containerReconcilePersistence.js +2 -2
  17. package/data/persistence/container-contents/containerReconcilePersistence.js.map +1 -1
  18. package/data/persistence/container-contents/containerStructuralRepair.js +1 -1
  19. package/data/persistence/container-contents/containerStructuralRepair.js.map +1 -1
  20. package/data/persistence/container-contents/dormantMetadataSweep.js +1 -1
  21. package/data/persistence/container-contents/dormantMetadataSweep.js.map +1 -1
  22. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  23. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js.map +1 -1
  24. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  25. package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
  26. package/data/persistence/documents/internal/discoveredDocumentPlacement.js +1 -1
  27. package/data/persistence/documents/internal/discoveredDocumentPlacement.js.map +1 -1
  28. package/data/principals/currentPolicyReferenceResolver.d.ts +3 -0
  29. package/index.d.ts +2 -2
  30. package/index.js +2 -2
  31. package/index.js.map +1 -1
  32. package/package.json +1 -1
  33. package/stores/container-contents/systemContainers/systemContainerIcon.js +1 -1
  34. package/stores/container-contents/systemContainers/systemContainerIcon.js.map +1 -1
  35. package/workflows/container-contents/container-state/create/createChild.js +1 -1
  36. package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
  37. package/workflows/container-contents/container-state/purge/purgeTree.js +1 -1
  38. package/workflows/container-contents/container-state/purge/purgeTree.js.map +1 -1
  39. package/workflows/container-contents/container-state/remote.js +1 -1
  40. package/workflows/container-contents/container-state/remote.js.map +1 -1
  41. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -1
  42. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  43. package/workflows/container-contents/container-state/share/groupShareEpoch.js +1 -1
  44. package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -1
  45. package/workflows/container-contents/container-state/types.js.map +1 -1
  46. package/workflows/container-contents/containerPersistence.d.ts +3 -3
  47. package/workflows/container-contents/containerPersistence.js +1 -1
  48. package/workflows/container-contents/containerPersistence.js.map +1 -1
  49. package/workflows/container-contents/documentLinks/documentLinkIntent.js +1 -1
  50. package/workflows/container-contents/documentLinks/documentLinkIntent.js.map +1 -1
  51. package/workflows/container-contents/documentLinks/index.js +1 -1
  52. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  53. package/workflows/container-contents/documentMove/documentMoveIntent.js +1 -1
  54. package/workflows/container-contents/documentMove/documentMoveIntent.js.map +1 -1
  55. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js +2 -2
  56. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js.map +1 -1
  57. package/workflows/container-contents/documentQueries/documentSubtreeQueries.js +1 -1
  58. package/workflows/container-contents/documentQueries/documentSubtreeQueries.js.map +1 -1
  59. package/workflows/container-contents/documentQueries/index.js +3 -3
  60. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  61. package/workflows/container-contents/documentQueries/pendingDownloads.js +1 -1
  62. package/workflows/container-contents/documentQueries/pendingDownloads.js.map +1 -1
  63. package/workflows/container-contents/index.d.ts +1 -1
  64. package/workflows/container-contents/index.js +1 -1
  65. package/workflows/container-contents/index.js.map +1 -1
  66. package/workflows/container-contents/info/blobInfo.js +1 -1
  67. package/workflows/container-contents/info/blobInfo.js.map +1 -1
  68. package/workflows/container-contents/info/containerInfo.js +2 -2
  69. package/workflows/container-contents/info/containerInfo.js.map +1 -1
  70. package/{data/containers → workflows/container-contents/metadata}/containerMetadataDocument.d.ts +1 -1
  71. package/{data/containers → workflows/container-contents/metadata}/containerMetadataDocument.js +2 -2
  72. package/workflows/container-contents/metadata/containerMetadataDocument.js.map +1 -0
  73. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  74. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  75. package/workflows/container-contents/metadata/metadataPersistence.js +1 -1
  76. package/workflows/container-contents/metadata/metadataPersistence.js.map +1 -1
  77. package/workflows/container-contents/metadata/metadataRecord.js.map +1 -1
  78. package/workflows/container-contents/metadata/metadataStateIsolation.js +1 -1
  79. package/workflows/container-contents/metadata/metadataStateIsolation.js.map +1 -1
  80. package/workflows/container-contents/metadata/metadataSyncSettlement.js +1 -1
  81. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  82. package/workflows/container-contents/metadata/metadataTypes.d.ts +2 -2
  83. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  84. package/workflows/container-contents/recovery/folderRecovery.js +1 -1
  85. package/workflows/container-contents/recovery/folderRecovery.js.map +1 -1
  86. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
  87. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
  88. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -1
  89. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  90. package/workflows/container-contents/remoteHydration/heldContainerRebind.js +1 -1
  91. package/workflows/container-contents/remoteHydration/heldContainerRebind.js.map +1 -1
  92. package/workflows/container-contents/remoteHydration/reattachMetadata.js +1 -1
  93. package/workflows/container-contents/remoteHydration/reattachMetadata.js.map +1 -1
  94. package/workflows/container-contents/remoteHydration/remoteContainers/insertRemoteContainer.js +2 -2
  95. package/workflows/container-contents/remoteHydration/remoteContainers/insertRemoteContainer.js.map +1 -1
  96. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +1 -1
  97. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  98. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  99. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  100. package/workflows/container-contents/storedContainerState.js +1 -1
  101. package/workflows/container-contents/storedContainerState.js.map +1 -1
  102. package/workflows/containers/child/mutationSubmit.d.ts +76 -0
  103. package/workflows/containers/child/rekey/carriedDescendantRekeys.d.ts +70 -0
  104. package/workflows/containers/child/share/index.d.ts +1 -38
  105. package/workflows/containers/child/share/index.js +1 -205
  106. package/workflows/containers/child/share/index.js.map +1 -1
  107. package/workflows/containers/child/share/shareAncestorRepair.d.ts +37 -0
  108. package/workflows/containers/child/share/shareProjection.d.ts +7 -0
  109. package/workflows/containers/index.d.ts +3 -2
  110. package/workflows/containers/index.js +4 -2
  111. package/workflows/containers/index.js.map +1 -1
  112. package/workflows/organizations/currentOrganizationAuthority.d.ts +21 -0
  113. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  114. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  115. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +30 -0
  116. package/workflows/{containers/child/share → organizations/groupShare}/currentShareGrantMutation.js +6 -6
  117. package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -0
  118. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +30 -0
  119. package/workflows/{containers/child/share → organizations/groupShare}/currentSharePrincipalPolicy.js +10 -10
  120. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -0
  121. package/workflows/organizations/groupShare/index.d.ts +4 -0
  122. package/workflows/organizations/groupShare/index.js +7 -0
  123. package/workflows/organizations/groupShare/index.js.map +1 -0
  124. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.d.ts +4 -0
  125. package/workflows/{containers/child/share → organizations/groupShare}/runtimeCurrentGroupShare.js +6 -8
  126. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js.map +1 -0
  127. package/workflows/{containers/child/share → organizations/groupShare}/sharePrincipalPolicy.d.ts +9 -9
  128. package/workflows/{containers/child/share → organizations/groupShare}/sharePrincipalPolicy.js +13 -13
  129. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -0
  130. package/workflows/organizations/groupShare/shareWithGroup.d.ts +44 -0
  131. package/workflows/organizations/groupShare/shareWithGroup.js +210 -0
  132. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -0
  133. package/workflows/organizations/index.d.ts +1 -0
  134. package/workflows/organizations/index.js +1 -0
  135. package/workflows/organizations/index.js.map +1 -1
  136. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.d.ts +16 -0
  137. package/workflows/organizations/readModel/localReadModelDetails.js +1 -1
  138. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  139. package/workflows/principals/runtimePolicyRecovery.d.ts +42 -0
  140. package/workflows/registration/bootstrapRootContainer.js +1 -1
  141. package/workflows/registration/bootstrapRootContainer.js.map +1 -1
  142. package/workflows/registration/provisioningBootstrapBuilders.js +1 -1
  143. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  144. package/workflows/registration/rootMetadataBootstrap.js +1 -1
  145. package/workflows/registration/rootMetadataBootstrap.js.map +1 -1
  146. package/workflows/sync/remoteReset.js +1 -1
  147. package/workflows/sync/remoteReset.js.map +1 -1
  148. package/data/containers/containerMetadataDocument.js.map +0 -1
  149. package/workflows/containers/child/share/currentShareGrantMutation.js.map +0 -1
  150. package/workflows/containers/child/share/currentSharePrincipalPolicy.js.map +0 -1
  151. package/workflows/containers/child/share/runtimeCurrentGroupShare.js.map +0 -1
  152. package/workflows/containers/child/share/sharePrincipalPolicy.js.map +0 -1
  153. /package/data/{containers → persistence/container-contents}/containerBinding.d.ts +0 -0
  154. /package/data/{containers → persistence/container-contents}/containerBinding.js.map +0 -0
  155. /package/data/persistence/{containers → container-contents}/containerPersistence.d.ts +0 -0
  156. /package/data/persistence/{containers → container-contents}/containerPersistence.js +0 -0
  157. /package/data/persistence/{containers → container-contents}/containerPersistence.js.map +0 -0
  158. /package/data/persistence/{containers → container-contents}/containerSyncWatermarkPersistence.d.ts +0 -0
  159. /package/data/persistence/{containers → container-contents}/containerSyncWatermarkPersistence.js +0 -0
  160. /package/data/persistence/{containers → container-contents}/containerSyncWatermarkPersistence.js.map +0 -0
  161. /package/data/persistence/{containers → container-contents}/documentContainerProjectionPersistence.js +0 -0
  162. /package/data/persistence/{containers → container-contents}/documentContainerProjectionPersistence.js.map +0 -0
  163. /package/data/persistence/{containers → container-contents}/documentPlacement.js +0 -0
  164. /package/data/persistence/{containers → container-contents}/documentPlacement.js.map +0 -0
@@ -1,4 +1,4 @@
1
- import { loadContainerDisplayNamesByIds } from "../../../data/persistence/containers/containerPersistence.js";
1
+ import { loadContainerDisplayNamesByIds } from "../../../data/persistence/container-contents/containerPersistence.js";
2
2
  import { loadOrganizationGroupDisplayNames } from "../../../data/persistence/organizations/organizationGroupNamePersistence.js";
3
3
  import { loadOrganizationReadModelProjection } from "../../../data/persistence/organizations/organizationReadModelPersistence.js";
4
4
  import { loadPrincipalPolicyBundle } from "../../../data/persistence/principalPolicy/principalPolicyPersistence.js";
@@ -1 +1 @@
1
- {"version":3,"file":"localReadModelDetails.js","sourceRoot":"","sources":["localReadModelDet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C,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CACpE,CAAC;QACF,MAAM,MAAM,GAAG,MAAM,YAAY,CAC/B,KAAK,CAAC,OAAO,EACb,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;QACF,OAAO;YACL,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,IAAI;YACJ,MAAM;YACN,MAAM,EAAE;gBACN,YAAY,EAAE,MAAM,CAAC,MAAM,CACzB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CACnE;gBACD,WAAW,EAAE,MAAM,CAAC,MAAM,CACxB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAClE;aACF;SACF,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n OrganizationContainerGrantResponse,\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { loadContainerDisplayNamesByIds } from \"../../../data/persistence/containers/containerPersistence\";\nimport { loadOrganizationGroupDisplayNames } from \"../../../data/persistence/organizations/organizationGroupNamePersistence\";\nimport { loadOrganizationReadModelProjection } from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { loadPrincipalPolicyBundle } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadVerifiedOrganizationGroupRoles } from \"../../../data/principals/organizationGroupRoles\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationGroupPolicyHistory,\n buildOrganizationPolicyHistory,\n} from \"../policyHistory/policyHistoryReadModel\";\nimport type {\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationUserDetail,\n} from \"./index\";\nimport { runOrganizationPresentationRead } from \"./organizationPresentationAccessState\";\n\ninterface LocalReadModelInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\ntype PolicyPrincipalType = ReferencedPrincipalStateResponse[\"principalType\"];\n\nconst DISPLAY_NAME_BATCH_SIZE = 400;\n\nfunction uniqueContainerIds(\n grants: readonly OrganizationContainerGrantResponse[],\n): string[] {\n return [...new Set(grants.map((grant) => grant.containerId))];\n}\n\nasync function enrichGrants(\n execSql: ExecSql,\n grants: readonly OrganizationContainerGrantResponse[],\n organizationId: string,\n): Promise<OrganizationContainerGrant[]> {\n const containerIds = uniqueContainerIds(grants);\n const groupNames = await loadOrganizationGroupDisplayNames(\n execSql,\n organizationId,\n );\n const groupRoles = await loadVerifiedOrganizationGroupRoles(\n execSql,\n organizationId,\n );\n const displayNames = new Map<string, string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += DISPLAY_NAME_BATCH_SIZE\n ) {\n const batch = await loadContainerDisplayNamesByIds(\n execSql,\n containerIds.slice(index, index + DISPLAY_NAME_BATCH_SIZE),\n );\n for (const [containerId, displayName] of batch) {\n displayNames.set(containerId, displayName);\n }\n }\n return grants.map((grant) => ({\n ...grant,\n containerDisplayName: displayNames.get(grant.containerId) ?? null,\n groupName:\n grant.subjectType === \"group\"\n ? (groupRoles.get(grant.subjectId) ??\n groupNames.get(grant.subjectId) ??\n null)\n : null,\n }));\n}\n\nfunction toGroupContainer(\n grant: OrganizationContainerGrant,\n): OrganizationGroupContainer {\n return {\n accessLevel: grant.accessLevel,\n containerId: grant.containerId,\n containerDisplayName: grant.containerDisplayName,\n createdAt: grant.createdAt,\n depth: grant.depth,\n isBuiltin: grant.isBuiltin,\n metadataAccessEpoch: grant.metadataAccessEpoch,\n metadataAccessStateHash: grant.metadataAccessStateHash,\n metadataDocumentId: grant.metadataDocumentId,\n parentId: grant.parentId,\n updatedAt: grant.updatedAt,\n };\n}\n\n/**\n * The groups a user belongs to is exactly the set naming them as a member.\n *\n * This used to be a breadth-first walk over group-in-group edges. Groups\n * contain only users now, so the walk had no second level to visit.\n */\nfunction reachableGroupIds(input: {\n readonly edges: ReadonlyArray<{\n readonly groupId: string;\n readonly userId: string;\n }>;\n readonly userId: string;\n}): Set<string> {\n return new Set(\n input.edges\n .filter((edge) => edge.userId === input.userId)\n .map((edge) => edge.groupId),\n );\n}\n\nexport async function loadLocalOrganizationContainerGrants(\n input: LocalReadModelInput,\n): Promise<OrganizationContainerGrants | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n return {\n organizationId: input.organizationId,\n grants: await enrichGrants(\n input.execSql,\n projection.grants.grants,\n input.organizationId,\n ),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupContainers(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupContainers | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const groupIsInOrganization =\n input.groupId === projection.groups.memberGroupId ||\n projection.groups.groups.some(\n (group) => group.groupId === input.groupId,\n );\n if (!groupIsInOrganization) {\n return null;\n }\n const grants = projection.grants.grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n );\n return {\n organizationId: input.organizationId,\n groupId: input.groupId,\n containers: (\n await enrichGrants(input.execSql, grants, input.organizationId)\n ).map(toGroupContainer),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupPolicyHistory(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n );\n if (!projectedHead) {\n return null;\n }\n\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.groupId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)\n : null;\n },\n );\n}\n\nfunction policyBundleMatchesProjectedHead(\n bundle: PrincipalPolicyBundleResponse | null,\n projectedHead: {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n readonly stateHash: string;\n readonly version: number;\n },\n): bundle is PrincipalPolicyBundleResponse {\n const storedHead = bundle?.currentState;\n return Boolean(\n storedHead &&\n storedHead.principalType === projectedHead.principalType &&\n storedHead.principalId === projectedHead.principalId &&\n storedHead.stateHash === projectedHead.stateHash &&\n storedHead.version === projectedHead.version &&\n storedHead.keyEpoch === projectedHead.keyEpoch &&\n storedHead.keyFingerprint === projectedHead.keyFingerprint &&\n storedHead.memberCount === projectedHead.memberCount,\n );\n}\n\nexport async function loadLocalOrganizationPolicyHistory(\n input: LocalReadModelInput,\n): Promise<OrganizationPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"organization\" &&\n head.principalId === input.organizationId,\n );\n if (!projectedHead) {\n return null;\n }\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"organization\",\n input.organizationId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationPolicyHistory(bundle)\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationPolicyReference(\n input: LocalReadModelInput & {\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n },\n): Promise<ReferencedPrincipalStateResponse | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const head = projection.policyHeads.find(\n (candidate) =>\n candidate.principalType === input.principalType &&\n candidate.principalId === input.principalId,\n );\n return head\n ? {\n principalType: head.principalType,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n }\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationUserDetail(\n input: LocalReadModelInput & { readonly userId: string },\n): Promise<OrganizationUserDetail | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n const user = projection?.directory.users.find(\n (candidate) => candidate.userId === input.userId,\n );\n if (!projection?.requester || !user) {\n return null;\n }\n\n const reachable = reachableGroupIds({\n edges: projection.membershipEdges,\n userId: input.userId,\n });\n const groups = projection.groups.groups\n .filter((group) => reachable.has(group.groupId))\n .map((group) => ({ ...group, nameUnreadable: false }));\n const relevantGrants = projection.grants.grants.filter(\n (grant) =>\n (grant.subjectType === \"user\" && grant.subjectId === input.userId) ||\n (grant.subjectType === \"group\" && reachable.has(grant.subjectId)),\n );\n const grants = await enrichGrants(\n input.execSql,\n relevantGrants,\n input.organizationId,\n );\n return {\n organizationId: input.organizationId,\n user,\n groups,\n grants: {\n directGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"user\" && grant.subjectId === input.userId,\n ),\n groupGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && reachable.has(grant.subjectId),\n ),\n },\n };\n },\n );\n}\n"]}
1
+ {"version":3,"file":"localReadModelDetails.js","sourceRoot":"","sources":["localReadModelDetails.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,8BAA8B,EAAE,MAAM,mEAAmE,CAAC;AACnH,OAAO,EAAE,iCAAiC,EAAE,MAAM,0EAA0E,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAAE,MAAM,0EAA0E,CAAC;AAC/H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sEAAsE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AAErG,OAAO,EACL,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,yCAAyC,CAAC;AAUjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAUxF,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,SAAS,kBAAkB,CACzB,MAAqD;IAErD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,KAAK,UAAU,YAAY,CACzB,OAAgB,EAChB,MAAqD,EACrD,cAAsB;IAEtB,MAAM,YAAY,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,MAAM,iCAAiC,CACxD,OAAO,EACP,cAAc,CACf,CAAC;IACF,MAAM,UAAU,GAAG,MAAM,kCAAkC,CACzD,OAAO,EACP,cAAc,CACf,CAAC;IACF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC/C,KACE,IAAI,KAAK,GAAG,CAAC,EACb,KAAK,GAAG,YAAY,CAAC,MAAM,EAC3B,KAAK,IAAI,uB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AM,cAAc,GAAG,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CACpD,CAAC,KAAK,EAAE,EAAE,CACR,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CAAC;YAClE,CAAC,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CACpE,CAAC;QACF,MAAM,MAAM,GAAG,MAAM,YAAY,CAC/B,KAAK,CAAC,OAAO,EACb,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;QACF,OAAO;YACL,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,IAAI;YACJ,MAAM;YACN,MAAM,EAAE;gBACN,YAAY,EAAE,MAAM,CAAC,MAAM,CACzB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CACnE;gBACD,WAAW,EAAE,MAAM,CAAC,MAAM,CACxB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAClE;aACF;SACF,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n OrganizationContainerGrantResponse,\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { loadContainerDisplayNamesByIds } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { loadOrganizationGroupDisplayNames } from \"../../../data/persistence/organizations/organizationGroupNamePersistence\";\nimport { loadOrganizationReadModelProjection } from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { loadPrincipalPolicyBundle } from \"../../../data/persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadVerifiedOrganizationGroupRoles } from \"../../../data/principals/organizationGroupRoles\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationGroupPolicyHistory,\n buildOrganizationPolicyHistory,\n} from \"../policyHistory/policyHistoryReadModel\";\nimport type {\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationUserDetail,\n} from \"./index\";\nimport { runOrganizationPresentationRead } from \"./organizationPresentationAccessState\";\n\ninterface LocalReadModelInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\ntype PolicyPrincipalType = ReferencedPrincipalStateResponse[\"principalType\"];\n\nconst DISPLAY_NAME_BATCH_SIZE = 400;\n\nfunction uniqueContainerIds(\n grants: readonly OrganizationContainerGrantResponse[],\n): string[] {\n return [...new Set(grants.map((grant) => grant.containerId))];\n}\n\nasync function enrichGrants(\n execSql: ExecSql,\n grants: readonly OrganizationContainerGrantResponse[],\n organizationId: string,\n): Promise<OrganizationContainerGrant[]> {\n const containerIds = uniqueContainerIds(grants);\n const groupNames = await loadOrganizationGroupDisplayNames(\n execSql,\n organizationId,\n );\n const groupRoles = await loadVerifiedOrganizationGroupRoles(\n execSql,\n organizationId,\n );\n const displayNames = new Map<string, string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += DISPLAY_NAME_BATCH_SIZE\n ) {\n const batch = await loadContainerDisplayNamesByIds(\n execSql,\n containerIds.slice(index, index + DISPLAY_NAME_BATCH_SIZE),\n );\n for (const [containerId, displayName] of batch) {\n displayNames.set(containerId, displayName);\n }\n }\n return grants.map((grant) => ({\n ...grant,\n containerDisplayName: displayNames.get(grant.containerId) ?? null,\n groupName:\n grant.subjectType === \"group\"\n ? (groupRoles.get(grant.subjectId) ??\n groupNames.get(grant.subjectId) ??\n null)\n : null,\n }));\n}\n\nfunction toGroupContainer(\n grant: OrganizationContainerGrant,\n): OrganizationGroupContainer {\n return {\n accessLevel: grant.accessLevel,\n containerId: grant.containerId,\n containerDisplayName: grant.containerDisplayName,\n createdAt: grant.createdAt,\n depth: grant.depth,\n isBuiltin: grant.isBuiltin,\n metadataAccessEpoch: grant.metadataAccessEpoch,\n metadataAccessStateHash: grant.metadataAccessStateHash,\n metadataDocumentId: grant.metadataDocumentId,\n parentId: grant.parentId,\n updatedAt: grant.updatedAt,\n };\n}\n\n/**\n * The groups a user belongs to is exactly the set naming them as a member.\n *\n * This used to be a breadth-first walk over group-in-group edges. Groups\n * contain only users now, so the walk had no second level to visit.\n */\nfunction reachableGroupIds(input: {\n readonly edges: ReadonlyArray<{\n readonly groupId: string;\n readonly userId: string;\n }>;\n readonly userId: string;\n}): Set<string> {\n return new Set(\n input.edges\n .filter((edge) => edge.userId === input.userId)\n .map((edge) => edge.groupId),\n );\n}\n\nexport async function loadLocalOrganizationContainerGrants(\n input: LocalReadModelInput,\n): Promise<OrganizationContainerGrants | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n return {\n organizationId: input.organizationId,\n grants: await enrichGrants(\n input.execSql,\n projection.grants.grants,\n input.organizationId,\n ),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupContainers(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupContainers | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const groupIsInOrganization =\n input.groupId === projection.groups.memberGroupId ||\n projection.groups.groups.some(\n (group) => group.groupId === input.groupId,\n );\n if (!groupIsInOrganization) {\n return null;\n }\n const grants = projection.grants.grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n );\n return {\n organizationId: input.organizationId,\n groupId: input.groupId,\n containers: (\n await enrichGrants(input.execSql, grants, input.organizationId)\n ).map(toGroupContainer),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupPolicyHistory(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n );\n if (!projectedHead) {\n return null;\n }\n\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.groupId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)\n : null;\n },\n );\n}\n\nfunction policyBundleMatchesProjectedHead(\n bundle: PrincipalPolicyBundleResponse | null,\n projectedHead: {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n readonly stateHash: string;\n readonly version: number;\n },\n): bundle is PrincipalPolicyBundleResponse {\n const storedHead = bundle?.currentState;\n return Boolean(\n storedHead &&\n storedHead.principalType === projectedHead.principalType &&\n storedHead.principalId === projectedHead.principalId &&\n storedHead.stateHash === projectedHead.stateHash &&\n storedHead.version === projectedHead.version &&\n storedHead.keyEpoch === projectedHead.keyEpoch &&\n storedHead.keyFingerprint === projectedHead.keyFingerprint &&\n storedHead.memberCount === projectedHead.memberCount,\n );\n}\n\nexport async function loadLocalOrganizationPolicyHistory(\n input: LocalReadModelInput,\n): Promise<OrganizationPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"organization\" &&\n head.principalId === input.organizationId,\n );\n if (!projectedHead) {\n return null;\n }\n const bundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"organization\",\n input.organizationId,\n );\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationPolicyHistory(bundle)\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationPolicyReference(\n input: LocalReadModelInput & {\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n },\n): Promise<ReferencedPrincipalStateResponse | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const head = projection.policyHeads.find(\n (candidate) =>\n candidate.principalType === input.principalType &&\n candidate.principalId === input.principalId,\n );\n return head\n ? {\n principalType: head.principalType,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n }\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationUserDetail(\n input: LocalReadModelInput & { readonly userId: string },\n): Promise<OrganizationUserDetail | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n const user = projection?.directory.users.find(\n (candidate) => candidate.userId === input.userId,\n );\n if (!projection?.requester || !user) {\n return null;\n }\n\n const reachable = reachableGroupIds({\n edges: projection.membershipEdges,\n userId: input.userId,\n });\n const groups = projection.groups.groups\n .filter((group) => reachable.has(group.groupId))\n .map((group) => ({ ...group, nameUnreadable: false }));\n const relevantGrants = projection.grants.grants.filter(\n (grant) =>\n (grant.subjectType === \"user\" && grant.subjectId === input.userId) ||\n (grant.subjectType === \"group\" && reachable.has(grant.subjectId)),\n );\n const grants = await enrichGrants(\n input.execSql,\n relevantGrants,\n input.organizationId,\n );\n return {\n organizationId: input.organizationId,\n user,\n groups,\n grants: {\n directGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"user\" && grant.subjectId === input.userId,\n ),\n groupGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && reachable.has(grant.subjectId),\n ),\n },\n };\n },\n );\n}\n"]}
@@ -0,0 +1,42 @@
1
+ import type { PrincipalPolicyPageCurrent } from "../../internal/api-client/index.js";
2
+ import { type PrincipalPolicyResolveRequest, type ReferencedPrincipalPolicyWarmer, type ResolvedPrincipalPolicyEvidence } from "../../data/keyingProjectionVerification/types.js";
3
+ import type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
4
+ import type { SecurityIncidentReporter } from "../../data/shared/securityIncidents.js";
5
+ import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
6
+ import type { TrustedUserIdentityResolver } from "../../data/trustedUserIdentity/index.js";
7
+ import type { RecoveredPrincipalHistoryPage } from "./historyRecovery/loadRecoveredPrincipalHistoryPage.js";
8
+ import { type PrincipalPolicyHistoryReader } from "./principalPolicyHistoryReader.js";
9
+ export interface PrincipalPolicyRecoveryRuntime {
10
+ readonly apiClient: Partial<PrincipalPolicyHistoryReader>;
11
+ readonly infra: {
12
+ readonly execSql: ExecSql;
13
+ };
14
+ readonly state?: {
15
+ readonly online: boolean;
16
+ } | undefined;
17
+ readonly util: {
18
+ readonly reportSecurityIncident: SecurityIncidentReporter;
19
+ };
20
+ readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
21
+ readonly withPrincipalHistoryProtection?: PrincipalHistoryProtectionLease | undefined;
22
+ }
23
+ /** Keep the private recovery key inside its runtime lease while resolving cited evidence. */
24
+ export declare function createRuntimePrincipalPolicyResolver(runtime: PrincipalPolicyRecoveryRuntime, options?: {
25
+ readonly preferLocalCurrent?: boolean;
26
+ }): ReferencedPrincipalPolicyWarmer["resolveReference"];
27
+ export interface ResolvedPrincipalPolicyCurrent extends ResolvedPrincipalPolicyEvidence {
28
+ readonly current: PrincipalPolicyPageCurrent;
29
+ /** Rows end at the selected reference; current/policy may describe a newer recovered head. */
30
+ readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;
31
+ }
32
+ interface PrincipalPolicyCurrentRequest extends Omit<PrincipalPolicyResolveRequest, "reference"> {
33
+ readonly reference?: PrincipalPolicyResolveRequest["reference"] | undefined;
34
+ /** A read-model caller has selected this exact signed head; not a freshness read. */
35
+ readonly preferLocalCurrent?: boolean | undefined;
36
+ readonly historyPage?: {
37
+ readonly beforeVersion?: number;
38
+ } | undefined;
39
+ }
40
+ /** Keep current artifacts with their verified evidence and private runtime lifetime. */
41
+ export declare function createRuntimePrincipalPolicyCurrentResolver(runtime: PrincipalPolicyRecoveryRuntime): ((input: PrincipalPolicyCurrentRequest) => Promise<ResolvedPrincipalPolicyCurrent>) | undefined;
42
+ export {};
@@ -1,4 +1,4 @@
1
- import { ensureContainerTables, loadContainers, saveContainer, } from "../../data/persistence/containers/containerPersistence.js";
1
+ import { ensureContainerTables, loadContainers, saveContainer, } from "../../data/persistence/container-contents/containerPersistence.js";
2
2
  import { createExecSql, runSerializedSqlMutation, } from "../../data/sqlite/sqlSchema.js";
3
3
  async function bootstrapRootContainerFromExecSql(execSql) {
4
4
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrapRootContainer.js","sourceRoot":"","sources":["bootstrapRootContainer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,aAAa,GACd,MAAM,wDAAwD,CAAC;AAChE,OAAO,EACL,aAAa,EAGb,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAOrC,KAAK,UAAU,iCAAiC,CAC9C,OAAgB;IAEhB,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC/D,MAAM,qBAAqB,CAAC,aAAa,CAAC,CAAC;QAC3C,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,aAAa,CAAC,CAAC;QACvD,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAC1B,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,QAAQ,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,UAAU,CACpE,CAAC;QAEF,IAAI,IAAI,EAAE,CAAC;YACT,OAAO;gBACL,WAAW,EAAE,IAAI,CAAC,EAAE;gBACpB,OAAO,EAAE,KAAK;aACf,CAAC;QACJ,CAAC;QAED,MAAM,WAAW,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;QACxC,MAAM,aAAa,CAAC,aAAa,EAAE;YACjC,EAAE,EAAE,WAAW;YACf,oBAAoB,EAAE,OAAO;YAC7B,cAAc,EAAE,EAAE;YAClB,QAAQ,EAAE,IAAI;YACd,kBAAkB,EAAE,IAAI;YACxB,IAAI,EAAE,GAAG;YACT,IAAI,EAAE,IAAI;SACX,CAAC,CAAC;QAEH,OAAO;YACL,WAAW;YACX,OAAO,EAAE,IAAI;SACd,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAkC;IAElC,OAAO,iCAAiC,CACtC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,CAC3D,CAAC;AACJ,CAAC","sourcesContent":["import {\n ensureContainerTables,\n loadContainers,\n saveContainer,\n} from \"../../data/persistence/containers/containerPersistence\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\n\ninterface RootContainerBootstrapResult {\n containerId: string;\n created: boolean;\n}\n\nasync function bootstrapRootContainerFromExecSql(\n execSql: ExecSql,\n): Promise<RootContainerBootstrapResult> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureContainerTables(lockedExecSql);\n const containers = await loadContainers(lockedExecSql);\n const root = containers.find(\n (container) => container.parentId === null && !container.systemSlot,\n );\n\n if (root) {\n return {\n containerId: root.id,\n created: false,\n };\n }\n\n const containerId = crypto.randomUUID();\n await saveContainer(lockedExecSql, {\n id: containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: \"\",\n parentId: null,\n metadataDocumentId: null,\n name: \"/\",\n icon: null,\n });\n\n return {\n containerId,\n created: true,\n };\n });\n}\n\nexport async function bootstrapRootContainer(\n input: ExecSql | ExecSqlClientLike,\n): Promise<RootContainerBootstrapResult> {\n return bootstrapRootContainerFromExecSql(\n typeof input === \"function\" ? input : createExecSql(input),\n );\n}\n"]}
1
+ {"version":3,"file":"bootstrapRootContainer.js","sourceRoot":"","sources":["bootstrapRootContainer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,aAAa,GACd,MAAM,gEAAgE,CAAC;AACxE,OAAO,EACL,aAAa,EAGb,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAOrC,KAAK,UAAU,iCAAiC,CAC9C,OAAgB;IAEhB,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC/D,MAAM,qBAAqB,CAAC,aAAa,CAAC,CAAC;QAC3C,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,aAAa,CAAC,CAAC;QACvD,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAC1B,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,QAAQ,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,UAAU,CACpE,CAAC;QAEF,IAAI,IAAI,EAAE,CAAC;YACT,OAAO;gBACL,WAAW,EAAE,IAAI,CAAC,EAAE;gBACpB,OAAO,EAAE,KAAK;aACf,CAAC;QACJ,CAAC;QAED,MAAM,WAAW,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;QACxC,MAAM,aAAa,CAAC,aAAa,EAAE;YACjC,EAAE,EAAE,WAAW;YACf,oBAAoB,EAAE,OAAO;YAC7B,cAAc,EAAE,EAAE;YAClB,QAAQ,EAAE,IAAI;YACd,kBAAkB,EAAE,IAAI;YACxB,IAAI,EAAE,GAAG;YACT,IAAI,EAAE,IAAI;SACX,CAAC,CAAC;QAEH,OAAO;YACL,WAAW;YACX,OAAO,EAAE,IAAI;SACd,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAkC;IAElC,OAAO,iCAAiC,CACtC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,CAC3D,CAAC;AACJ,CAAC","sourcesContent":["import {\n ensureContainerTables,\n loadContainers,\n saveContainer,\n} from \"../../data/persistence/container-contents/containerPersistence\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\n\ninterface RootContainerBootstrapResult {\n containerId: string;\n created: boolean;\n}\n\nasync function bootstrapRootContainerFromExecSql(\n execSql: ExecSql,\n): Promise<RootContainerBootstrapResult> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureContainerTables(lockedExecSql);\n const containers = await loadContainers(lockedExecSql);\n const root = containers.find(\n (container) => container.parentId === null && !container.systemSlot,\n );\n\n if (root) {\n return {\n containerId: root.id,\n created: false,\n };\n }\n\n const containerId = crypto.randomUUID();\n await saveContainer(lockedExecSql, {\n id: containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: \"\",\n parentId: null,\n metadataDocumentId: null,\n name: \"/\",\n icon: null,\n });\n\n return {\n containerId,\n created: true,\n };\n });\n}\n\nexport async function bootstrapRootContainer(\n input: ExecSql | ExecSqlClientLike,\n): Promise<RootContainerBootstrapResult> {\n return bootstrapRootContainerFromExecSql(\n typeof input === \"function\" ? input : createExecSql(input),\n );\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { base64ToBytes } from "../../internal/encoding/index.js";
2
- import { createInitializedContainerMetadataDocument } from "../../data/containers/containerMetadataDocument.js";
3
2
  import { deriveStableDocumentId } from "../../data/documents/shared/stableDocumentId.js";
3
+ import { createInitializedContainerMetadataDocument } from "../container-contents/metadata/containerMetadataDocument.js";
4
4
  import { deriveContainerSystemSlot, } from "../container-contents/systemSlot.js";
5
5
  import { buildContainerCreatePlan, childContainerWriterProjectionFromCreatePlan, } from "../containers/child/create/index.js";
6
6
  import { buildRootContainerCreatePlan, rootContainerWriterProjectionFromCreatePlan, } from "../containers/root/create.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,0CAA0C,EAAE,MAAM,iDAAiD,CAAC;AAC7G,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,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,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from \"@tearleads/validators/containerSystemSlot\";\nimport type { CreateOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport { createInitializedContainerMetadataDocument } from \"../../data/containers/containerMetadataDocument\";\nimport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\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":"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,MAAM,WAAW,GAAG,KAAK,CAAC,WAAW,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;IAC7D,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,0CAA0C,CACxE,WAAW,EACX;QACE,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,I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+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,4 +1,4 @@
1
- import { createInitializedContainerMetadataDocument } from "../../data/containers/containerMetadataDocument.js";
1
+ import { createInitializedContainerMetadataDocument } from "../container-contents/metadata/containerMetadataDocument.js";
2
2
  export async function createInitialRootMetadataBootstrap(containerId) {
3
3
  const metadataDocumentId = crypto.randomUUID();
4
4
  const { initialUpdate } = await createInitializedContainerMetadataDocument(containerId, {
@@ -1 +1 @@
1
- {"version":3,"file":"rootMetadataBootstrap.js","sourceRoot":"","sources":["rootMetadataBootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0CAA0C,EAAE,MAAM,iDAAiD,CAAC;AAO7G,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,WAAmB;IAEnB,MAAM,kBAAkB,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IAC/C,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,0CAA0C,CACxE,WAAW,EACX;QACE,IAAI,EAAE,IAAI;QACV,IAAI,EAAE,GAAG;KACV,CACF,CAAC;IAEF,OAAO;QACL,aAAa;QACb,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import { createInitializedContainerMetadataDocument } from \"../../data/containers/containerMetadataDocument\";\n\nexport interface InitialRootMetadataBootstrap {\n initialUpdate: Uint8Array;\n metadataDocumentId: string;\n}\n\nexport async function createInitialRootMetadataBootstrap(\n containerId: string,\n): Promise<InitialRootMetadataBootstrap> {\n const metadataDocumentId = crypto.randomUUID();\n const { initialUpdate } = await createInitializedContainerMetadataDocument(\n containerId,\n {\n icon: null,\n name: \"/\",\n },\n );\n\n return {\n initialUpdate,\n metadataDocumentId,\n };\n}\n"]}
1
+ {"version":3,"file":"rootMetadataBootstrap.js","sourceRoot":"","sources":["rootMetadataBootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0CAA0C,EAAE,MAAM,0DAA0D,CAAC;AAOtH,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,WAAmB;IAEnB,MAAM,kBAAkB,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IAC/C,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,0CAA0C,CACxE,WAAW,EACX;QACE,IAAI,EAAE,IAAI;QACV,IAAI,EAAE,GAAG;KACV,CACF,CAAC;IAEF,OAAO;QACL,aAAa;QACb,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import { createInitializedContainerMetadataDocument } from \"../container-contents/metadata/containerMetadataDocument\";\n\nexport interface InitialRootMetadataBootstrap {\n initialUpdate: Uint8Array;\n metadataDocumentId: string;\n}\n\nexport async function createInitialRootMetadataBootstrap(\n containerId: string,\n): Promise<InitialRootMetadataBootstrap> {\n const metadataDocumentId = crypto.randomUUID();\n const { initialUpdate } = await createInitializedContainerMetadataDocument(\n containerId,\n {\n icon: null,\n name: \"/\",\n },\n );\n\n return {\n initialUpdate,\n metadataDocumentId,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { and, eq, inArray, or } from "drizzle-orm";
2
+ import { deleteDocumentPlacementRowsByContainerIds, deleteDocumentPlacementRowsByDocumentIds, } from "../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
3
  import { recordSupersededContainerBindingsInTransaction } from "../../data/persistence/container-contents/supersededContainerBindings.js";
3
- import { deleteDocumentPlacementRowsByContainerIds, deleteDocumentPlacementRowsByDocumentIds, } from "../../data/persistence/containers/documentContainerProjectionPersistence.js";
4
4
  import { clearDocumentDiscoveryEvidenceOnRemoteReset } from "../../data/persistence/documents/documentDiscoveryReset.js";
5
5
  import { queuedUpdateRow, unqueueDocumentScopesInTransaction, } from "../../data/sqlite/documentPersistence/documentPendingUpdatePersistence.js";
6
6
  import { CLEARED_DOCUMENT_SYNC_FAILURE } from "../../data/sqlite/documentPersistence/documentSyncFailurePersistence.js";
@@ -1 +1 @@
1
- {"version":3,"file":"remoteReset.js","sourceRoot":"","sources":["remoteReset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,8CAA8C,EAAE,MAAM,uEAAuE,CAAC;AACvI,OAAO,EACL,yCAAyC,EACzC,wCAAwC,GACzC,MAAM,0EAA0E,CAAC;AAClF,OAAO,EAAE,2CAA2C,EAAE,MAAM,yDAA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AC1C,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,CAAC;QACD,OAAO,OAAO,CAAC,MAAM,CAAC;IACxB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport { recordSupersededContainerBindingsInTransaction } from \"../../data/persistence/container-contents/supersededContainerBindings\";\nimport {\n deleteDocumentPlacementRowsByContainerIds,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../data/persistence/containers/documentContainerProjectionPersistence\";\nimport { clearDocumentDiscoveryEvidenceOnRemoteReset } from \"../../data/persistence/documents/documentDiscoveryReset\";\nimport {\n queuedUpdateRow,\n unqueueDocumentScopesInTransaction,\n} from \"../../data/sqlite/documentPersistence/documentPendingUpdatePersistence\";\nimport { CLEARED_DOCUMENT_SYNC_FAILURE } from \"../../data/sqlite/documentPersistence/documentSyncFailurePersistence\";\nimport {\n clientSqlTables,\n containerHydrationTombstones,\n containers,\n documentAttachmentBlobProjection,\n documentHistoryUpdates,\n documentPendingAttachments,\n documentProjection,\n documents,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n inContainerIntentLanes,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../data/sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../data/sqlite/schema/documentPlacementIntentSchema\";\nimport { organizationDataUsageSnapshots } from \"../../data/sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelContainerGrants,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroupMembers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../data/sqlite/schema/organizationReadModelSchema\";\nimport { verifiedAccessManifestBundles } from \"../../data/sqlite/schema/verifiedManifestBundleSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../data/sqlite/sqlTableSchema\";\nimport { runOrganizationPresentationReset } from \"../organizations/readModel/organizationPresentationAccessState\";\nimport { clearResetPendingAttachments } from \"./remoteResetAttachments\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\nimport { clearRemoteResetSyncCursors } from \"./remoteResetCursorScope\";\nimport {\n buildResetPlans,\n type ResetAttachmentUpload,\n type ResetDocumentUpdate,\n} from \"./remoteResetPlans\";\nimport { clearRemoteResetPrincipalRows } from \"./remoteResetPrincipalScope\";\nimport {\n type RemoteResetInput,\n type RemoteSyncStateSnapshot,\n readRemoteSyncStateSnapshot,\n} from \"./remoteResetScope\";\n\nexport type {\n RemoteResetInput,\n RemoteResetReplacement,\n} from \"./remoteResetScope\";\n\nconst CONTAINER_CREATE_INTENT_TYPE = \"container.create\";\n\nexport interface ClearRemoteSyncStateResult {\n readonly clearedContainerCreateIntentCount: number;\n readonly clearedContainerMoveIntentCount: number;\n readonly clearedDocumentMoveIntentCount: number;\n readonly clearedPrincipalPolicyCount: number;\n readonly clearedSyncCursorCount: number;\n readonly queuedAttachmentUploadCount: number;\n readonly queuedContainerCreateCount: number;\n readonly queuedDocumentUpdateCount: number;\n readonly resetContainerCount: number;\n readonly resetDocumentCount: number;\n}\n\nasync function clearOrganizationPresentationRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n for (const table of [\n organizationDataUsageSnapshots,\n organizationReadModelContainerGrants,\n organizationReadModelGroupMembers,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n organizationPresentationDenials,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n}\n\ninterface ScopedRemoteRowsInput {\n attachmentUploads: readonly ResetAttachmentUpload[];\n organizationId: string;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}\n\nasync function clearScopedContainerRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n for (const containerBatch of remoteResetBatches(\n input.snapshot.containerIds,\n )) {\n await deleteDocumentPlacementRowsByContainerIds(input.tx, containerBatch);\n await input.tx\n .delete(localIntents)\n .where(\n and(\n inContainerIntentLanes(),\n inArray(localIntents.subjectId, containerBatch),\n ),\n )\n .run();\n await input.tx\n .delete(containerHydrationTombstones)\n .where(inArray(containerHydrationTombstones.containerId, containerBatch))\n .run();\n }\n}\n\nasync function clearScopedDocumentRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { snapshot, tx } = input;\n for (const documentIdBatch of remoteResetBatches(snapshot.oldDocumentIds)) {\n await deleteDocumentPlacementRowsByDocumentIds(tx, documentIdBatch);\n }\n await clearResetPendingAttachments({\n attachmentUploads: input.attachmentUploads,\n documentLocalIds: snapshot.documentLocalIds,\n tx,\n });\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n const placementIntents = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n inArray(localIntents.localId, localIdBatch),\n );\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(placementIntents),\n ),\n )\n .run();\n await tx.delete(localIntents).where(placementIntents).run();\n }\n // Sync failures clear with the document columns in resetRemoteColumns.\n for (const documentBatch of remoteResetBatches(snapshot.documentRows)) {\n await unqueueDocumentScopesInTransaction(tx, documentBatch);\n }\n}\n\nasync function clearScopedRemoteRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { organizationId, tx } = input;\n await clearOrganizationPresentationRows(tx, organizationId);\n for (const table of [\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n verifiedAccessManifestBundles,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n await clearDocumentDiscoveryEvidenceOnRemoteReset(tx, {\n containerIds: input.snapshot.containerIds,\n documentIds: input.snapshot.oldDocumentIds,\n });\n await clearRemoteResetPrincipalRows(input);\n await clearScopedContainerRows(input);\n await clearScopedDocumentRows(input);\n await clearRemoteResetSyncCursors({\n containerIds: input.snapshot.containerIds,\n tx,\n });\n}\n\nasync function resetRemoteColumns(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { now, reset, snapshot, tx } = input;\n for (const row of snapshot.documentRows) {\n await tx\n .update(documents)\n .set({\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n lastCommitLsn: null,\n pullContinuation: null,\n recoveryDocumentId: row.documentId ?? row.recoveryDocumentId,\n ...CLEARED_DOCUMENT_SYNC_FAILURE,\n updatedAt: now,\n })\n .where(\n and(\n eq(documents.appKind, row.appKind),\n eq(documents.localId, row.localId),\n ),\n )\n .run();\n }\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n await tx\n .update(documentProjection)\n .set({\n documentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n })\n .where(inArray(documentProjection.localId, localIdBatch))\n .run();\n }\n // Replacement re-homes folders under their ids; the purged organization\n // can never bind them again on this device.\n for (const containerIds of reset.replacement\n ? remoteResetBatches(snapshot.containerIds)\n : []) {\n await recordSupersededContainerBindingsInTransaction(tx, {\n containerIds,\n organizationId: reset.organizationId,\n supersededAt: now,\n });\n }\n for (const row of snapshot.containerRows) {\n await tx\n .update(containers)\n .set({\n metadataDocumentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n parentId:\n reset.replacement && row.parentId === null\n ? reset.replacement.rootContainerId\n : row.parentId,\n serverCreatedAt: null,\n serverUpdatedAt: null,\n ...(reset.replacement ? { systemSlot: null } : {}),\n localUpdatedAt: now,\n })\n .where(eq(containers.id, row.id))\n .run();\n }\n}\n\nasync function queueResetDocumentUpdates(input: {\n documentUpdates: readonly ResetDocumentUpdate[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const updateBatch of remoteResetBatches(input.documentUpdates)) {\n await input.tx\n .insert(documentHistoryUpdates)\n .values(\n updateBatch.map((update) =>\n queuedUpdateRow({\n createdAt: input.now,\n origin: \"outbox\",\n pendingUpdate: update,\n scope: update,\n updateId: crypto.randomUUID(),\n }),\n ),\n )\n .run();\n }\n}\n\nasync function queueResetContainerCreates(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<number> {\n const rows = input.snapshot.containerRows.flatMap((row) => {\n const parentId =\n row.parentId ?? input.reset.replacement?.rootContainerId ?? null;\n return parentId ? [{ id: row.id, parentId }] : [];\n });\n if (rows.length === 0) return 0;\n for (const rowBatch of remoteResetBatches(rows)) {\n await input.tx\n .insert(localIntents)\n .values(\n rowBatch.map((row) => ({\n id: crypto.randomUUID(),\n lane: LOCAL_INTENT_LANES.containerCreate,\n subjectId: row.id,\n targetContainerId: row.parentId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\" as const,\n remoteContainerId: null,\n remoteMetadataAccessStateHash: null,\n remoteMetadataDocumentId: null,\n lastError: null,\n createdAt: input.now,\n updatedAt: input.now,\n })),\n )\n .run();\n }\n return rows.length;\n}\n\nasync function queueResetAttachmentUploads(input: {\n attachmentUploads: readonly ResetAttachmentUpload[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const attachmentBatch of remoteResetBatches(input.attachmentUploads)) {\n await input.tx\n .insert(documentPendingAttachments)\n .values(\n attachmentBatch.map((attachment) => ({\n ...attachment,\n createdAt: input.now,\n })),\n )\n .run();\n await input.tx\n .delete(documentAttachmentBlobProjection)\n .where(\n or(\n ...attachmentBatch.map((attachment) =>\n and(\n eq(documentAttachmentBlobProjection.localId, attachment.localId),\n eq(documentAttachmentBlobProjection.slotId, attachment.slotId),\n ),\n ),\n ),\n )\n .run();\n }\n}\n\nasync function clearRemoteSyncStateInTransaction(input: {\n plans: Awaited<ReturnType<typeof buildResetPlans>>;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<ClearRemoteSyncStateResult> {\n const now = new Date().toISOString();\n const { snapshot } = input;\n await clearScopedRemoteRows({\n attachmentUploads: input.plans.attachmentUploads,\n organizationId: input.reset.organizationId,\n snapshot,\n tx: input.tx,\n });\n await resetRemoteColumns({ now, reset: input.reset, snapshot, tx: input.tx });\n await queueResetDocumentUpdates({\n documentUpdates: input.plans.documentUpdates,\n now,\n tx: input.tx,\n });\n const queuedContainerCreateCount = await queueResetContainerCreates({\n now,\n reset: input.reset,\n snapshot,\n tx: input.tx,\n });\n await queueResetAttachmentUploads({\n attachmentUploads: input.plans.attachmentUploads,\n now,\n tx: input.tx,\n });\n return {\n clearedContainerCreateIntentCount:\n snapshot.clearedContainerCreateIntentCount,\n clearedContainerMoveIntentCount: snapshot.clearedContainerMoveIntentCount,\n clearedDocumentMoveIntentCount: snapshot.clearedDocumentMoveIntentCount,\n clearedPrincipalPolicyCount: snapshot.clearedPrincipalPolicyCount,\n clearedSyncCursorCount: snapshot.clearedSyncCursorCount,\n queuedAttachmentUploadCount: input.plans.attachmentUploads.length,\n queuedContainerCreateCount,\n queuedDocumentUpdateCount: input.plans.documentUpdates.length,\n resetContainerCount: snapshot.containerRows.length,\n resetDocumentCount: snapshot.documentRows.length,\n };\n}\n\nexport async function clearRemoteSyncState(\n execSql: ExecSql,\n reset: RemoteResetInput,\n canCommit?: (() => boolean) | undefined,\n): Promise<ClearRemoteSyncStateResult> {\n return runOrganizationPresentationReset(\n execSql,\n reset.organizationId,\n async () => {\n await ensureSqlTables(execSql, clientSqlTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const resetInTransaction = async (tx: ClientSQLiteTransactionScope) => {\n if (canCommit && !canCommit()) {\n throw new Error(\n \"Remote sync reset aborted: session identity changed\",\n );\n }\n const snapshot = await readRemoteSyncStateSnapshot(\n tx,\n reset.organizationId,\n );\n const plans = await buildResetPlans(tx, snapshot.documentRows);\n return clearRemoteSyncStateInTransaction({\n plans,\n reset,\n snapshot,\n tx,\n });\n };\n if (!canCommit) {\n return runtime.transaction(resetInTransaction);\n }\n const outcome = await runtime.guardedTransaction(\n resetInTransaction,\n canCommit,\n );\n if (!outcome.committed || !outcome.result) {\n throw new Error(\"Remote sync reset aborted: session identity changed\");\n }\n return outcome.result;\n },\n );\n}\n"]}
1
+ {"version":3,"file":"remoteReset.js","sourceRoot":"","sources":["remoteReset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EACL,yCAAyC,EACzC,wCAAwC,GACzC,MAAM,kFAAkF,CAAC;AAC1F,OAAO,EAAE,8CAA8C,EAAE,MAAM,uEAAuE,CAAC;AACvI,OAAO,EAAE,2CAA2C,EAAE,MAAM,yDAAyD,CAAC;AACtH,OAAO,EACL,eAAe,EACf,kCAAkC,GACnC,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAAE,6BAA6B,EAAE,MAAM,sEAAsE,CAAC;AACrH,OAAO,EACL,eAAe,EACf,4BAA4B,EAC5B,UAAU,EACV,gCAAgC,EAChC,sBAAsB,EACtB,0BAA0B,EAC1B,kBAAkB,EAClB,SAAS,EACT,wBAAwB,EACxB,4BAA4B,EAC5B,sBAAsB,EACtB,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,yBAAyB,EAAE,MAAM,wDAAwD,CAAC;AACnG,OAAO,EAAE,8BAA8B,EAAE,MAAM,sDAAsD,CAAC;AACtG,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,mCAAmC,EACnC,iCAAiC,EACjC,2BAA2B,EAC3B,+BAA+B,EAC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;YACpE,IAAI,SAAS,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;gBAC9B,MAAM,IAAI,KAAK,CACb,qDAAqD,CACtD,CAAC;YACJ,CAAC;YACD,MAAM,QAAQ,GAAG,MAAM,2BAA2B,CAChD,EAAE,EACF,KAAK,CAAC,cAAc,CACrB,CAAC;YACF,MAAM,KAAK,GAAG,MAAM,eAAe,CAAC,EAAE,EAAE,QAAQ,CAAC,YAAY,CAAC,CAAC;YAC/D,OAAO,iCAAiC,CAAC;gBACvC,KAAK;gBACL,KAAK;gBACL,QAAQ;gBACR,EAAE;aACH,CAAC,CAAC;QACL,CAAC,CAAC;QACF,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,OAAO,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC;QACjD,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC9C,kBAAkB,EAClB,SAAS,CACV,CAAC;QACF,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,CAAC;QACD,OAAO,OAAO,CAAC,MAAM,CAAC;IACxB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport {\n deleteDocumentPlacementRowsByContainerIds,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { recordSupersededContainerBindingsInTransaction } from \"../../data/persistence/container-contents/supersededContainerBindings\";\nimport { clearDocumentDiscoveryEvidenceOnRemoteReset } from \"../../data/persistence/documents/documentDiscoveryReset\";\nimport {\n queuedUpdateRow,\n unqueueDocumentScopesInTransaction,\n} from \"../../data/sqlite/documentPersistence/documentPendingUpdatePersistence\";\nimport { CLEARED_DOCUMENT_SYNC_FAILURE } from \"../../data/sqlite/documentPersistence/documentSyncFailurePersistence\";\nimport {\n clientSqlTables,\n containerHydrationTombstones,\n containers,\n documentAttachmentBlobProjection,\n documentHistoryUpdates,\n documentPendingAttachments,\n documentProjection,\n documents,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n inContainerIntentLanes,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../data/sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../data/sqlite/schema/documentPlacementIntentSchema\";\nimport { organizationDataUsageSnapshots } from \"../../data/sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelContainerGrants,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroupMembers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../data/sqlite/schema/organizationReadModelSchema\";\nimport { verifiedAccessManifestBundles } from \"../../data/sqlite/schema/verifiedManifestBundleSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../data/sqlite/sqlTableSchema\";\nimport { runOrganizationPresentationReset } from \"../organizations/readModel/organizationPresentationAccessState\";\nimport { clearResetPendingAttachments } from \"./remoteResetAttachments\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\nimport { clearRemoteResetSyncCursors } from \"./remoteResetCursorScope\";\nimport {\n buildResetPlans,\n type ResetAttachmentUpload,\n type ResetDocumentUpdate,\n} from \"./remoteResetPlans\";\nimport { clearRemoteResetPrincipalRows } from \"./remoteResetPrincipalScope\";\nimport {\n type RemoteResetInput,\n type RemoteSyncStateSnapshot,\n readRemoteSyncStateSnapshot,\n} from \"./remoteResetScope\";\n\nexport type {\n RemoteResetInput,\n RemoteResetReplacement,\n} from \"./remoteResetScope\";\n\nconst CONTAINER_CREATE_INTENT_TYPE = \"container.create\";\n\nexport interface ClearRemoteSyncStateResult {\n readonly clearedContainerCreateIntentCount: number;\n readonly clearedContainerMoveIntentCount: number;\n readonly clearedDocumentMoveIntentCount: number;\n readonly clearedPrincipalPolicyCount: number;\n readonly clearedSyncCursorCount: number;\n readonly queuedAttachmentUploadCount: number;\n readonly queuedContainerCreateCount: number;\n readonly queuedDocumentUpdateCount: number;\n readonly resetContainerCount: number;\n readonly resetDocumentCount: number;\n}\n\nasync function clearOrganizationPresentationRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n for (const table of [\n organizationDataUsageSnapshots,\n organizationReadModelContainerGrants,\n organizationReadModelGroupMembers,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n organizationPresentationDenials,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n}\n\ninterface ScopedRemoteRowsInput {\n attachmentUploads: readonly ResetAttachmentUpload[];\n organizationId: string;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}\n\nasync function clearScopedContainerRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n for (const containerBatch of remoteResetBatches(\n input.snapshot.containerIds,\n )) {\n await deleteDocumentPlacementRowsByContainerIds(input.tx, containerBatch);\n await input.tx\n .delete(localIntents)\n .where(\n and(\n inContainerIntentLanes(),\n inArray(localIntents.subjectId, containerBatch),\n ),\n )\n .run();\n await input.tx\n .delete(containerHydrationTombstones)\n .where(inArray(containerHydrationTombstones.containerId, containerBatch))\n .run();\n }\n}\n\nasync function clearScopedDocumentRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { snapshot, tx } = input;\n for (const documentIdBatch of remoteResetBatches(snapshot.oldDocumentIds)) {\n await deleteDocumentPlacementRowsByDocumentIds(tx, documentIdBatch);\n }\n await clearResetPendingAttachments({\n attachmentUploads: input.attachmentUploads,\n documentLocalIds: snapshot.documentLocalIds,\n tx,\n });\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n const placementIntents = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n inArray(localIntents.localId, localIdBatch),\n );\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(placementIntents),\n ),\n )\n .run();\n await tx.delete(localIntents).where(placementIntents).run();\n }\n // Sync failures clear with the document columns in resetRemoteColumns.\n for (const documentBatch of remoteResetBatches(snapshot.documentRows)) {\n await unqueueDocumentScopesInTransaction(tx, documentBatch);\n }\n}\n\nasync function clearScopedRemoteRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { organizationId, tx } = input;\n await clearOrganizationPresentationRows(tx, organizationId);\n for (const table of [\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n verifiedAccessManifestBundles,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n await clearDocumentDiscoveryEvidenceOnRemoteReset(tx, {\n containerIds: input.snapshot.containerIds,\n documentIds: input.snapshot.oldDocumentIds,\n });\n await clearRemoteResetPrincipalRows(input);\n await clearScopedContainerRows(input);\n await clearScopedDocumentRows(input);\n await clearRemoteResetSyncCursors({\n containerIds: input.snapshot.containerIds,\n tx,\n });\n}\n\nasync function resetRemoteColumns(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { now, reset, snapshot, tx } = input;\n for (const row of snapshot.documentRows) {\n await tx\n .update(documents)\n .set({\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n lastCommitLsn: null,\n pullContinuation: null,\n recoveryDocumentId: row.documentId ?? row.recoveryDocumentId,\n ...CLEARED_DOCUMENT_SYNC_FAILURE,\n updatedAt: now,\n })\n .where(\n and(\n eq(documents.appKind, row.appKind),\n eq(documents.localId, row.localId),\n ),\n )\n .run();\n }\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n await tx\n .update(documentProjection)\n .set({\n documentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n })\n .where(inArray(documentProjection.localId, localIdBatch))\n .run();\n }\n // Replacement re-homes folders under their ids; the purged organization\n // can never bind them again on this device.\n for (const containerIds of reset.replacement\n ? remoteResetBatches(snapshot.containerIds)\n : []) {\n await recordSupersededContainerBindingsInTransaction(tx, {\n containerIds,\n organizationId: reset.organizationId,\n supersededAt: now,\n });\n }\n for (const row of snapshot.containerRows) {\n await tx\n .update(containers)\n .set({\n metadataDocumentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n parentId:\n reset.replacement && row.parentId === null\n ? reset.replacement.rootContainerId\n : row.parentId,\n serverCreatedAt: null,\n serverUpdatedAt: null,\n ...(reset.replacement ? { systemSlot: null } : {}),\n localUpdatedAt: now,\n })\n .where(eq(containers.id, row.id))\n .run();\n }\n}\n\nasync function queueResetDocumentUpdates(input: {\n documentUpdates: readonly ResetDocumentUpdate[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const updateBatch of remoteResetBatches(input.documentUpdates)) {\n await input.tx\n .insert(documentHistoryUpdates)\n .values(\n updateBatch.map((update) =>\n queuedUpdateRow({\n createdAt: input.now,\n origin: \"outbox\",\n pendingUpdate: update,\n scope: update,\n updateId: crypto.randomUUID(),\n }),\n ),\n )\n .run();\n }\n}\n\nasync function queueResetContainerCreates(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<number> {\n const rows = input.snapshot.containerRows.flatMap((row) => {\n const parentId =\n row.parentId ?? input.reset.replacement?.rootContainerId ?? null;\n return parentId ? [{ id: row.id, parentId }] : [];\n });\n if (rows.length === 0) return 0;\n for (const rowBatch of remoteResetBatches(rows)) {\n await input.tx\n .insert(localIntents)\n .values(\n rowBatch.map((row) => ({\n id: crypto.randomUUID(),\n lane: LOCAL_INTENT_LANES.containerCreate,\n subjectId: row.id,\n targetContainerId: row.parentId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\" as const,\n remoteContainerId: null,\n remoteMetadataAccessStateHash: null,\n remoteMetadataDocumentId: null,\n lastError: null,\n createdAt: input.now,\n updatedAt: input.now,\n })),\n )\n .run();\n }\n return rows.length;\n}\n\nasync function queueResetAttachmentUploads(input: {\n attachmentUploads: readonly ResetAttachmentUpload[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const attachmentBatch of remoteResetBatches(input.attachmentUploads)) {\n await input.tx\n .insert(documentPendingAttachments)\n .values(\n attachmentBatch.map((attachment) => ({\n ...attachment,\n createdAt: input.now,\n })),\n )\n .run();\n await input.tx\n .delete(documentAttachmentBlobProjection)\n .where(\n or(\n ...attachmentBatch.map((attachment) =>\n and(\n eq(documentAttachmentBlobProjection.localId, attachment.localId),\n eq(documentAttachmentBlobProjection.slotId, attachment.slotId),\n ),\n ),\n ),\n )\n .run();\n }\n}\n\nasync function clearRemoteSyncStateInTransaction(input: {\n plans: Awaited<ReturnType<typeof buildResetPlans>>;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<ClearRemoteSyncStateResult> {\n const now = new Date().toISOString();\n const { snapshot } = input;\n await clearScopedRemoteRows({\n attachmentUploads: input.plans.attachmentUploads,\n organizationId: input.reset.organizationId,\n snapshot,\n tx: input.tx,\n });\n await resetRemoteColumns({ now, reset: input.reset, snapshot, tx: input.tx });\n await queueResetDocumentUpdates({\n documentUpdates: input.plans.documentUpdates,\n now,\n tx: input.tx,\n });\n const queuedContainerCreateCount = await queueResetContainerCreates({\n now,\n reset: input.reset,\n snapshot,\n tx: input.tx,\n });\n await queueResetAttachmentUploads({\n attachmentUploads: input.plans.attachmentUploads,\n now,\n tx: input.tx,\n });\n return {\n clearedContainerCreateIntentCount:\n snapshot.clearedContainerCreateIntentCount,\n clearedContainerMoveIntentCount: snapshot.clearedContainerMoveIntentCount,\n clearedDocumentMoveIntentCount: snapshot.clearedDocumentMoveIntentCount,\n clearedPrincipalPolicyCount: snapshot.clearedPrincipalPolicyCount,\n clearedSyncCursorCount: snapshot.clearedSyncCursorCount,\n queuedAttachmentUploadCount: input.plans.attachmentUploads.length,\n queuedContainerCreateCount,\n queuedDocumentUpdateCount: input.plans.documentUpdates.length,\n resetContainerCount: snapshot.containerRows.length,\n resetDocumentCount: snapshot.documentRows.length,\n };\n}\n\nexport async function clearRemoteSyncState(\n execSql: ExecSql,\n reset: RemoteResetInput,\n canCommit?: (() => boolean) | undefined,\n): Promise<ClearRemoteSyncStateResult> {\n return runOrganizationPresentationReset(\n execSql,\n reset.organizationId,\n async () => {\n await ensureSqlTables(execSql, clientSqlTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const resetInTransaction = async (tx: ClientSQLiteTransactionScope) => {\n if (canCommit && !canCommit()) {\n throw new Error(\n \"Remote sync reset aborted: session identity changed\",\n );\n }\n const snapshot = await readRemoteSyncStateSnapshot(\n tx,\n reset.organizationId,\n );\n const plans = await buildResetPlans(tx, snapshot.documentRows);\n return clearRemoteSyncStateInTransaction({\n plans,\n reset,\n snapshot,\n tx,\n });\n };\n if (!canCommit) {\n return runtime.transaction(resetInTransaction);\n }\n const outcome = await runtime.guardedTransaction(\n resetInTransaction,\n canCommit,\n );\n if (!outcome.committed || !outcome.result) {\n throw new Error(\"Remote sync reset aborted: session identity changed\");\n }\n return outcome.result;\n },\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"containerMetadataDocument.js","sourceRoot":"","sources":["containerMetadataDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CA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,MAAM,QAAQ,GAAG,GAAG,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAEzC,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAEjC,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC;QACf,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QACjC,OAAO;IACT,CAAC;IAED,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import { createDocument, exportAllUpdates } from \"@tearleads/loro\";\nimport { getScopedPeerSeed } from \"../sync/crdtPeerSeed\";\n\ninterface ContainerMetadataValue {\n icon: string | null;\n name: string;\n}\n\nexport type ContainerMetadataDocument = Awaited<\n ReturnType<typeof createDocument>\n>;\n\nexport function getDefaultContainerName(parentId: string | null): string {\n return parentId === null ? \"/\" : \"Untitled\";\n}\n\nexport async function createContainerMetadataDocument(\n _containerId: string,\n): Promise<ContainerMetadataDocument> {\n // A single static scope for all container-metadata docs: they are separate\n // CRDTs, so they can share one device peer, and a per-container scope would\n // hold a distinct device-peer lock (and cache entry) per container for the\n // tab's lifetime, accumulating without bound as containers are browsed.\n return createDocument(await getScopedPeerSeed(\"container-metadata\"));\n}\n\nexport async function createInitializedContainerMetadataDocument(\n containerId: string,\n value: ContainerMetadataValue,\n): Promise<{\n doc: ContainerMetadataDocument;\n initialUpdate: Uint8Array;\n}> {\n const doc = await createContainerMetadataDocument(containerId);\n writeContainerMetadataValue(doc, value);\n\n return {\n doc,\n initialUpdate: exportAllUpdates(doc),\n };\n}\n\nexport function readContainerMetadataValue(\n doc: ContainerMetadataDocument,\n defaultName: string,\n): ContainerMetadataValue {\n const metadata = doc.getMap(\"container\");\n const storedName = metadata.get(\"name\");\n const storedIcon = metadata.get(\"icon\");\n\n return {\n icon:\n typeof storedIcon === \"string\" && storedIcon.length > 0\n ? storedIcon\n : null,\n name:\n typeof storedName === \"string\" && storedName.trim().length > 0\n ? storedName\n : defaultName,\n };\n}\n\nexport function writeContainerMetadataValue(\n doc: ContainerMetadataDocument,\n value: ContainerMetadataValue,\n): void {\n const metadata = doc.getMap(\"container\");\n\n metadata.set(\"name\", value.name);\n\n if (value.icon) {\n metadata.set(\"icon\", value.icon);\n return;\n }\n\n metadata.delete(\"icon\");\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"currentShareGrantMutation.js","sourceRoot":"","sources":["currentShareGrantMutation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,qDAAqD,CAAC;AAC1G,OAAO,EAAE,gCAAgC,EAAE,MAAM,2DAA2D,CAAC;AAC7G,OAAO,EAAE,gCAAgC,EAAE,MAAM,qEAAqE,CAAC;AACvH,OAAO,EAAE,wCAAwC,EAAE,MAAM,wDAAwD,CAAC;AAKlH,OAAO,EAAE,uBAAuB,EAAE,MAAM,+DAA+D,CAAC;AACxG,OAAO,EAEL,+CAA+C,GAChD,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAErE,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,KAS7C;IACC,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IAC1B,MAAM,YAAY,GAAG,KAAK,CAAC,iBAAiB,CAAC;IAC7C,IAAI,YAAY,KAAK,IAAI;QACvB,MAAM,IAAI,KAAK,CACb,8GAA8G,CAC/G,CAAC;IACJ,MAAM,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAC5C,IAAI,CAAC,cAAc;QACjB,MAAM,IAAI,KAAK,CACb,iEAAiE,CAClE,CAAC;IACJ,OAAO,KAAK,CAAC,MAAM,CACjB;QACE,OAAO,EAAE,KAAK,CAAC,gBAAgB;QAC/B,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;QAC3C,YAAY,EAAE,KAAK,CAAC,MAAM,C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O,CAAC,aAAa,CAAC,aAAa,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,CAChE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,CAAU,CAC/C,CACF,CAAC,MAAM,EAAE;SACX;QACD,OAAO,EAAE,KAAK,CAAC,gBAAgB;QAC/B,UAAU;QACV,+BAA+B,EAAE,OAAO,CAAC,+BAA+B;QACxE,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,sBAAsB;KACvB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { MaterializedContainerSharePlan } from \"../../../../data/containers/shared/types\";\nimport { assertProjectionVerificationCurrent } from \"../../../../data/keyingProjectionVerification/types\";\nimport { createRuntimeGroupMetadataAccess } from \"../../../organizations/groupMetadata/groupMetadataRuntime\";\nimport { commitCurrentGroupPolicyMutation } from \"../../../organizations/groupPolicy/commitCurrentGroupPolicyMutation\";\nimport { buildSetGroupContainerGrantPolicyRequest } from \"../../../organizations/groupPolicy/groupPolicyRequests\";\nimport type {\n createRuntimeCurrentGroupMutation,\n RuntimeCurrentGroupMutationContext,\n} from \"../../../organizations/principalMutations/runtimeCurrentGroupMutation\";\nimport { groupPolicyNameMismatch } from \"../../../organizations/principalPolicy/principalPolicyRequest\";\nimport {\n type PreparedPrincipalContainerRematerializationBatch,\n preparePrincipalContainerRematerializationBatch,\n} from \"../../rematerialization\";\nimport type { createRuntimeCurrentSharePrincipalPolicy } from \"./currentSharePrincipalPolicy\";\nimport type { shareRemoteContainerWithGroup } from \"./index\";\nimport { GroupShareNameMismatchError } from \"./sharePrincipalPolicy\";\n\n/** Fresh mutation authority rechecks the chosen name before authoring a grant. */\nexport async function commitCurrentShareGrant(input: {\n readonly runtime: Parameters<\n typeof createRuntimeCurrentSharePrincipalPolicy\n >[0];\n readonly share: Parameters<typeof shareRemoteContainerWithGroup>[0];\n readonly recitationStillCurrent?: (() => boolean) | undefined;\n readonly mutate: NonNullable<\n ReturnType<typeof createRuntimeCurrentGroupMutation>\n >;\n}): ReturnType<typeof shareRemoteContainerWithGroup> {\n const share = input.share;\n const expectedName = share.expectedGroupName;\n if (expectedName === null)\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n const signingKeyPair = share.signingKeyPair;\n if (!signingKeyPair)\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n return input.mutate(\n {\n groupId: share.recipientGroupId,\n organizationId: share.author.organizationId,\n signerUserId: share.author.signerUserId,\n stillCurrent: share.stillCurrent ?? (() => true),\n },\n async (context) => {\n await assertCurrentShareGrantName(\n input.runtime,\n share,\n context,\n expectedName,\n );\n const request = await buildSetGroupContainerGrantPolicyRequest({\n ...context,\n accessLevel: share.accessLevel,\n containerId: share.containerId,\n signerUserId: share.author.signerUserId,\n signingFingerprint: share.author.signerKeyFingerprint,\n signingKeyPair,\n });\n const prepared: {\n batch?: PreparedPrincipalContainerRematerializationBatch;\n } = {};\n const response = await commitCurrentGroupPolicyMutation({\n apiClient: share.apiClient,\n context,\n groupId: share.recipientGroupId,\n organizationId: share.author.organizationId,\n request,\n signerUserId: share.author.signerUserId,\n signingFingerprint: share.author.signerKeyFingerprint,\n signingKeyPair,\n resolveTrustedUserIdentity: share.resolveTrustedUserIdentity,\n prepareContainerMutations: async (nextPolicy) => {\n prepared.batch = await prepareCurrentShareGrantBatch(\n share,\n context,\n nextPolicy,\n input.recitationStillCurrent,\n );\n return prepared.batch;\n },\n });\n const index =\n prepared.batch?.plans.findIndex(\n (planned) => planned.plan.containerId === share.containerId,\n ) ?? -1;\n const plan = prepared.batch?.plans[index];\n const acknowledgement = response.containerMutations[index];\n if (!plan || !acknowledgement || !isSharePlan(plan))\n throw new Error(\"Container group share acknowledgement is incomplete\");\n return {\n containerKey: plan.containerKey,\n plan: plan.plan,\n response: acknowledgement,\n };\n },\n );\n}\n\nfunction isSharePlan(\n plan: PreparedPrincipalContainerRematerializationBatch[\"plans\"][number],\n): plan is MaterializedContainerSharePlan {\n return plan.plan.body.eventType === \"container.grant\";\n}\n\nasync function assertCurrentShareGrantName(\n runtime: Parameters<typeof createRuntimeCurrentSharePrincipalPolicy>[0],\n share: Parameters<typeof shareRemoteContainerWithGroup>[0],\n context: RuntimeCurrentGroupMutationContext,\n expectedName: string,\n) {\n const mismatch = await groupPolicyNameMismatch(\n context.currentPolicy,\n expectedName,\n createRuntimeGroupMetadataAccess(\n runtime,\n share.author.organizationId,\n context.stillCurrent,\n context.verifyMetadataContainer,\n ).readName,\n );\n if (mismatch)\n throw new GroupShareNameMismatchError(\n \"Container share group name does not match the signed group policy\",\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n}\n\nfunction prepareCurrentShareGrantBatch(\n share: Parameters<typeof shareRemoteContainerWithGroup>[0],\n context: RuntimeCurrentGroupMutationContext,\n nextPolicy: Parameters<\n typeof preparePrincipalContainerRematerializationBatch\n >[0][\"nextPolicy\"],\n recitationStillCurrent?: () => boolean,\n) {\n return preparePrincipalContainerRematerializationBatch({\n ...share,\n grants: [\n ...new Map(\n [...context.currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: share.recipientGroupId,\n nextPolicy,\n resolveAuthoredPolicyReferences: context.resolveAuthoredPolicyReferences,\n stillCurrent: context.stillCurrent,\n recitationStillCurrent,\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"currentSharePrincipalPolicy.js","sourceRoot":"","sources":["currentSharePrincipalPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,qDAAqD,CAAC;AAC1G,OAAO,EAAE,kCAAkC,EAAE,MAAM,mFAAmF,CAAC;AACvI,OAAO,EAAE,6BAA6B,EAAE,MAAM,6DAA6D,CAAC;AAC5G,OAAO,EAAE,gCAAgC,EAAE,MAAM,qDA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ACL,SAAS,EACT,KAAK,EACL,YAAY,GAOb;IACC,IAAI,KAAK,CAAC,iBAAiB,KAAK,SAAS;QAAE,OAAO;IAClD,MAAM,QAAQ,GACZ,KAAK,CAAC,iBAAiB;QACvB,gCAAgC,CAC9B,OAAO,EACP,KAAK,CAAC,cAAc,EACpB,YAAY,EACZ,mDAAmD,CAAC;YAClD,SAAS;YACT,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,YAAY;SACb,CAAC,CACH,CAAC,QAAQ,CAAC;IACb,MAAM,QAAQ,GAAG,MAAM,uBAAuB,CAC5C,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,iBAAiB,EACvB,QAAQ,CACT,CAAC;IACF,IAAI,QAAQ;QACV,MAAM,IAAI,2BAA2B,CACnC,QAAQ,KAAK,sBAAsB;YACjC,CAAC,CAAC,kEAAkE;YACpE,CAAC,CAAC,mEAAmE,CACxE,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../../data/keyingProjectionVerification/types\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../../../data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence\";\nimport { principalHeadMatchesReference } from \"../../../../data/principals/organizationAuthorityDescriptor\";\nimport { loadCurrentOrganizationAuthority } from \"../../../organizations/currentOrganizationAuthority\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../../../organizations/groupMetadata/currentGroupMetadataAuthority\";\nimport { assertGroupMetadataBinding } from \"../../../organizations/groupMetadata/groupMetadataBinding\";\nimport { createRuntimeGroupMetadataAccess } from \"../../../organizations/groupMetadata/groupMetadataRuntime\";\nimport { createCurrentPrincipalMutationLease } from \"../../../organizations/principalMutations/currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"../../../organizations/principalMutations/principalMutationJournalManagement\";\nimport {\n type GroupPolicyNameReader,\n groupPolicyNameMismatch,\n} from \"../../../organizations/principalPolicy/principalPolicyRequest\";\nimport { GroupShareNameMismatchError } from \"./sharePrincipalPolicy\";\n\ntype CurrentShareRuntime = Parameters<\n typeof createRuntimeGroupMetadataAccess\n>[0] &\n Parameters<typeof createCurrentPrincipalMutationLease>[0] & {\n readonly apiClient: {\n readonly recoverPendingPrincipalMutation?:\n | PrincipalMutationRecoveryApi[\"recoverPendingPrincipalMutation\"]\n | undefined;\n };\n };\n\ninterface CurrentShareInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly expectedGroupHead?: ReferencedPrincipalHead | undefined;\n readonly expectedGroupName?: string | undefined;\n /** Trusted internal reader; it must authenticate the signed metadata container. */\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly stillCurrent: () => boolean;\n}\n\ntype CurrentGroup = Awaited<\n ReturnType<\n Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>[\"readGroup\"]\n >\n>;\n\nexport interface CurrentSharePrincipalPolicy {\n readonly current: CurrentGroup[\"current\"];\n readonly policy: CurrentGroup[\"policy\"];\n readonly checkpointPolicies: readonly CurrentGroup[\"policy\"][];\n readonly stillCurrent: () => boolean;\n}\n\n/** A share read need not be a group administrator; minting a grant checks that separately. */\nexport function createRuntimeCurrentSharePrincipalPolicy(\n runtime: CurrentShareRuntime,\n) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: CurrentShareInput,\n work: (policy: CurrentSharePrincipalPolicy) => Promise<T>,\n ): Promise<T> => {\n input = {\n ...input,\n expectedGroupHead: input.expectedGroupHead\n ? { ...input.expectedGroupHead }\n : undefined,\n };\n return lease(\n input.stillCurrent,\n async ({ resolveCurrentPolicy, stillCurrent: leaseCurrent }) => {\n await runtime.apiClient.recoverPendingPrincipalMutation?.(\n input.organizationId,\n );\n assertProjectionVerificationCurrent(leaseCurrent);\n const authority = await loadCurrentOrganizationAuthority({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: leaseCurrent,\n });\n const group = await authority.readGroup(input.groupId);\n const stillCurrent = () =>\n leaseCurrent() && authority.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(\n group.policy.state,\n input.expectedGroupHead,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Container share expected group head conflicts with the signed organization directory\",\n );\n assertGroupMetadataBinding(group.current, authority.descriptor);\n await assertCurrentShareName({\n runtime,\n input,\n authority,\n group,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const checkpointPolicies = [...group.dependencies, group.policy];\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n policies: checkpointPolicies,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n current: group.current,\n policy: group.policy,\n checkpointPolicies,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function assertCurrentShareName({\n runtime,\n input,\n authority,\n group,\n stillCurrent,\n}: {\n runtime: CurrentShareRuntime;\n input: CurrentShareInput;\n authority: Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>;\n group: CurrentGroup;\n stillCurrent: () => boolean;\n}) {\n if (input.expectedGroupName === undefined) return;\n const readName =\n input.readEncryptedName ??\n createRuntimeGroupMetadataAccess(\n runtime,\n input.organizationId,\n stillCurrent,\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent,\n }),\n ).readName;\n const mismatch = await groupPolicyNameMismatch(\n group.current,\n input.expectedGroupName,\n readName,\n );\n if (mismatch)\n throw new GroupShareNameMismatchError(\n mismatch === \"forbidden_characters\"\n ? \"Container share group name contains control or format characters\"\n : \"Container share group name does not match the signed group policy\",\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"runtimeCurrentG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;oBACL,MAAM;oBACN,sBAAsB;iBACvB,CAAC,CAAC;YACL,MAAM,YAAY,GAAG,MAAM,mCAAmC,CAAC;gBAC7D,GAAG,KAAK;gBACR,kBAAkB;gBAClB,oBAAoB,EAClB,uCAAuC,CAAC,kBAAkB,CAAC;gBAC7D,SAAS,EAAE;oBACT,eAAe,EAAE,MAAM;oBACvB,SAAS,EAAE,KAAK,CAAC,gBAAgB;oBACjC,WAAW,EAAE,OAAO;iBACrB;gBACD,wBAAwB;aACzB,CAAC,CAAC;YACH,OAAO,mCAAmC,CAAC;gBACzC,GAAG,KAAK;gBACR,kBAAkB,EAAE,kBAAkB;gBACtC,sBAAsB;gBACtB,YAAY,EAAE,YAAY,CAAC,YAAY;gBACvC,IAAI,EAAE,YAAY,CAAC,IAAI;gBACvB,MAAM,EAAE,GAAG,EAAE,CACX,4BAA4B,CAAC,GAAG,EAAE,CAChC,KAAK,CAAC,SAAS,CAAC,cAAc,CAC5B,KAAK,CAAC,WAAW,EACjB,YAAY,CAAC,IAAI,CAAC,OAAO,EACzB;oBACE,qCAAqC,EACnC,KAAK,CAAC,MAAM,CAAC,cAAc;iBAC9B,CACF,CACF;aACJ,CAAC,CAAC;QACL,CAAC,CACF,CACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n nullOnProjectionVerificationCancellation,\n requireProjectionUserKeyResolver,\n} from \"../../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { inheritPrincipalHistoryProtection } from \"../../../../data/principals/principalHistoryRuntime\";\nimport { createRuntimeCurrentGroupMutation } from \"../../../organizations/principalMutations/runtimeCurrentGroupMutation\";\nimport {\n apiPrincipalPolicyPageReader,\n apiProjectionPolicyHistoryReader,\n} from \"../../../principals/principalPolicyHistoryReader\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"../mutationSubmit\";\nimport { commitCurrentShareGrant } from \"./currentShareGrantMutation\";\nimport { createRuntimeCurrentSharePrincipalPolicy } from \"./currentSharePrincipalPolicy\";\nimport type { shareRemoteContainerWithGroup } from \"./index\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport { resolveShareProjection } from \"./shareProjection\";\n\n/** Current evidence covers planning, any compound grant mint, and acknowledgement. */\nexport function createRuntimeCurrentGroupShare(\n runtime: Parameters<typeof createRuntimeCurrentSharePrincipalPolicy>[0],\n): typeof shareRemoteContainerWithGroup | undefined {\n const readCurrent = createRuntimeCurrentSharePrincipalPolicy(runtime);\n const api = runtime.apiClient;\n const historyReader = apiPrincipalPolicyPageReader(api);\n if (!readCurrent || !historyReader) return undefined;\n const mutate = createRuntimeCurrentGroupMutation(\n inheritPrincipalHistoryProtection(runtime, {\n ...runtime,\n apiClient: {\n ...historyReader,\n ...apiProjectionPolicyHistoryReader(api),\n recoverPendingPrincipalMutation: async (organizationId: string) => {\n // Built-in clients supply journal recovery; standalone hosts retain\n // responsibility for transport and exact-outcome recovery.\n await api.recoverPendingPrincipalMutation?.(organizationId);\n },\n },\n }),\n );\n if (!mutate) throw new Error(\"Current group mutation custody is unavailable\");\n return async (input) => {\n if (input.stillCurrent?.() === false) return null;\n const recitationStillCurrent = input.stillCurrent ?? (() => true);\n return nullOnProjectionVerificationCancellation(() =>\n readCurrent(\n {\n expectedGroupName: input.expectedGroupName ?? undefined,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n },\n async ({ policy, checkpointPolicies, stillCurrent }) => {\n const share = { ...input, stillCurrent };\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n share,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const grant = policy.grants.find(\n (candidate) => candidate.containerId === input.containerId,\n );\n if (!grant || grant.accessLevel !== input.accessLevel)\n return commitCurrentShareGrant({\n runtime,\n share,\n mutate,\n recitationStillCurrent,\n });\n const materialized = await buildMaterializedContainerSharePlan({\n ...share,\n previousProjection,\n principalPolicyCache:\n principalPolicyCacheForVerifiedPolicies(checkpointPolicies),\n recipient: {\n principalPolicy: policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n });\n return submitAcknowledgedContainerMutation({\n ...share,\n recitationPolicies: checkpointPolicies,\n recitationStillCurrent,\n containerKey: materialized.containerKey,\n plan: materialized.plan,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materialized.plan.request,\n {\n expectedPaymentRequiredOrganizationId:\n input.author.organizationId,\n },\n ),\n ),\n });\n },\n ),\n );\n };\n}\n"]}