@tearleads/client-sdk 0.1.79 → 0.1.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/client/deviceFirst/index.d.ts +1 -1
  2. package/client/deviceFirst/index.js +1 -1
  3. package/client/deviceFirst/index.js.map +1 -1
  4. package/client/runtime/principalMutationApi.js +1 -1
  5. package/client/runtime/principalMutationApi.js.map +1 -1
  6. package/client/runtime/principalMutationDispatch.js +1 -1
  7. package/client/runtime/principalMutationDispatch.js.map +1 -1
  8. package/client/runtime/rootContainerAdoption.js.map +1 -1
  9. package/client/runtime/workflowRuntime.d.ts +1 -1
  10. package/client/runtime/workflowRuntime.js.map +1 -1
  11. package/client/session/sessionPurgeRecovery.js +1 -1
  12. package/client/session/sessionPurgeRecovery.js.map +1 -1
  13. package/data/blobs/attachments/projection.js +2 -3
  14. package/data/blobs/attachments/projection.js.map +1 -1
  15. package/data/documents/documentConstants.d.ts +1 -0
  16. package/data/documents/documentConstants.js +1 -0
  17. package/data/documents/documentConstants.js.map +1 -1
  18. package/data/documents/shared/containerKek/containerKekEntryVerification.d.ts +3 -0
  19. package/data/documents/shared/containerKek/index.d.ts +5 -0
  20. package/data/documents/shared/containerKek/index.js +9 -0
  21. package/data/documents/shared/containerKek/index.js.map +1 -0
  22. package/data/documents/shared/projection/index.d.ts +1 -1
  23. package/data/documents/shared/projection/index.js +1 -1
  24. package/data/documents/shared/projection/index.js.map +1 -1
  25. package/data/documents/shared/sync/syncResponseAuthorization.js +1 -1
  26. package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -1
  27. package/data/keyingProjectionVerification/container/containerCreateManifest.d.ts +12 -0
  28. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +16 -0
  29. package/data/keyingProjectionVerification/index.d.ts +5 -0
  30. package/data/keyingProjectionVerification/index.js +6 -1
  31. package/data/keyingProjectionVerification/index.js.map +1 -1
  32. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.d.ts +3 -0
  33. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +1 -1
  34. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  35. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCheckpointSelection.d.ts +6 -0
  36. package/data/{persistence → keyingProjectionVerification}/principalPolicy/principalPolicyCheckpointSelection.js +1 -1
  37. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
  38. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.d.ts +24 -0
  39. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +1 -1
  40. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  41. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js +1 -1
  42. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -1
  43. package/data/persistence/container-contents/documentPlacement.js +1 -1
  44. package/data/persistence/container-contents/documentPlacement.js.map +1 -1
  45. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
  46. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js.map +1 -1
  47. package/data/persistence/documents/documentsPersistence.d.ts +1 -1
  48. package/data/persistence/documents/documentsPersistence.js +2 -3
  49. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  50. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  51. package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
  52. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +1 -1
  53. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  54. package/data/persistence/documents/internal/documentDeletionPersistence.js +1 -1
  55. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  56. package/data/persistence/documents/internal/documentMutationPersistence.js +1 -1
  57. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  58. package/data/persistence/documents/internal/documentProjectionRows.js +1 -2
  59. package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
  60. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  61. package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
  62. package/data/persistence/documents/internal/documentRows.js +1 -2
  63. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  64. package/data/persistence/documents/internal/orphanSideRows.js +1 -1
  65. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  66. package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
  67. package/data/persistence/documents/internal/pendingCreateAdoption.js.map +1 -1
  68. package/data/persistence/documents/internal/rowQueryPersistence.js +1 -1
  69. package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
  70. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +11 -51
  71. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
  72. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +1 -30
  73. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +4 -85
  74. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  75. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +88 -0
  76. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -0
  77. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js +53 -0
  78. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js.map +1 -0
  79. package/package.json +1 -1
  80. package/stores/local-projection/localProjectionStore.d.ts +1 -1
  81. package/stores/local-projection/localProjectionStore.js +1 -1
  82. package/stores/local-projection/localProjectionStore.js.map +1 -1
  83. package/stores/local-projection/registry.d.ts +1 -1
  84. package/stores/local-projection/registry.js.map +1 -1
  85. package/stores/local-projection/types.d.ts +1 -1
  86. package/stores/local-projection/types.js.map +1 -1
  87. package/workflows/blobs/hydration/decrypt.js +1 -2
  88. package/workflows/blobs/hydration/decrypt.js.map +1 -1
  89. package/workflows/blobs/hydration/hydrate.d.ts +1 -1
  90. package/workflows/blobs/hydration/hydrate.js.map +1 -1
  91. package/workflows/container-contents/container-state/create/createAdoption.js +1 -2
  92. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  93. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -1
  94. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  95. package/workflows/container-contents/info/documentInfo.js +1 -1
  96. package/workflows/container-contents/info/documentInfo.js.map +1 -1
  97. package/workflows/container-contents/metadata/index.js +1 -2
  98. package/workflows/container-contents/metadata/index.js.map +1 -1
  99. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  100. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  101. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
  102. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
  103. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  104. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  105. package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
  106. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  107. package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
  108. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  109. package/workflows/container-contents/pendingWrites/index.js +1 -1
  110. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  111. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -3
  112. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  113. package/workflows/containers/child/create/index.js +1 -1
  114. package/workflows/containers/child/create/index.js.map +1 -1
  115. package/workflows/containers/child/move/moveRotation.js +1 -1
  116. package/workflows/containers/child/move/moveRotation.js.map +1 -1
  117. package/workflows/containers/child/move/moveWraps.js +1 -1
  118. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  119. package/workflows/containers/child/rekey/rekeyProjection.js +1 -1
  120. package/workflows/containers/child/rekey/rekeyProjection.js.map +1 -1
  121. package/workflows/containers/child/rotation/rotationContext.js +1 -2
  122. package/workflows/containers/child/rotation/rotationContext.js.map +1 -1
  123. package/workflows/containers/child/share/shareAncestorRepair.js +1 -2
  124. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -1
  125. package/workflows/containers/index.d.ts +2 -3
  126. package/workflows/containers/index.js +1 -2
  127. package/workflows/containers/index.js.map +1 -1
  128. package/workflows/containers/writeRefusal.js +1 -1
  129. package/workflows/containers/writeRefusal.js.map +1 -1
  130. package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
  131. package/workflows/documents/linkSet/linkSetProjectionSeed.js.map +1 -1
  132. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +1 -1
  133. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  134. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  135. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  136. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
  137. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  138. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
  139. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  140. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  141. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  142. package/workflows/organizations/provisioning/createOrganization.d.ts +1 -1
  143. package/workflows/organizations/provisioning/createOrganization.js +1 -1
  144. package/workflows/organizations/provisioning/createOrganization.js.map +1 -1
  145. package/workflows/organizations/provisioning/organizationProvisioningAttempt.d.ts +1 -1
  146. package/workflows/organizations/provisioning/organizationProvisioningAttempt.js.map +1 -1
  147. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  148. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
  149. package/workflows/principals/externalAdminPolicy.js +1 -1
  150. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  151. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
  152. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  153. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +1 -1
  154. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  155. package/workflows/registration/index.d.ts +2 -1
  156. package/workflows/registration/index.js +2 -1
  157. package/workflows/registration/index.js.map +1 -1
  158. package/workflows/registration/organizationProvisioning.d.ts +39 -0
  159. package/workflows/registration/organizationProvisioning.js +211 -0
  160. package/workflows/registration/organizationProvisioning.js.map +1 -0
  161. package/workflows/registration/organizationProvisioningArtifacts.d.ts +2 -3
  162. package/workflows/registration/organizationProvisioningArtifacts.js.map +1 -1
  163. package/workflows/registration/provisioningBootstrapBuilders.d.ts +3 -3
  164. package/workflows/registration/provisioningBootstrapBuilders.js +3 -4
  165. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  166. package/workflows/registration/registerIdentity.d.ts +2 -39
  167. package/workflows/registration/registerIdentity.js +2 -207
  168. package/workflows/registration/registerIdentity.js.map +1 -1
  169. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
  170. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  171. package/workflows/sync/remoteResetPlans.js +2 -2
  172. package/workflows/sync/remoteResetPlans.js.map +1 -1
  173. package/data/persistence/documents/internal/constants.d.ts +0 -1
  174. package/data/persistence/documents/internal/constants.js +0 -2
  175. package/data/persistence/documents/internal/constants.js.map +0 -1
  176. package/data/persistence/principalKeys/principalGrantRetirementPersistence.d.ts +0 -9
  177. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { type ContainerContentsStore, type ContainerContentsStoreOptions } from "../../stores/container-contents/index.js";
2
2
  import { type LocalProjectionView } from "../../stores/local-projection/index.js";
3
3
  import { type ReconciliationService } from "../../sync/reconciliation/index.js";
4
- import { type ContainerContentsStoreWorkflowRuntime } from "../../workflows/container-contents/runtime.js";
4
+ import { type ContainerContentsStoreWorkflowRuntime } from "../../workflows/container-contents/index.js";
5
5
  import type { ContainerContents } from "../containerContents/index.js";
6
6
  import type { InternalRuntime } from "../runtime/workflowRuntime.js";
7
7
  export type { LocalProjectionView } from "../../stores/local-projection/index.js";
@@ -4,9 +4,9 @@ import { openDocumentStore } from "../../stores/documents/index.js";
4
4
  import { requestRegisteredDocumentRemoteSync, subscribeToPersistedDocumentDeletions, subscribeToPersistedDocuments, } from "../../stores/documents/registry.js";
5
5
  import { getOrCreateLocalProjectionStore, } from "../../stores/local-projection/index.js";
6
6
  import { connectReconciliationTriggers, createReconciliationService, systemReconciliationClock, } from "../../sync/reconciliation/index.js";
7
+ import { createContainerContentsDocumentsRuntime, createContainerContentsStoreWorkflowRuntime, } from "../../workflows/container-contents/index.js";
7
8
  import { listAllContainerDocumentIdsFromApi } from "../../workflows/container-contents/documentDiscovery/containerDocumentListing.js";
8
9
  import { probeUndiscoveredRemoteDocumentBatch } from "../../workflows/container-contents/documentPriming/documentHydrationProbe.js";
9
- import { createContainerContentsDocumentsRuntime, createContainerContentsStoreWorkflowRuntime, } from "../../workflows/container-contents/runtime.js";
10
10
  import { discoverContainerDocumentLanesForRuntime } from "../containerContents/documentDiscovery.js";
11
11
  import { createReconciledDocumentContentPuller } from "./reconciledDocumentContentPull.js";
12
12
  export function createDeviceFirst(runtimeService, containerContents) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,mC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AAC;IACvC,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,cAA+B;IAE/B,OAAO,2CAA2C,CAChD,cAAc,CAAC,aAAa,EAAE,EAC9B,cAAc,CAAC,kBAAkB,CAClC,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n disposeDomainSyncCoordinator,\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n isAutomaticRootCatchupContainerNode,\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n} from \"../../stores/container-contents\";\nimport { openDocumentStore } from \"../../stores/documents\";\nimport {\n requestRegisteredDocumentRemoteSync,\n subscribeToPersistedDocumentDeletions,\n subscribeToPersistedDocuments,\n} from \"../../stores/documents/registry\";\nimport {\n getOrCreateLocalProjectionStore,\n type LocalProjectionStore,\n type LocalProjectionView,\n} from \"../../stores/local-projection\";\nimport {\n connectReconciliationTriggers,\n createReconciliationService,\n type ReconciliationHost,\n type ReconciliationService,\n systemReconciliationClock,\n} from \"../../sync/reconciliation\";\nimport { listAllContainerDocumentIdsFromApi } from \"../../workflows/container-contents/documentDiscovery/containerDocumentListing\";\nimport { probeUndiscoveredRemoteDocumentBatch } from \"../../workflows/container-contents/documentPriming/documentHydrationProbe\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n} from \"../../workflows/container-contents/runtime\";\nimport type { ContainerContents } from \"../containerContents\";\nimport { discoverContainerDocumentLanesForRuntime } from \"../containerContents/documentDiscovery\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { createReconciledDocumentContentPuller } from \"./reconciledDocumentContentPull\";\n\nexport type { LocalProjectionView } from \"../../stores/local-projection\";\n\n/** One domain scope's local read, local-write, and reconciliation handles. */\nexport interface DeviceFirstContainerContents {\n /**\n * Locally durable container tree and mutation store. Ordinary tree writes\n * update this store after local persistence and queue remote convergence in\n * the background; security-sensitive remote operations keep their explicit\n * online requirements.\n */\n readonly containerStore: ContainerContentsStore;\n /** Background remote reconciliation; never awaited for first paint. */\n readonly reconciler: ReconciliationService;\n /** Synchronously readable container/document projection. */\n readonly view: LocalProjectionView;\n}\n\n/**\n * Device-first facade. Opens a shared scope that pairs immediate local reads\n * and locally durable writes with background remote convergence.\n */\nexport interface DeviceFirst {\n /** Open all device-first handles for the current domain scope. */\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents;\n /** Stop the current scope's reconciler (if one was created) on teardown. */\n dispose(): void;\n}\n\nexport function createDeviceFirst(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n): DeviceFirst {\n return new DeviceFirstService(runtimeService, containerContents);\n}\n\ninterface DeviceFirstScopeEntry {\n contents: DeviceFirstContainerContents;\n disconnectReconciliationTriggers: () => void;\n unsubscribePersistedDocumentDeletions: () => void;\n unsubscribePersistedDocuments: () => void;\n}\n\nfunction createInitialDocumentProbeHost(\n runtimeService: InternalRuntime,\n domainScope: ReconciliationHost[\"domainScope\"],\n): Pick<\n ReconciliationHost,\n | \"listContainerDocumentIds\"\n | \"probeUndiscoveredDocumentsBatch\"\n | \"reportInitialDocumentProbeComplete\"\n> {\n return {\n listContainerDocumentIds: (containerId) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return listAllContainerDocumentIdsFromApi({\n apiClient: runtime.apiClient,\n containerId,\n reportErrors: false,\n });\n },\n probeUndiscoveredDocumentsBatch: async (input) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return probeUndiscoveredRemoteDocumentBatch({\n ...input,\n host: {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: (target) =>\n openDocumentStore(\n domainScope,\n target.localId,\n target.runtime,\n target.documentId,\n ),\n },\n runtime,\n });\n },\n reportInitialDocumentProbeComplete: (requestedCount) => {\n runtimeService\n .workflowInput()\n .util.log(\n `Initial document hydration probe requested ${requestedCount} syncs`,\n );\n },\n };\n}\n\nclass DeviceFirstService implements DeviceFirst {\n // A real Map (not WeakMap) so dispose() can iterate every scope seen this\n // session. A running reconciler holds event subscriptions that keep an idle,\n // stale-scope service (and its scope) reachable anyway, so WeakMap bought no\n // GC here; the entries are released explicitly on dispose().\n private readonly entriesByScope = new Map<\n DomainScope,\n DeviceFirstScopeEntry\n >();\n\n constructor(\n private readonly runtimeService: InternalRuntime,\n private readonly containerContents: ContainerContents,\n ) {}\n\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents {\n return this.getOrCreateEntry(options).contents;\n }\n\n dispose(): void {\n // Stop every reconciler created this session — not just the current\n // scope's. A scope change (e.g. anonymous -> authenticated) leaves the old\n // scope's reconciler subscribed and its coordinator pump live; tear them\n // all down. Force-stop each scope's coordinator (which runs the reconciler\n // lane) alongside stopping the service.\n for (const [domainScope, entry] of this.entriesByScope) {\n entry.contents.reconciler.stop();\n entry.disconnectReconciliationTriggers();\n entry.unsubscribePersistedDocumentDeletions();\n entry.unsubscribePersistedDocuments();\n disposeDomainSyncCoordinator(domainScope);\n }\n this.entriesByScope.clear();\n }\n\n private workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createDeviceFirstWorkflowRuntime(this.runtimeService);\n }\n\n private getOrCreateEntry(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstScopeEntry {\n const runtime = this.workflowRuntime();\n const domainScope = runtime.state.domainScope;\n const existing = this.entriesByScope.get(domainScope);\n if (existing) {\n // Do not call updateRuntime here: facade selectors run during React\n // render, and updateRuntime emits synchronously. Hosts drive runtime\n // updates through view.updateRuntime() from an effect instead.\n return existing;\n }\n\n const store = getOrCreateLocalProjectionStore({\n domainScope,\n runtime,\n options,\n });\n const service = createReconciliationService(\n this.createReconciliationHost(store, domainScope),\n );\n const disconnectReconciliationTriggers = connectReconciliationTriggers({\n service,\n store,\n });\n const unsubscribePersistedDocumentDeletions =\n subscribeToPersistedDocumentDeletions(domainScope, (localId) => {\n store.removePersistedDocument(localId);\n });\n const unsubscribePersistedDocuments = subscribeToPersistedDocuments(\n domainScope,\n (document, change) =>\n store.refreshPersistedDocument(document, change.placementChanged),\n );\n service.start();\n\n const view: LocalProjectionView = {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (listener) => store.subscribe(listener),\n setActiveContainer: (containerId) =>\n store.setActiveContainer(containerId),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n\n const entry: DeviceFirstScopeEntry = {\n contents: {\n containerStore: store.getContainerStore(),\n reconciler: service,\n view,\n },\n disconnectReconciliationTriggers,\n unsubscribePersistedDocumentDeletions,\n unsubscribePersistedDocuments,\n };\n this.entriesByScope.set(domainScope, entry);\n return entry;\n }\n\n private createReconciliationHost(\n store: LocalProjectionStore,\n domainScope: ReconciliationHost[\"domainScope\"],\n ): ReconciliationHost {\n const runtimeService = this.runtimeService;\n const containerContents = this.containerContents;\n const requestDocumentContentPull = createReconciledDocumentContentPuller({\n getContainer: (containerId) =>\n store\n .getSnapshot()\n .containers.find((container) => container.id === containerId) ?? null,\n pullDocumentContent: (input) =>\n containerContents.pullDocumentContent(input),\n requestRegisteredDocumentRemoteSync: (localId, documentId) =>\n requestRegisteredDocumentRemoteSync(domainScope, localId, documentId),\n });\n const canDiscoverContainerDocuments = (containerId: string) => {\n const container = store\n .getSnapshot()\n .containers.find((node) => node.id === containerId);\n return container ? isRemoteBackedContainerNode(container) : false;\n };\n const listKnownContainerIds = () => {\n // A local-first id is not listable yet and may still be racing its create\n // request. Once remote-backed, it participates normally; system contents\n // are especially important during rematerialization because this device\n // may not have authored them.\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isReconcilableContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n const listAutomaticRootCatchupContainerIds = () => {\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isAutomaticRootCatchupContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n return {\n clock: systemReconciliationClock,\n domainScope,\n registerLane: (key, config) =>\n getOrCreateDomainSyncCoordinator(domainScope).registerLane(key, config),\n canDiscoverContainerDocuments,\n getRuntimeStatus: () => {\n const input = runtimeService.workflowInput();\n return {\n dbStatus: input.infra.dbStatus,\n isAuthenticated: input.auth.isAuthenticated,\n online: input.state.online,\n };\n },\n listKnownContainerIds,\n // Root discovery can surface directly granted non-root containers, so\n // retain every regular container. Exclude only this identity's own system\n // children; cold/auth backfill and explicit full Refresh cover those.\n listAutomaticRootCatchupContainerIds,\n discoverContainerDocuments: (requests, onOutcome) =>\n discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n }),\n loadContainerDelta: (containerId) =>\n store.loadContainerDelta(containerId),\n applyReconciled: (delta) => store.applyReconciled(delta),\n requestDocumentContentPull,\n ...createInitialDocumentProbeHost(runtimeService, domainScope),\n refreshTree: async () => {\n await store.getContainerStore().refresh();\n },\n refreshRootTree: async () => {\n await store.getContainerStore().refreshRootLane();\n },\n isIgnorableError: isDatabaseUnavailableError,\n // Resolve the runtime per call: it is rebuilt as the active identity\n // changes, and a reference captured here would report into a dead host.\n logError: (message, error) =>\n logReconciliationFailure(this.workflowRuntime(), message, error),\n };\n }\n}\n\n// Returns the host's result: both callbacks are declared `=> void` but may be\n// async, and the lane reporter only catches a rejection it is handed.\nfunction logReconciliationFailure(\n runtime: ContainerContentsStoreWorkflowRuntime,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nexport function createDeviceFirstWorkflowRuntime(\n runtimeService: InternalRuntime,\n): ContainerContentsStoreWorkflowRuntime {\n return createContainerContentsStoreWorkflowRuntime(\n runtimeService.workflowInput(),\n runtimeService.adoptRootContainer,\n );\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,mCAAmC,EACnC,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,mCAAmC,EACnC,qCAAqC,EACrC,6BAA6B,GAC9B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,+BAA+B,GAGhC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,6BAA6B,EAC7B,2BAA2B,EAG3B,yBAAyB,GAC1B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAEL,uCAAuC,EACvC,2CAA2C,GAC5C,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,kCAAkC,EAAE,MAAM,+EAA+E,CAAC;AACnI,OAAO,EAAE,oCAAoC,EAAE,MAAM,2EAA2E,CAAC;AAEjI,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAElG,OAAO,EAAE,qCAAqC,EAAE,MAAM,iCAAiC,CAAC;AAgCxF,MAAM,UAAU,iBAAiB,CAC/B,cAA+B,EAC/B,iBAAoC;IAEpC,OAAO,IAAI,kBAAkB,CAAC,cAAc,EAAE,iBAAiB,CAAC,CAAC;AACnE,CAAC;AASD,SAAS,8BAA8B,CACrC,cAA+B,EAC/B,WAA8C;IAO9C,OAAO;QACL,wBAAwB,EAAE,CAAC,WAAW,EAAE,EAAE;YACxC,MAAM,OAAO,GAAG,gCAAgC,CAAC,cAAc,CAAC,CAAC;YACjE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,QAAQ,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,CAC3B,wBAAwB,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC;SACnE,CAAC;IACJ,CAAC;CACF;AAED,8EAA8E;AAC9E,sEAAsE;AACtE,SAAS,wBAAwB,CAC/B,OAA8C,EAC9C,OAAe,EACf,KAAc;IAEd,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IACvC,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,cAA+B;IAE/B,OAAO,2CAA2C,CAChD,cAAc,CAAC,aAAa,EAAE,EAC9B,cAAc,CAAC,kBAAkB,CAClC,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n disposeDomainSyncCoordinator,\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n isAutomaticRootCatchupContainerNode,\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n} from \"../../stores/container-contents\";\nimport { openDocumentStore } from \"../../stores/documents\";\nimport {\n requestRegisteredDocumentRemoteSync,\n subscribeToPersistedDocumentDeletions,\n subscribeToPersistedDocuments,\n} from \"../../stores/documents/registry\";\nimport {\n getOrCreateLocalProjectionStore,\n type LocalProjectionStore,\n type LocalProjectionView,\n} from \"../../stores/local-projection\";\nimport {\n connectReconciliationTriggers,\n createReconciliationService,\n type ReconciliationHost,\n type ReconciliationService,\n systemReconciliationClock,\n} from \"../../sync/reconciliation\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n} from \"../../workflows/container-contents\";\nimport { listAllContainerDocumentIdsFromApi } from \"../../workflows/container-contents/documentDiscovery/containerDocumentListing\";\nimport { probeUndiscoveredRemoteDocumentBatch } from \"../../workflows/container-contents/documentPriming/documentHydrationProbe\";\nimport type { ContainerContents } from \"../containerContents\";\nimport { discoverContainerDocumentLanesForRuntime } from \"../containerContents/documentDiscovery\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { createReconciledDocumentContentPuller } from \"./reconciledDocumentContentPull\";\n\nexport type { LocalProjectionView } from \"../../stores/local-projection\";\n\n/** One domain scope's local read, local-write, and reconciliation handles. */\nexport interface DeviceFirstContainerContents {\n /**\n * Locally durable container tree and mutation store. Ordinary tree writes\n * update this store after local persistence and queue remote convergence in\n * the background; security-sensitive remote operations keep their explicit\n * online requirements.\n */\n readonly containerStore: ContainerContentsStore;\n /** Background remote reconciliation; never awaited for first paint. */\n readonly reconciler: ReconciliationService;\n /** Synchronously readable container/document projection. */\n readonly view: LocalProjectionView;\n}\n\n/**\n * Device-first facade. Opens a shared scope that pairs immediate local reads\n * and locally durable writes with background remote convergence.\n */\nexport interface DeviceFirst {\n /** Open all device-first handles for the current domain scope. */\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents;\n /** Stop the current scope's reconciler (if one was created) on teardown. */\n dispose(): void;\n}\n\nexport function createDeviceFirst(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n): DeviceFirst {\n return new DeviceFirstService(runtimeService, containerContents);\n}\n\ninterface DeviceFirstScopeEntry {\n contents: DeviceFirstContainerContents;\n disconnectReconciliationTriggers: () => void;\n unsubscribePersistedDocumentDeletions: () => void;\n unsubscribePersistedDocuments: () => void;\n}\n\nfunction createInitialDocumentProbeHost(\n runtimeService: InternalRuntime,\n domainScope: ReconciliationHost[\"domainScope\"],\n): Pick<\n ReconciliationHost,\n | \"listContainerDocumentIds\"\n | \"probeUndiscoveredDocumentsBatch\"\n | \"reportInitialDocumentProbeComplete\"\n> {\n return {\n listContainerDocumentIds: (containerId) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return listAllContainerDocumentIdsFromApi({\n apiClient: runtime.apiClient,\n containerId,\n reportErrors: false,\n });\n },\n probeUndiscoveredDocumentsBatch: async (input) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return probeUndiscoveredRemoteDocumentBatch({\n ...input,\n host: {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: (target) =>\n openDocumentStore(\n domainScope,\n target.localId,\n target.runtime,\n target.documentId,\n ),\n },\n runtime,\n });\n },\n reportInitialDocumentProbeComplete: (requestedCount) => {\n runtimeService\n .workflowInput()\n .util.log(\n `Initial document hydration probe requested ${requestedCount} syncs`,\n );\n },\n };\n}\n\nclass DeviceFirstService implements DeviceFirst {\n // A real Map (not WeakMap) so dispose() can iterate every scope seen this\n // session. A running reconciler holds event subscriptions that keep an idle,\n // stale-scope service (and its scope) reachable anyway, so WeakMap bought no\n // GC here; the entries are released explicitly on dispose().\n private readonly entriesByScope = new Map<\n DomainScope,\n DeviceFirstScopeEntry\n >();\n\n constructor(\n private readonly runtimeService: InternalRuntime,\n private readonly containerContents: ContainerContents,\n ) {}\n\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents {\n return this.getOrCreateEntry(options).contents;\n }\n\n dispose(): void {\n // Stop every reconciler created this session — not just the current\n // scope's. A scope change (e.g. anonymous -> authenticated) leaves the old\n // scope's reconciler subscribed and its coordinator pump live; tear them\n // all down. Force-stop each scope's coordinator (which runs the reconciler\n // lane) alongside stopping the service.\n for (const [domainScope, entry] of this.entriesByScope) {\n entry.contents.reconciler.stop();\n entry.disconnectReconciliationTriggers();\n entry.unsubscribePersistedDocumentDeletions();\n entry.unsubscribePersistedDocuments();\n disposeDomainSyncCoordinator(domainScope);\n }\n this.entriesByScope.clear();\n }\n\n private workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createDeviceFirstWorkflowRuntime(this.runtimeService);\n }\n\n private getOrCreateEntry(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstScopeEntry {\n const runtime = this.workflowRuntime();\n const domainScope = runtime.state.domainScope;\n const existing = this.entriesByScope.get(domainScope);\n if (existing) {\n // Do not call updateRuntime here: facade selectors run during React\n // render, and updateRuntime emits synchronously. Hosts drive runtime\n // updates through view.updateRuntime() from an effect instead.\n return existing;\n }\n\n const store = getOrCreateLocalProjectionStore({\n domainScope,\n runtime,\n options,\n });\n const service = createReconciliationService(\n this.createReconciliationHost(store, domainScope),\n );\n const disconnectReconciliationTriggers = connectReconciliationTriggers({\n service,\n store,\n });\n const unsubscribePersistedDocumentDeletions =\n subscribeToPersistedDocumentDeletions(domainScope, (localId) => {\n store.removePersistedDocument(localId);\n });\n const unsubscribePersistedDocuments = subscribeToPersistedDocuments(\n domainScope,\n (document, change) =>\n store.refreshPersistedDocument(document, change.placementChanged),\n );\n service.start();\n\n const view: LocalProjectionView = {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (listener) => store.subscribe(listener),\n setActiveContainer: (containerId) =>\n store.setActiveContainer(containerId),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n\n const entry: DeviceFirstScopeEntry = {\n contents: {\n containerStore: store.getContainerStore(),\n reconciler: service,\n view,\n },\n disconnectReconciliationTriggers,\n unsubscribePersistedDocumentDeletions,\n unsubscribePersistedDocuments,\n };\n this.entriesByScope.set(domainScope, entry);\n return entry;\n }\n\n private createReconciliationHost(\n store: LocalProjectionStore,\n domainScope: ReconciliationHost[\"domainScope\"],\n ): ReconciliationHost {\n const runtimeService = this.runtimeService;\n const containerContents = this.containerContents;\n const requestDocumentContentPull = createReconciledDocumentContentPuller({\n getContainer: (containerId) =>\n store\n .getSnapshot()\n .containers.find((container) => container.id === containerId) ?? null,\n pullDocumentContent: (input) =>\n containerContents.pullDocumentContent(input),\n requestRegisteredDocumentRemoteSync: (localId, documentId) =>\n requestRegisteredDocumentRemoteSync(domainScope, localId, documentId),\n });\n const canDiscoverContainerDocuments = (containerId: string) => {\n const container = store\n .getSnapshot()\n .containers.find((node) => node.id === containerId);\n return container ? isRemoteBackedContainerNode(container) : false;\n };\n const listKnownContainerIds = () => {\n // A local-first id is not listable yet and may still be racing its create\n // request. Once remote-backed, it participates normally; system contents\n // are especially important during rematerialization because this device\n // may not have authored them.\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isReconcilableContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n const listAutomaticRootCatchupContainerIds = () => {\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isAutomaticRootCatchupContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n return {\n clock: systemReconciliationClock,\n domainScope,\n registerLane: (key, config) =>\n getOrCreateDomainSyncCoordinator(domainScope).registerLane(key, config),\n canDiscoverContainerDocuments,\n getRuntimeStatus: () => {\n const input = runtimeService.workflowInput();\n return {\n dbStatus: input.infra.dbStatus,\n isAuthenticated: input.auth.isAuthenticated,\n online: input.state.online,\n };\n },\n listKnownContainerIds,\n // Root discovery can surface directly granted non-root containers, so\n // retain every regular container. Exclude only this identity's own system\n // children; cold/auth backfill and explicit full Refresh cover those.\n listAutomaticRootCatchupContainerIds,\n discoverContainerDocuments: (requests, onOutcome) =>\n discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n }),\n loadContainerDelta: (containerId) =>\n store.loadContainerDelta(containerId),\n applyReconciled: (delta) => store.applyReconciled(delta),\n requestDocumentContentPull,\n ...createInitialDocumentProbeHost(runtimeService, domainScope),\n refreshTree: async () => {\n await store.getContainerStore().refresh();\n },\n refreshRootTree: async () => {\n await store.getContainerStore().refreshRootLane();\n },\n isIgnorableError: isDatabaseUnavailableError,\n // Resolve the runtime per call: it is rebuilt as the active identity\n // changes, and a reference captured here would report into a dead host.\n logError: (message, error) =>\n logReconciliationFailure(this.workflowRuntime(), message, error),\n };\n }\n}\n\n// Returns the host's result: both callbacks are declared `=> void` but may be\n// async, and the lane reporter only catches a rejection it is handed.\nfunction logReconciliationFailure(\n runtime: ContainerContentsStoreWorkflowRuntime,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nexport function createDeviceFirstWorkflowRuntime(\n runtimeService: InternalRuntime,\n): ContainerContentsStoreWorkflowRuntime {\n return createContainerContentsStoreWorkflowRuntime(\n runtimeService.workflowInput(),\n runtimeService.adoptRootContainer,\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
+ import { recoverJournaledPrincipalMutation } from "../../workflows/organizations/index.js";
1
2
  import { abandonJournaledPrincipalMutation, discardUnreadableJournaledPrincipalMutation, readJournaledPrincipalMutation, } from "../../workflows/organizations/principalMutations/principalMutationJournalManagement.js";
2
- import { recoverJournaledPrincipalMutation } from "../../workflows/organizations/principalMutations/principalMutationJournalSession.js";
3
3
  import { createPrincipalMutationDispatcher } from "./principalMutationDeadline.js";
4
4
  import { createJournaledPrincipalMutations, dispatchAuthoredPrincipalMutation, } from "./principalMutationDispatch.js";
5
5
  function sameScope(current, bound) {
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationApi.js","sourceRoot":"","sources":["principalMutationApi.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iCAAiC,EACjC,2CAA2C,EAE3C,8BAA8B,GAC/B,MAAM,qFAAqF,CAAC;AAC7F,OAAO,EAAE,iCAAiC,EAAE,MAAM,kFAAkF,CAAC;AACrI,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,EACL,iCAAiC,EACjC,iCAAiC,GAElC,MAAM,6BAA6B,CAAC;AAYrC,SAAS,SAAS,CAChB,OAA6C,EAC7C,KAA2C;IAE3C,IAAI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,CAAC,GAAG,CAAC,GAAG,EAAE,8BAA8B,CAAC,KAAK,UAAU;QACtE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,oCAAoC,CAAC,KAAK,UAAU,CAC7E,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n type PrincipalMutationRecoveryApi,\n readJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutations/principalMutationJournalManagement\";\nimport { recoverJournaledPrincipalMutation } from \"../../workflows/organizations/principalMutations/principalMutationJournalSession\";\nimport { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\nimport {\n createJournaledPrincipalMutations,\n dispatchAuthoredPrincipalMutation,\n type JournaledPrincipalMutationMethods,\n} from \"./principalMutationDispatch\";\n\nexport interface PrincipalMutationRuntimeScope {\n readonly database: object;\n readonly execSql: ExecSql;\n readonly generation: number;\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}\n\nfunction sameScope(\n current: PrincipalMutationRuntimeScope | null,\n bound: PrincipalMutationRuntimeScope | null,\n): boolean {\n if (!current || !bound) return current === bound;\n return (\n current.database === bound.database &&\n current.execSql === bound.execSql &&\n current.generation === bound.generation &&\n current.identityTrustDomain === bound.identityTrustDomain &&\n current.signingFingerprint === bound.signingFingerprint &&\n current.signingKeyPair === bound.signingKeyPair &&\n current.userId === bound.userId\n );\n}\n\nexport type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;\ntype MutationOverrides = JournaledPrincipalMutationMethods &\n PrincipalMutationRecoveryApi;\n\ninterface PrincipalMutationApiCustodyInput {\n readonly api: ApiClient;\n readonly readScope: () => PrincipalMutationRuntimeScope | null;\n readonly principalMutationTimeoutMs?: number | undefined;\n}\n\nfunction mutationContext(\n input: PrincipalMutationApiCustodyInput,\n scope: PrincipalMutationRuntimeScope | null,\n organizationId: string,\n) {\n if (!scope)\n throw new Error(\n \"Principal mutations require an authenticated signing identity, a trusted API origin and durable local storage\",\n );\n return {\n execSql: scope.execSql,\n signingKeyPair: scope.signingKeyPair,\n scope: {\n identityTrustDomain: scope.identityTrustDomain,\n organizationId,\n signingFingerprint: scope.signingFingerprint,\n userId: scope.userId,\n },\n stillCurrent: () => sameScope(input.readScope(), scope),\n };\n}\n\n/** Keep API methods bound to their real receiver and journal principal policy and group lifecycle writes. */\nexport function createPrincipalMutationApiCustody(\n input: PrincipalMutationApiCustodyInput,\n) {\n const dispatch = createPrincipalMutationDispatcher(\n input.principalMutationTimeoutMs,\n );\n let cached: {\n scope: PrincipalMutationRuntimeScope | null;\n api: PrincipalMutationApi;\n } | null = null;\n return {\n bind(): PrincipalMutationApi {\n const scope = input.readScope();\n if (cached && sameScope(scope, cached.scope)) return cached.api;\n const context = (organizationId: string) =>\n mutationContext(input, scope, organizationId);\n const read: PrincipalMutationRecoveryApi[\"readPendingPrincipalMutation\"] =\n async (organizationId) =>\n scope\n ? readJournaledPrincipalMutation(context(organizationId))\n : null;\n const abandon: PrincipalMutationRecoveryApi[\"abandonPendingPrincipalMutation\"] =\n async (organizationId, mutation, acknowledgeUnknownOutcome) =>\n abandonJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n acknowledgeUnknownOutcome,\n });\n const methods = {\n ...createJournaledPrincipalMutations(input.api, context, dispatch),\n discardUnreadablePrincipalMutation: async (\n organizationId,\n recordId,\n acknowledgeUnknownOutcome,\n ) =>\n discardUnreadableJournaledPrincipalMutation({\n ...context(organizationId),\n recordId,\n acknowledgeUnknownOutcome,\n }),\n readPendingPrincipalMutation: read,\n abandonPendingPrincipalMutation: abandon,\n recoverPendingPrincipalMutation: async (organizationId) => {\n await recoverJournaledPrincipalMutation({\n ...context(organizationId),\n submit: (mutation) =>\n dispatch({ reportErrors: false }, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n input.api,\n organizationId,\n mutation,\n dispatchOptions,\n ),\n ),\n });\n },\n } satisfies MutationOverrides;\n const api = bindMutationMethods(input.api, methods);\n cached = { scope, api };\n return api;\n },\n };\n}\n\nfunction bindMutationMethods(\n api: ApiClient,\n methods: MutationOverrides,\n): PrincipalMutationApi {\n const boundMethods = new Map<\n PropertyKey,\n { source: unknown; bound: unknown }\n >();\n const bound = new Proxy(api, {\n get(target, property) {\n if (Object.hasOwn(methods, property))\n return Reflect.get(methods, property);\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const previous = boundMethods.get(property);\n if (previous?.source === value) return previous.bound;\n const bound = value.bind(target);\n boundMethods.set(property, { source: value, bound });\n return bound;\n },\n });\n // The checked overrides supply the signatures; verify their presence through\n // the reflective boundary before exposing the extended API to callers.\n if (!hasRecoveryMethods(bound))\n throw new Error(\"Principal mutation recovery methods are unavailable\");\n return bound;\n}\n\nfunction hasRecoveryMethods(api: ApiClient): api is PrincipalMutationApi {\n return (\n typeof Reflect.get(api, \"readPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"recoverPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"abandonPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"discardUnreadablePrincipalMutation\") === \"function\"\n );\n}\n"]}
1
+ {"version":3,"file":"principalMutationApi.js","sourceRoot":"","sources":["principalMutationApi.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAClF,OAAO,EACL,iCAAiC,EACjC,2CAA2C,EAE3C,8BAA8B,GAC/B,MAAM,qFAAqF,CAAC;AAC7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C,kBAAkB,CAAC,KAAK,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAc;IACxC,OAAO,CACL,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,8BAA8B,CAAC,KAAK,UAAU;QACtE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,oCAAoC,CAAC,KAAK,UAAU,CAC7E,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { recoverJournaledPrincipalMutation } from \"../../workflows/organizations\";\nimport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n type PrincipalMutationRecoveryApi,\n readJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutations/principalMutationJournalManagement\";\nimport { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\nimport {\n createJournaledPrincipalMutations,\n dispatchAuthoredPrincipalMutation,\n type JournaledPrincipalMutationMethods,\n} from \"./principalMutationDispatch\";\n\nexport interface PrincipalMutationRuntimeScope {\n readonly database: object;\n readonly execSql: ExecSql;\n readonly generation: number;\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}\n\nfunction sameScope(\n current: PrincipalMutationRuntimeScope | null,\n bound: PrincipalMutationRuntimeScope | null,\n): boolean {\n if (!current || !bound) return current === bound;\n return (\n current.database === bound.database &&\n current.execSql === bound.execSql &&\n current.generation === bound.generation &&\n current.identityTrustDomain === bound.identityTrustDomain &&\n current.signingFingerprint === bound.signingFingerprint &&\n current.signingKeyPair === bound.signingKeyPair &&\n current.userId === bound.userId\n );\n}\n\nexport type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;\ntype MutationOverrides = JournaledPrincipalMutationMethods &\n PrincipalMutationRecoveryApi;\n\ninterface PrincipalMutationApiCustodyInput {\n readonly api: ApiClient;\n readonly readScope: () => PrincipalMutationRuntimeScope | null;\n readonly principalMutationTimeoutMs?: number | undefined;\n}\n\nfunction mutationContext(\n input: PrincipalMutationApiCustodyInput,\n scope: PrincipalMutationRuntimeScope | null,\n organizationId: string,\n) {\n if (!scope)\n throw new Error(\n \"Principal mutations require an authenticated signing identity, a trusted API origin and durable local storage\",\n );\n return {\n execSql: scope.execSql,\n signingKeyPair: scope.signingKeyPair,\n scope: {\n identityTrustDomain: scope.identityTrustDomain,\n organizationId,\n signingFingerprint: scope.signingFingerprint,\n userId: scope.userId,\n },\n stillCurrent: () => sameScope(input.readScope(), scope),\n };\n}\n\n/** Keep API methods bound to their real receiver and journal principal policy and group lifecycle writes. */\nexport function createPrincipalMutationApiCustody(\n input: PrincipalMutationApiCustodyInput,\n) {\n const dispatch = createPrincipalMutationDispatcher(\n input.principalMutationTimeoutMs,\n );\n let cached: {\n scope: PrincipalMutationRuntimeScope | null;\n api: PrincipalMutationApi;\n } | null = null;\n return {\n bind(): PrincipalMutationApi {\n const scope = input.readScope();\n if (cached && sameScope(scope, cached.scope)) return cached.api;\n const context = (organizationId: string) =>\n mutationContext(input, scope, organizationId);\n const read: PrincipalMutationRecoveryApi[\"readPendingPrincipalMutation\"] =\n async (organizationId) =>\n scope\n ? readJournaledPrincipalMutation(context(organizationId))\n : null;\n const abandon: PrincipalMutationRecoveryApi[\"abandonPendingPrincipalMutation\"] =\n async (organizationId, mutation, acknowledgeUnknownOutcome) =>\n abandonJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n acknowledgeUnknownOutcome,\n });\n const methods = {\n ...createJournaledPrincipalMutations(input.api, context, dispatch),\n discardUnreadablePrincipalMutation: async (\n organizationId,\n recordId,\n acknowledgeUnknownOutcome,\n ) =>\n discardUnreadableJournaledPrincipalMutation({\n ...context(organizationId),\n recordId,\n acknowledgeUnknownOutcome,\n }),\n readPendingPrincipalMutation: read,\n abandonPendingPrincipalMutation: abandon,\n recoverPendingPrincipalMutation: async (organizationId) => {\n await recoverJournaledPrincipalMutation({\n ...context(organizationId),\n submit: (mutation) =>\n dispatch({ reportErrors: false }, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n input.api,\n organizationId,\n mutation,\n dispatchOptions,\n ),\n ),\n });\n },\n } satisfies MutationOverrides;\n const api = bindMutationMethods(input.api, methods);\n cached = { scope, api };\n return api;\n },\n };\n}\n\nfunction bindMutationMethods(\n api: ApiClient,\n methods: MutationOverrides,\n): PrincipalMutationApi {\n const boundMethods = new Map<\n PropertyKey,\n { source: unknown; bound: unknown }\n >();\n const bound = new Proxy(api, {\n get(target, property) {\n if (Object.hasOwn(methods, property))\n return Reflect.get(methods, property);\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const previous = boundMethods.get(property);\n if (previous?.source === value) return previous.bound;\n const bound = value.bind(target);\n boundMethods.set(property, { source: value, bound });\n return bound;\n },\n });\n // The checked overrides supply the signatures; verify their presence through\n // the reflective boundary before exposing the extended API to callers.\n if (!hasRecoveryMethods(bound))\n throw new Error(\"Principal mutation recovery methods are unavailable\");\n return bound;\n}\n\nfunction hasRecoveryMethods(api: ApiClient): api is PrincipalMutationApi {\n return (\n typeof Reflect.get(api, \"readPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"recoverPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"abandonPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"discardUnreadablePrincipalMutation\") === \"function\"\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { isCommitOrganizationGroupPolicyResponse, isCreateOrganizationGroupResponse, isDeleteOrganizationGroupResponse, isPrincipalPolicyMutationResponse, } from "../../internal/validators/response/index.js";
2
- import { submitJournaledPrincipalMutation, } from "../../workflows/organizations/principalMutations/principalMutationJournalSession.js";
2
+ import { submitJournaledPrincipalMutation, } from "../../workflows/organizations/index.js";
3
3
  /** Dispatch the authenticated operation, with no application planning callback. */
4
4
  export function dispatchAuthoredPrincipalMutation(api, organizationId, mutation, options = {}) {
5
5
  switch (mutation.kind) {
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationDispatch.js","sourceRoot":"","sources":["principalMutationDispatch.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EACjC,iCAAiC,EACjC,iCAAiC,GAClC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAEL,gCAAgC,GACjC,MAAM,kFAAkF,CAAC;AAiB1F,mFAAmF;AACnF,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,cAAsB,EACtB,QAAmC,EACnC,UAAgC,EAAE;IAElC,QAAQ,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,wBAAwB,CACjC,cAAc,EACd,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,UAAU;YACb,OAAO,GAAG,CAAC,mCAAmC,CAC5C,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ;YACE,OAAO,mBAAmB,CAAC,QAAQ,CAAC,CAAC;IACzC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ions,\n} from \"@tearleads/api-client\";\nimport {\n isCommitOrganizationGroupPolicyResponse,\n isCreateOrganizationGroupResponse,\n isDeleteOrganizationGroupResponse,\n isPrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport type { AuthoredPrincipalMutation } from \"../../data/principals/principalMutationJournal\";\nimport {\n type PrincipalMutationJournalContext,\n submitJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutations/principalMutationJournalSession\";\nimport type { PrincipalMutationResponse } from \"../../workflows/organizations/principalMutations/principalOperationReceipt\";\n\nimport type { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\n\nexport type JournaledPrincipalMutationMethods = Pick<\n ApiClient,\n | \"commitOrganizationGroupPolicy\"\n | \"commitOrganizationGroupPolicyResult\"\n | \"createOrganizationGroup\"\n | \"createOrganizationGroupResult\"\n | \"deleteOrganizationGroup\"\n | \"deleteOrganizationGroupResult\"\n | \"putPrincipalPolicy\"\n | \"putPrincipalPolicyResult\"\n>;\n\n/** Dispatch the authenticated operation, with no application planning callback. */\nexport function dispatchAuthoredPrincipalMutation(\n api: ApiClient,\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n options: RequestResultOptions = {},\n): Promise<RequestResult<PrincipalMutationResponse>> {\n switch (mutation.kind) {\n case \"organization\":\n return api.putPrincipalPolicyResult(\n \"organization\",\n organizationId,\n mutation.request,\n options,\n );\n case \"group-create\":\n return api.createOrganizationGroupResult(\n organizationId,\n mutation.request,\n options,\n );\n case \"group-delete\":\n return api.deleteOrganizationGroupResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n case \"compound\":\n return api.commitOrganizationGroupPolicyResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n default:\n return unsupportedMutation(mutation);\n }\n}\n\nfunction unsupportedMutation(_mutation: never): never {\n throw new Error(\"Unsupported principal mutation operation\");\n}\n\nexport function createJournaledPrincipalMutations(\n api: ApiClient,\n context: (\n organizationId: string,\n ) => Omit<PrincipalMutationJournalContext, \"submit\">,\n dispatch: ReturnType<typeof createPrincipalMutationDispatcher>,\n): JournaledPrincipalMutationMethods {\n async function submit<T extends PrincipalMutationResponse>(\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n validator: (value: unknown) => value is T,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<T>> {\n const result = await submitJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n submit: (saved) =>\n dispatch(options, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n api,\n organizationId,\n saved,\n dispatchOptions,\n ),\n ),\n });\n if (!result.ok) return result;\n // The session already verified this operation before clearing its row.\n // This check narrows the union for each existing public API signature.\n if (!validator(result.data))\n throw new Error(\"Unexpected principal receipt operation\");\n return { ok: true, data: result.data };\n }\n const commit: ApiClient[\"commitOrganizationGroupPolicyResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"compound\", groupId, request },\n isCommitOrganizationGroupPolicyResponse,\n options,\n );\n const create: ApiClient[\"createOrganizationGroupResult\"] = (\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-create\", groupId: request.groupId, request },\n isCreateOrganizationGroupResponse,\n options,\n );\n const remove: ApiClient[\"deleteOrganizationGroupResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-delete\", groupId, request },\n isDeleteOrganizationGroupResponse,\n options,\n );\n const put: ApiClient[\"putPrincipalPolicyResult\"] = (\n _type,\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"organization\", groupId: null, request },\n isPrincipalPolicyMutationResponse,\n options,\n );\n return {\n commitOrganizationGroupPolicyResult: commit,\n commitOrganizationGroupPolicy: async (...args) =>\n nullable(await commit(...args)),\n createOrganizationGroupResult: create,\n createOrganizationGroup: async (...args) => nullable(await create(...args)),\n deleteOrganizationGroupResult: remove,\n deleteOrganizationGroup: async (...args) => nullable(await remove(...args)),\n putPrincipalPolicyResult: put,\n putPrincipalPolicy: async (...args) => nullable(await put(...args)),\n };\n}\n\nfunction nullable<T>(result: RequestResult<T>): T | null {\n return result.ok ? result.data : null;\n}\n"]}
1
+ {"version":3,"file":"principalMutationDispatch.js","sourceRoot":"","sources":["principalMutationDispatch.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EACjC,iCAAiC,EACjC,iCAAiC,GAClC,MAAM,gCAAgC,CAAC;AAGxC,OAAO,EAEL,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAgBvC,mFAAmF;AACnF,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,cAAsB,EACtB,QAAmC,EACnC,UAAgC,EAAE;IAElC,QAAQ,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,wBAAwB,CACjC,cAAc,EACd,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,UAAU;YACb,OAAO,GAAG,CAAC,mCAAmC,CAC5C,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ;YACE,OAAO,mBAAmB,CAAC,QAAQ,CAAC,CAAC;IACzC,CAAC;AACH,CAAC;AAED,SAAS,mBAAmB,CAAC,SAAgB;IAC3C,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,OAEoD,EACpD,QAA8D;I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AC1C,iCAAiC,EACjC,OAAO,CACR,CAAC;IACJ,MAAM,GAAG,GAA0C,CACjD,KAAK,EACL,cAAc,EACd,OAAO,EACP,OAAO,EACP,EAAE,CACF,MAAM,CACJ,cAAc,EACd,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAChD,iCAAiC,EACjC,OAAO,CACR,CAAC;IACJ,OAAO;QACL,mCAAmC,EAAE,MAAM;QAC3C,6BAA6B,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAC/C,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QACjC,6BAA6B,EAAE,MAAM;QACrC,uBAAuB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3E,6BAA6B,EAAE,MAAM;QACrC,uBAAuB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3E,wBAAwB,EAAE,GAAG;QAC7B,kBAAkB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;KACpE,CAAC;AACJ,CAAC;AAED,SAAS,QAAQ,CAAI,MAAwB;IAC3C,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AACxC,CAAC","sourcesContent":["import type {\n ApiClient,\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n isCommitOrganizationGroupPolicyResponse,\n isCreateOrganizationGroupResponse,\n isDeleteOrganizationGroupResponse,\n isPrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport type { AuthoredPrincipalMutation } from \"../../data/principals/principalMutationJournal\";\nimport type { PrincipalMutationResponse } from \"../../workflows/organizations\";\nimport {\n type PrincipalMutationJournalContext,\n submitJournaledPrincipalMutation,\n} from \"../../workflows/organizations\";\n\nimport type { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\n\nexport type JournaledPrincipalMutationMethods = Pick<\n ApiClient,\n | \"commitOrganizationGroupPolicy\"\n | \"commitOrganizationGroupPolicyResult\"\n | \"createOrganizationGroup\"\n | \"createOrganizationGroupResult\"\n | \"deleteOrganizationGroup\"\n | \"deleteOrganizationGroupResult\"\n | \"putPrincipalPolicy\"\n | \"putPrincipalPolicyResult\"\n>;\n\n/** Dispatch the authenticated operation, with no application planning callback. */\nexport function dispatchAuthoredPrincipalMutation(\n api: ApiClient,\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n options: RequestResultOptions = {},\n): Promise<RequestResult<PrincipalMutationResponse>> {\n switch (mutation.kind) {\n case \"organization\":\n return api.putPrincipalPolicyResult(\n \"organization\",\n organizationId,\n mutation.request,\n options,\n );\n case \"group-create\":\n return api.createOrganizationGroupResult(\n organizationId,\n mutation.request,\n options,\n );\n case \"group-delete\":\n return api.deleteOrganizationGroupResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n case \"compound\":\n return api.commitOrganizationGroupPolicyResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n default:\n return unsupportedMutation(mutation);\n }\n}\n\nfunction unsupportedMutation(_mutation: never): never {\n throw new Error(\"Unsupported principal mutation operation\");\n}\n\nexport function createJournaledPrincipalMutations(\n api: ApiClient,\n context: (\n organizationId: string,\n ) => Omit<PrincipalMutationJournalContext, \"submit\">,\n dispatch: ReturnType<typeof createPrincipalMutationDispatcher>,\n): JournaledPrincipalMutationMethods {\n async function submit<T extends PrincipalMutationResponse>(\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n validator: (value: unknown) => value is T,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<T>> {\n const result = await submitJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n submit: (saved) =>\n dispatch(options, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n api,\n organizationId,\n saved,\n dispatchOptions,\n ),\n ),\n });\n if (!result.ok) return result;\n // The session already verified this operation before clearing its row.\n // This check narrows the union for each existing public API signature.\n if (!validator(result.data))\n throw new Error(\"Unexpected principal receipt operation\");\n return { ok: true, data: result.data };\n }\n const commit: ApiClient[\"commitOrganizationGroupPolicyResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"compound\", groupId, request },\n isCommitOrganizationGroupPolicyResponse,\n options,\n );\n const create: ApiClient[\"createOrganizationGroupResult\"] = (\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-create\", groupId: request.groupId, request },\n isCreateOrganizationGroupResponse,\n options,\n );\n const remove: ApiClient[\"deleteOrganizationGroupResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-delete\", groupId, request },\n isDeleteOrganizationGroupResponse,\n options,\n );\n const put: ApiClient[\"putPrincipalPolicyResult\"] = (\n _type,\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"organization\", groupId: null, request },\n isPrincipalPolicyMutationResponse,\n options,\n );\n return {\n commitOrganizationGroupPolicyResult: commit,\n commitOrganizationGroupPolicy: async (...args) =>\n nullable(await commit(...args)),\n createOrganizationGroupResult: create,\n createOrganizationGroup: async (...args) => nullable(await create(...args)),\n deleteOrganizationGroupResult: remove,\n deleteOrganizationGroup: async (...args) => nullable(await remove(...args)),\n putPrincipalPolicyResult: put,\n putPrincipalPolicy: async (...args) => nullable(await put(...args)),\n };\n}\n\nfunction nullable<T>(result: RequestResult<T>): T | null {\n return result.ok ? result.data : null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"rootContainerAdoption.js","sourceRoot":"","sources":["rootContainerAdoption.ts"],"names":[],"mappings":"AAmBA,MAAM,UAAU,yBAAyB,CACvC,YAA+C,EAC/C,KAAyC;IAEzC,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC;IACrC,IACE,YAAY,CAAC,cAAc,EAAE,KAAK,KAAK,CAAC,WAAW;QACnD,CAAC,OAAO,CAAC,eAAe;QACxB,OAAO,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC/C,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,EAC/B,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,eAAe,EAAE,CAAC;QAClD,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,mBAAmB,EAAE,CAAC;QACtD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IAC9C,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n} from \"../../workflows/container-contents/runtime\";\nimport type { Session } from \"../session/sessionTypes\";\n\ninterface RootContainerAdoptionDependencies {\n readonly getDomainScope: () => DomainScope;\n readonly session: Pick<\n Session,\n | \"containerId\"\n | \"isAuthenticated\"\n | \"organizationId\"\n | \"setContainerId\"\n | \"userId\"\n >;\n}\n\nexport function adoptSessionRootContainer(\n dependencies: RootContainerAdoptionDependencies,\n input: ContainerContentsRootAdoptionInput,\n): ReturnType<ContainerContentsRootAdopter> {\n const session = dependencies.session;\n if (\n dependencies.getDomainScope() !== input.domainScope ||\n !session.isAuthenticated ||\n session.organizationId !== input.organizationId ||\n session.userId !== input.userId\n ) {\n return false;\n }\n if (session.containerId === input.nextContainerId) {\n return \"already-adopted\";\n }\n if (session.containerId !== input.expectedContainerId) {\n return false;\n }\n\n session.setContainerId(input.nextContainerId);\n return true;\n}\n"]}
1
+ {"version":3,"file":"rootContainerAdoption.js","sourceRoot":"","sources":["rootContainerAdoption.ts"],"names":[],"mappings":"AAmBA,MAAM,UAAU,yBAAyB,CACvC,YAA+C,EAC/C,KAAyC;IAEzC,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC;IACrC,IACE,YAAY,CAAC,cAAc,EAAE,KAAK,KAAK,CAAC,WAAW;QACnD,CAAC,OAAO,CAAC,eAAe;QACxB,OAAO,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC/C,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,EAC/B,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,eAAe,EAAE,CAAC;QAClD,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,mBAAmB,EAAE,CAAC;QACtD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IAC9C,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n} from \"../../workflows/container-contents\";\nimport type { Session } from \"../session/sessionTypes\";\n\ninterface RootContainerAdoptionDependencies {\n readonly getDomainScope: () => DomainScope;\n readonly session: Pick<\n Session,\n | \"containerId\"\n | \"isAuthenticated\"\n | \"organizationId\"\n | \"setContainerId\"\n | \"userId\"\n >;\n}\n\nexport function adoptSessionRootContainer(\n dependencies: RootContainerAdoptionDependencies,\n input: ContainerContentsRootAdoptionInput,\n): ReturnType<ContainerContentsRootAdopter> {\n const session = dependencies.session;\n if (\n dependencies.getDomainScope() !== input.domainScope ||\n !session.isAuthenticated ||\n session.organizationId !== input.organizationId ||\n session.userId !== input.userId\n ) {\n return false;\n }\n if (session.containerId === input.nextContainerId) {\n return \"already-adopted\";\n }\n if (session.containerId !== input.expectedContainerId) {\n return false;\n }\n\n session.setContainerId(input.nextContainerId);\n return true;\n}\n"]}
@@ -4,7 +4,7 @@ import type { PrincipalHistoryProtectionLease } from "../../data/principals/prin
4
4
  import type { DomainScope } from "../../data/shared/domainScope.js";
5
5
  import type { SecurityIncidentReporter } from "../../data/shared/securityIncidents.js";
6
6
  import { type LocalUserIdentityCandidate, type TrustedUserIdentityResolver, type TrustedUserIdentityService } from "../../data/trustedUserIdentity/index.js";
7
- import type { ContainerContentsRootAdopter } from "../../workflows/container-contents/runtime.js";
7
+ import type { ContainerContentsRootAdopter } from "../../workflows/container-contents/index.js";
8
8
  import { type ProvisionedPrincipalHistoryPrimer } from "../../workflows/registration/provisionedPrincipalHistory.js";
9
9
  import type { WorkflowRuntimeGroups, WorkflowRuntimeUtilInput } from "../../workflows/shared/runtimeInput.js";
10
10
  import type { Blobs } from "../blobs/index.js";
@@ -1 +1 @@
1
- {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AAIjG,OAAO,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,EAEhC,sBAAsB,GAGvB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,uCAAuC,GAExC,MAAM,0DAA0D,CAAC;AAWlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAI1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,iCAAiC,GAElC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAqEpE,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AAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../../workflows/container-contents/runtime\";\nimport {\n createProvisionedPrincipalHistoryPrimer,\n type ProvisionedPrincipalHistoryPrimer,\n} from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n identityLinks: Pick<\n TrustedUserIdentityService,\n \"createLink\" | \"verifyLink\" | \"resolvePinned\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedPrincipalHistory: ProvisionedPrincipalHistoryPrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\nfunction localIdentityCandidate(\n identity: Identity,\n): LocalUserIdentityCandidate | null {\n const { encapsulationKeyPair, signingKeyPair } = identity;\n if (!encapsulationKeyPair || !signingKeyPair) return null;\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedPrincipalHistoryPrimer {\n return createProvisionedPrincipalHistoryPrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: readyExecSql,\n getLocalIdentity: () => localIdentityCandidate(dependencies.identity),\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedPrincipalHistory: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
1
+ {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AAIjG,OAAO,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,EAEhC,sBAAsB,GAGvB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,uCAAuC,GAExC,MAAM,0DAA0D,CAAC;AAWlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAI1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,iCAAiC,GAElC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAqEpE,SAAS,wBAAwB,CAC/B,YAAyC,EACzC,cAA4B;IAE5B,OAAO,iCAAiC,CAAC;QACvC,GAAG,EAAE,YAAY,CAAC,GAAG;QACrB,0BAA0B,EAAE,YAAY,CAAC,0BAA0B;QACnE,SAAS,EAAE,GAAG,EAAE;YACd,MAAM,EAAE,cAAc,EAAE,kBAAkB,EAAE,GAAG,YAAY,CAAC,QAAQ,CAAC;YACrE,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,GAAG,YAAY,CAAC,OAAO,CAAC;YACzD,MAAM,mBAAmB,GAAG,YAAY,CAAC,mBAAmB,CAAC;YAC7D,IACE,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MAAM;YACN,KAAK;YACL,KAAK;YACL,IAAI;YACJ,0BAA0B;YAC1B,8BAA8B,EAAE,qBAAqB,EAAE;SACxD,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO;QACL,SAAS,CAAC,WAAW;YACnB,MAAM,EACJ,SAAS,EAAE,UAAU,EACrB,0BAA0B,EAAE,2BAA2B,EACvD,8BAA8B,EAAE,+BAA+B,EAC/D,IAAI,EAAE,YAAY,EAClB,GAAG,KAAK,EACT,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;YAC/B,QAAQ,GAAG,mBAAmB,CAAC,QAAQ,EAAE;gBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAC1B,OAAsB,EACtB,IAAO;IAEP,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../../workflows/container-contents\";\nimport {\n createProvisionedPrincipalHistoryPrimer,\n type ProvisionedPrincipalHistoryPrimer,\n} from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n identityLinks: Pick<\n TrustedUserIdentityService,\n \"createLink\" | \"verifyLink\" | \"resolvePinned\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedPrincipalHistory: ProvisionedPrincipalHistoryPrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\nfunction localIdentityCandidate(\n identity: Identity,\n): LocalUserIdentityCandidate | null {\n const { encapsulationKeyPair, signingKeyPair } = identity;\n if (!encapsulationKeyPair || !signingKeyPair) return null;\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedPrincipalHistoryPrimer {\n return createProvisionedPrincipalHistoryPrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: readyExecSql,\n getLocalIdentity: () => localIdentityCandidate(dependencies.identity),\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedPrincipalHistory: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { resolveOrganizationBillingView } from "../../workflows/organizations/billing.js";
1
+ import { resolveOrganizationBillingView } from "../../workflows/organizations/index.js";
2
2
  import { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "../../workflows/organizations/provisioning/organizationProvisioningAttempt.js";
3
3
  import { verifyOrganizationReplacementResponse } from "../../workflows/organizations/provisioning/organizationReplacementVerification.js";
4
4
  import { clearRemoteSyncState } from "../../workflows/sync/index.js";
@@ -1 +1 @@
1
- {"version":3,"file":"sessionPurgeRecovery.js","sourceRoot":"","sources":["sessionPurgeRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,uCAAuC,CAAC;AACvF,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,4EAA4E,CAAC;AACpF,OAAO,EAAE,qCAAqC,EAAE,MAAM,gFAAgF,CAAC;AACvI,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,EAAE,8CAA8C,EAAE,MAAM,yBAAyB,CAAC;AAyBzF,SAAS,yBAAyB,CAChC,WAA4C,EAC5C,OAAiE;IAEjE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,CAAC,8BAA8B,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;QACjE,MAAM,IAAI,8CAA8C,CACtD,WAAW,CAAC,cAAc,EAC1B,OAAO,CAAC,MAAM,EACd,WAAW,CAAC,WAAW,CACxB,CAAC;IACJ,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,YAA8C,EAC9C,OAAoC,EACpC,cAAsB;IAEtB,MAAM,OAAO,GAAG,YAAY,CAAC,QAAQ,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;IAC7E,MAAM,MAAM,GAAG,MAAM,oBAAoB,CAAC,OAAO,EAAE;QACjD,cAAc;KACf,CAAC,CAAC;IACH,YAAY,CAAC,GAAG,CAAC,2BAA2B,EAAE,CAAC;IAC/C,IAA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IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACtC,MAAM,oBAAoB,GACxB,MAAM,YAAY,CAAC,GAAG,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAC;IACjE,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACtC,0BAA0B,CACxB,oBAAoB,EACpB,WAAW,EACX,cAAc,EACd,MAAM,EACN,gBAAgB,CAAC,cAAc,CAChC,CAAC;IACF,MAAM,cAAc,GAAG,MAAM,qCAAqC,CAAC;QACjE,SAAS,EAAE,iBAAiB;QAC5B,OAAO;QACP,sBAAsB,EAAE,cAAc;QACtC,MAAM;KACP,CAAC,CAAC;IACH,IAAI,CAAC,cAAc,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACzD,YAAY,CAAC,GAAG,CAAC,2BAA2B,EAAE,CAAC;IAC/C,OAAO,CAAC,UAAU,CAAC;QACjB,WAAW,EAAE,WAAW,CAAC,WAAW;QACpC,qBAAqB,EAAE,WAAW,CAAC,cAAc;QACjD,cAAc,EAAE,WAAW,CAAC,cAAc;KAC3C,CAAC,CAAC;IACH,YAAY,CAAC,GAAG,CACd,iCAAiC,WAAW,CAAC,cAAc,GAAG,CAC/D,CAAC;IACF,OAAO;QACL,GAAG,WAAW;QACd,sBAAsB,EAAE,cAAc;QACtC,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { resolveOrganizationBillingView } from \"../../workflows/organizations/billing\";\nimport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"../../workflows/organizations/provisioning/organizationProvisioningAttempt\";\nimport { verifyOrganizationReplacementResponse } from \"../../workflows/organizations/provisioning/organizationReplacementVerification\";\nimport { clearRemoteSyncState } from \"../../workflows/sync\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport { PurgedOrganizationRecoveryBillingRequiredError } from \"./sessionRecoveryErrors\";\nimport type {\n CreateOrganizationOptions,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionRecoverOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionPurgeRecoveryDependencies {\n api: Pick<ApiClient, \"clearWriterProjectionCaches\">;\n database: Pick<Database, \"requireExecSql\">;\n identity: Pick<Identity, \"snapshot\">;\n log: (message: string) => void;\n}\n\ninterface SessionPurgeRecoveryContext {\n createOrganization: (\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n ) => Promise<SessionCreateOrganizationResult | null>;\n organizationId: string | null;\n setContext: (context: SessionContext) => void;\n userId: string | null;\n}\n\nfunction requireReplacementCanSync(\n replacement: SessionCreateOrganizationResult,\n billing: Awaited<ReturnType<ApiClient[\"getOrganizationBilling\"]>>,\n): void {\n if (!billing) {\n throw new Error(\"Replacement organization billing could not be loaded\");\n }\n if (!resolveOrganizationBillingView(billing, Date.now()).canSync) {\n throw new PurgedOrganizationRecoveryBillingRequiredError(\n replacement.organizationId,\n billing.status,\n replacement.containerId,\n );\n }\n}\n\nexport async function clearSessionRemoteSyncState(\n dependencies: SessionPurgeRecoveryDependencies,\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n) {\n const execSql = dependencies.database.requireExecSql(\"clearRemoteSyncState\");\n const result = await clearRemoteSyncState(execSql, {\n organizationId,\n });\n dependencies.api.clearWriterProjectionCaches();\n if (session.organizationId === organizationId) {\n session.setContext({ containerId: null, organizationId: null });\n }\n dependencies.log(\"Remote sync state cleared\");\n return result;\n}\n\nfunction verifyFinalizedReplacement(\n finalizedReplacement: Awaited<ReturnType<ApiClient[\"createOrganization\"]>>,\n replacement: SessionCreateOrganizationResult,\n replacesOrganizationId: string,\n userId: string,\n signingKeyPair: Identity[\"snapshot\"][\"signingKeyPair\"],\n): void {\n if (\n !finalizedReplacement ||\n finalizedReplacement.organizationId !== replacement.organizationId ||\n finalizedReplacement.rootContainerId !== replacement.containerId ||\n finalizedReplacement.userId !== userId\n ) {\n throw new Error(\"Organization replacement finalization was inconsistent\");\n }\n if (!signingKeyPair) {\n throw new Error(\n \"Organization replacement requires the current signing identity\",\n );\n }\n verifyOrganizationReplacementResponse({\n replacesOrganizationId,\n response: finalizedReplacement,\n signingPublicKey: signingKeyPair.signingPublicKey,\n userId,\n });\n}\n\nexport async function recoverPurgedSessionOrganization(\n dependencies: SessionPurgeRecoveryDependencies & {\n api: Pick<\n ApiClient,\n | \"clearWriterProjectionCaches\"\n | \"createOrganization\"\n | \"getOrganizationBilling\"\n >;\n },\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n options: CreateOrganizationOptions | undefined,\n): Promise<SessionRecoverOrganizationResult | null> {\n const identitySnapshot = dependencies.identity.snapshot;\n const sessionOrganizationId = session.organizationId;\n const userId = session.userId;\n if (!userId) {\n throw new Error(\"Purged organization recovery requires a current user\");\n }\n const isRecoveryCurrent = () =>\n dependencies.identity.snapshot === identitySnapshot &&\n session.organizationId === sessionOrganizationId &&\n session.userId === userId;\n const billing = await dependencies.api.getOrganizationBilling(organizationId);\n if (billing?.status !== \"purged\") {\n throw new Error(\n `Organization ${organizationId} cannot be recovered before its purge finishes`,\n );\n }\n if (!isRecoveryCurrent()) return null;\n const replacement = await session.createOrganization(options, organizationId);\n if (!replacement) return null;\n if (!isRecoveryCurrent()) return null;\n const replacementBilling = await dependencies.api.getOrganizationBilling(\n replacement.organizationId,\n );\n if (!isRecoveryCurrent()) return null;\n requireReplacementCanSync(replacement, replacementBilling);\n const execSql = dependencies.database.requireExecSql(\n \"recoverPurgedOrganization\",\n );\n const reset = await clearRemoteSyncState(\n execSql,\n {\n organizationId,\n replacement: {\n organizationId: replacement.organizationId,\n rootContainerId: replacement.containerId,\n },\n },\n isRecoveryCurrent,\n );\n if (!isRecoveryCurrent()) return null;\n const finalizationRequest =\n await loadOrganizationReplacementFinalizationRequest({\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!isRecoveryCurrent()) return null;\n const finalizedReplacement =\n await dependencies.api.createOrganization(finalizationRequest);\n if (!isRecoveryCurrent()) return null;\n verifyFinalizedReplacement(\n finalizedReplacement,\n replacement,\n organizationId,\n userId,\n identitySnapshot.signingKeyPair,\n );\n const attemptRemoved = await removeOrganizationProvisioningAttempt({\n canCommit: isRecoveryCurrent,\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!attemptRemoved || !isRecoveryCurrent()) return null;\n dependencies.api.clearWriterProjectionCaches();\n session.setContext({\n containerId: replacement.containerId,\n defaultOrganizationId: replacement.organizationId,\n organizationId: replacement.organizationId,\n });\n dependencies.log(\n `Purged organization replaced (${replacement.organizationId})`,\n );\n return {\n ...replacement,\n replacedOrganizationId: organizationId,\n reset,\n };\n}\n"]}
1
+ {"version":3,"file":"sessionPurgeRecovery.js","sourceRoot":"","sources":["sessionPurgeRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,4EAA4E,CAAC;AACpF,OAAO,EAAE,qCAAqC,EAAE,MAAM,gFAAgF,CAAC;AACvI,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,EAAE,8CAA8C,EAAE,MAAM,yBAAyB,CAAC;AAyBzF,SAAS,yBAAyB,CAChC,WAA4C,EAC5C,OAAiE;IAEjE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,CAAC,8BAA8B,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;QACjE,MAAM,IAAI,8CAA8C,CACtD,WAAW,CAAC,cAAc,EAC1B,OAAO,CAAC,MAAM,EACd,WAAW,CAAC,WAAW,CACxB,CAAC;IACJ,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,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ACX,cAAc,EAAE,WAAW,CAAC,cAAc;YAC1C,eAAe,EAAE,WAAW,CAAC,WAAW;SACzC;KACF,EACD,iBAAiB,CAClB,CAAC;IACF,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACtC,MAAM,mBAAmB,GACvB,MAAM,8CAA8C,CAAC;QACnD,OAAO;QACP,sBAAsB,EAAE,cAAc;QACtC,MAAM;KACP,CAAC,CAAC;IACL,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACtC,MAAM,oBAAoB,GACxB,MAAM,YAAY,CAAC,GAAG,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAC;IACjE,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACtC,0BAA0B,CACxB,oBAAoB,EACpB,WAAW,EACX,cAAc,EACd,MAAM,EACN,gBAAgB,CAAC,cAAc,CAChC,CAAC;IACF,MAAM,cAAc,GAAG,MAAM,qCAAqC,CAAC;QACjE,SAAS,EAAE,iBAAiB;QAC5B,OAAO;QACP,sBAAsB,EAAE,cAAc;QACtC,MAAM;KACP,CAAC,CAAC;IACH,IAAI,CAAC,cAAc,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACzD,YAAY,CAAC,GAAG,CAAC,2BAA2B,EAAE,CAAC;IAC/C,OAAO,CAAC,UAAU,CAAC;QACjB,WAAW,EAAE,WAAW,CAAC,WAAW;QACpC,qBAAqB,EAAE,WAAW,CAAC,cAAc;QACjD,cAAc,EAAE,WAAW,CAAC,cAAc;KAC3C,CAAC,CAAC;IACH,YAAY,CAAC,GAAG,CACd,iCAAiC,WAAW,CAAC,cAAc,GAAG,CAC/D,CAAC;IACF,OAAO;QACL,GAAG,WAAW;QACd,sBAAsB,EAAE,cAAc;QACtC,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { resolveOrganizationBillingView } from \"../../workflows/organizations\";\nimport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"../../workflows/organizations/provisioning/organizationProvisioningAttempt\";\nimport { verifyOrganizationReplacementResponse } from \"../../workflows/organizations/provisioning/organizationReplacementVerification\";\nimport { clearRemoteSyncState } from \"../../workflows/sync\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport { PurgedOrganizationRecoveryBillingRequiredError } from \"./sessionRecoveryErrors\";\nimport type {\n CreateOrganizationOptions,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionRecoverOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionPurgeRecoveryDependencies {\n api: Pick<ApiClient, \"clearWriterProjectionCaches\">;\n database: Pick<Database, \"requireExecSql\">;\n identity: Pick<Identity, \"snapshot\">;\n log: (message: string) => void;\n}\n\ninterface SessionPurgeRecoveryContext {\n createOrganization: (\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n ) => Promise<SessionCreateOrganizationResult | null>;\n organizationId: string | null;\n setContext: (context: SessionContext) => void;\n userId: string | null;\n}\n\nfunction requireReplacementCanSync(\n replacement: SessionCreateOrganizationResult,\n billing: Awaited<ReturnType<ApiClient[\"getOrganizationBilling\"]>>,\n): void {\n if (!billing) {\n throw new Error(\"Replacement organization billing could not be loaded\");\n }\n if (!resolveOrganizationBillingView(billing, Date.now()).canSync) {\n throw new PurgedOrganizationRecoveryBillingRequiredError(\n replacement.organizationId,\n billing.status,\n replacement.containerId,\n );\n }\n}\n\nexport async function clearSessionRemoteSyncState(\n dependencies: SessionPurgeRecoveryDependencies,\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n) {\n const execSql = dependencies.database.requireExecSql(\"clearRemoteSyncState\");\n const result = await clearRemoteSyncState(execSql, {\n organizationId,\n });\n dependencies.api.clearWriterProjectionCaches();\n if (session.organizationId === organizationId) {\n session.setContext({ containerId: null, organizationId: null });\n }\n dependencies.log(\"Remote sync state cleared\");\n return result;\n}\n\nfunction verifyFinalizedReplacement(\n finalizedReplacement: Awaited<ReturnType<ApiClient[\"createOrganization\"]>>,\n replacement: SessionCreateOrganizationResult,\n replacesOrganizationId: string,\n userId: string,\n signingKeyPair: Identity[\"snapshot\"][\"signingKeyPair\"],\n): void {\n if (\n !finalizedReplacement ||\n finalizedReplacement.organizationId !== replacement.organizationId ||\n finalizedReplacement.rootContainerId !== replacement.containerId ||\n finalizedReplacement.userId !== userId\n ) {\n throw new Error(\"Organization replacement finalization was inconsistent\");\n }\n if (!signingKeyPair) {\n throw new Error(\n \"Organization replacement requires the current signing identity\",\n );\n }\n verifyOrganizationReplacementResponse({\n replacesOrganizationId,\n response: finalizedReplacement,\n signingPublicKey: signingKeyPair.signingPublicKey,\n userId,\n });\n}\n\nexport async function recoverPurgedSessionOrganization(\n dependencies: SessionPurgeRecoveryDependencies & {\n api: Pick<\n ApiClient,\n | \"clearWriterProjectionCaches\"\n | \"createOrganization\"\n | \"getOrganizationBilling\"\n >;\n },\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n options: CreateOrganizationOptions | undefined,\n): Promise<SessionRecoverOrganizationResult | null> {\n const identitySnapshot = dependencies.identity.snapshot;\n const sessionOrganizationId = session.organizationId;\n const userId = session.userId;\n if (!userId) {\n throw new Error(\"Purged organization recovery requires a current user\");\n }\n const isRecoveryCurrent = () =>\n dependencies.identity.snapshot === identitySnapshot &&\n session.organizationId === sessionOrganizationId &&\n session.userId === userId;\n const billing = await dependencies.api.getOrganizationBilling(organizationId);\n if (billing?.status !== \"purged\") {\n throw new Error(\n `Organization ${organizationId} cannot be recovered before its purge finishes`,\n );\n }\n if (!isRecoveryCurrent()) return null;\n const replacement = await session.createOrganization(options, organizationId);\n if (!replacement) return null;\n if (!isRecoveryCurrent()) return null;\n const replacementBilling = await dependencies.api.getOrganizationBilling(\n replacement.organizationId,\n );\n if (!isRecoveryCurrent()) return null;\n requireReplacementCanSync(replacement, replacementBilling);\n const execSql = dependencies.database.requireExecSql(\n \"recoverPurgedOrganization\",\n );\n const reset = await clearRemoteSyncState(\n execSql,\n {\n organizationId,\n replacement: {\n organizationId: replacement.organizationId,\n rootContainerId: replacement.containerId,\n },\n },\n isRecoveryCurrent,\n );\n if (!isRecoveryCurrent()) return null;\n const finalizationRequest =\n await loadOrganizationReplacementFinalizationRequest({\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!isRecoveryCurrent()) return null;\n const finalizedReplacement =\n await dependencies.api.createOrganization(finalizationRequest);\n if (!isRecoveryCurrent()) return null;\n verifyFinalizedReplacement(\n finalizedReplacement,\n replacement,\n organizationId,\n userId,\n identitySnapshot.signingKeyPair,\n );\n const attemptRemoved = await removeOrganizationProvisioningAttempt({\n canCommit: isRecoveryCurrent,\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!attemptRemoved || !isRecoveryCurrent()) return null;\n dependencies.api.clearWriterProjectionCaches();\n session.setContext({\n containerId: replacement.containerId,\n defaultOrganizationId: replacement.organizationId,\n organizationId: replacement.organizationId,\n });\n dependencies.log(\n `Purged organization replaced (${replacement.organizationId})`,\n );\n return {\n ...replacement,\n replacedOrganizationId: organizationId,\n reset,\n };\n}\n"]}
@@ -1,8 +1,7 @@
1
1
  import { BLOB_CONTENT_KEY_WRAP_SUITE, wrapContentKey, } from "../../../internal/crypto/index.js";
2
2
  import { bytesToBase64 } from "../../../internal/encoding/index.js";
3
- import { assertDocumentKekPathsCurrent } from "../../documents/shared/containerKek/containerKekCurrency.js";
4
- import { readLinkedContainerIdsFromDocumentManifest, unwrapContainerKekPath, verifiedDocumentWrapTargets, } from "../../documents/shared/projection/index.js";
5
- import { unwrapContentKeyTargetForKind } from "../../documents/shared/projection/projectionContentKeys.js";
3
+ import { assertDocumentKekPathsCurrent } from "../../documents/shared/containerKek/index.js";
4
+ import { readLinkedContainerIdsFromDocumentManifest, unwrapContainerKekPath, unwrapContentKeyTargetForKind, verifiedDocumentWrapTargets, } from "../../documents/shared/projection/index.js";
6
5
  import { assertEqualBytes, normalizeDocumentKekTargetResponse, } from "../../documents/shared/readers.js";
7
6
  import { projectionVerificationOptions, } from "../../documents/shared/types.js";
8
7
  import { documentContainerProjections } from "../../keyingProjectionVerification/document/documentContainerProjections.js";
@@ -1 +1 @@
1
- {"version":3,"file":"projection.js","sourceRoot":"","sources":["projection.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAE3B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EACL,0CAA0C,EAC1C,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,6BAA6B,EAAE,MAAM,yDAAyD,CAAC;AACxG,OAAO,EACL,gBAAgB,EAChB,kCAAkC,GACnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAEL,6BAA6B,GAC9B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,4BAA4B,EAAE,MAAM,0EAA0E,CAAC;AAExH,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAG5C,SAAS,cAAc,CACrB,KAAgD,EAChD,OAA4C;IAE5C,OAAO,eAAe,CACpB,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACvB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,GAAG,MAAM;KACV,CAAC,CAAC,CACJ,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,6CAA6C,CAAC,KAI7D;IACC,OAAO,cAAc,CACnB,KAAK,EACL,2BAA2B,CAAC;QAC1B,kBAAkB,EAAE,0CAA0C,CAC5D,KAAK,CAAC,gBAAgB,CACvB;QACD,aAAa,EAAE,kCAAkC,CAC/C,KAAK,CAAC,gBAAgB,CA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AC","sourcesContent":["import {\n BLOB_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { BlobContentKeyTargetEnvelopeRequest } from \"@tearleads/validators/request\";\nimport type {\n BlobContentKeyBundleResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentKekPathsCurrent } from \"../../documents/shared/containerKek/containerKekCurrency\";\nimport {\n readLinkedContainerIdsFromDocumentManifest,\n unwrapContainerKekPath,\n verifiedDocumentWrapTargets,\n} from \"../../documents/shared/projection\";\nimport { unwrapContentKeyTargetForKind } from \"../../documents/shared/projection/projectionContentKeys\";\nimport {\n assertEqualBytes,\n normalizeDocumentKekTargetResponse,\n} from \"../../documents/shared/readers\";\nimport {\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../documents/shared/types\";\nimport { documentContainerProjections } from \"../../keyingProjectionVerification/document/documentContainerProjections\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { sortBlobTargets } from \"./readers\";\nimport type { BlobContentKeyTarget, BlobEncryptedBytesHeader } from \"./types\";\n\nfunction blobTargetsFor(\n input: { bindingId: string; documentId: string },\n targets: readonly DocumentContentKeyTarget[],\n): BlobContentKeyTarget[] {\n return sortBlobTargets(\n targets.map((target) => ({\n bindingId: input.bindingId,\n documentId: input.documentId,\n ...target,\n })),\n );\n}\n\n/**\n * The targets a blob content key may be wrapped to: the verified current\n * heads of the document's linked containers. The server list only names which\n * containers a bundle must cover.\n */\nexport function verifiedBlobWrapTargetsFromDocumentProjection(input: {\n bindingId: string;\n documentId: string;\n writerProjection: DocumentWriterProjectionResponse;\n}): BlobContentKeyTarget[] {\n return blobTargetsFor(\n input,\n verifiedDocumentWrapTargets({\n linkedContainerIds: readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n ),\n serverTargets: normalizeDocumentKekTargetResponse(\n input.writerProjection.documentKekTargets,\n ),\n writerProjection: input.writerProjection,\n }),\n );\n}\n\n// Not collectContainerKeksForDocumentSync: the blob upload retry classifier\n// keys on the bare \"Container writer projection KEK… could not be unwrapped\"\n// message, which the sync collector would wrap with document-sync context.\nasync function collectContainerKeks(\n input: {\n execSql?: ExecSql | undefined;\n secretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<ReadonlyMap<string, Uint8Array>> {\n const keksByEpochId = new Map<string, Uint8Array>();\n\n for (const projection of documentContainerProjections(\n input.writerProjection,\n )) {\n const projectionKeks = await unwrapContainerKekPath({\n execSql: input.execSql,\n projection,\n secretKey: input.secretKey,\n ...projectionVerificationOptions(input),\n });\n\n for (const [containerKeyEpochId, keyMaterial] of projectionKeks) {\n const existing = keksByEpochId.get(containerKeyEpochId);\n if (existing) {\n assertEqualBytes(\n existing,\n keyMaterial,\n \"Blob writer projection contains conflicting container KEKs\",\n );\n continue;\n }\n keksByEpochId.set(containerKeyEpochId, keyMaterial);\n }\n }\n\n return keksByEpochId;\n}\n\nexport async function wrapBlobContentKey(\n input: {\n blobId: string;\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n execSql?: ExecSql | undefined;\n secretKey: Uint8Array;\n targets: readonly BlobContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<BlobContentKeyTargetEnvelopeRequest[]> {\n assertDocumentKekPathsCurrent(\n input.writerProjection,\n new Set(input.targets.map((target) => target.containerId)),\n );\n const keksByEpochId = await collectContainerKeks({\n execSql: input.execSql,\n secretKey: input.secretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n\n return Promise.all(\n input.targets.map(async (target) => {\n const targetKek = keksByEpochId.get(target.containerKeyEpochId);\n if (!targetKek) {\n throw new Error(\n `Blob target KEK could not be unwrapped for ${target.containerKeyEpochId}`,\n );\n }\n\n const wrapped = await wrapContentKey(input.contentKey, targetKek, {\n kind: \"Blob\",\n objectId: input.blobId,\n contentKeyEpoch: input.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n }),\n );\n}\n\nasync function unwrapBlobContentKeyTarget(input: {\n blobId: string;\n containerKek: Uint8Array;\n contentKeyEpoch: number;\n envelope: BlobContentKeyTargetEnvelopeRequest;\n}): Promise<Uint8Array> {\n return unwrapContentKeyTargetForKind({\n containerKek: input.containerKek,\n contentKeyEpoch: input.contentKeyEpoch,\n envelope: input.envelope,\n kind: \"Blob\",\n objectId: input.blobId,\n });\n}\n\nexport async function unwrapBlobContentKey(\n input: {\n /** The blob being read; its wraps must be sealed to it. */\n blobId: string;\n contentKeyBundle: BlobContentKeyBundleResponse;\n documentId: string;\n encrypted: BlobEncryptedBytesHeader;\n execSql?: ExecSql | undefined;\n expectedBindingId: string;\n secretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<Uint8Array> {\n const keksByEpochId = await collectContainerKeks({\n execSql: input.execSql,\n secretKey: input.secretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n let contentKey: Uint8Array | null = null;\n const attachmentTargets = input.contentKeyBundle.targets.filter(\n (envelope) =>\n envelope.bindingId === input.expectedBindingId &&\n envelope.documentId === input.documentId,\n );\n\n if (attachmentTargets.length === 0) {\n throw new Error(\"Blob content-key bundle is missing attachment target\");\n }\n\n for (const envelope of attachmentTargets) {\n const containerKek = keksByEpochId.get(envelope.containerKeyEpochId);\n if (!containerKek) {\n continue;\n }\n const unwrapped = await unwrapBlobContentKeyTarget({\n blobId: input.blobId,\n containerKek,\n contentKeyEpoch: input.contentKeyBundle.contentKeyEpoch,\n envelope,\n });\n if (contentKey) {\n assertEqualBytes(\n contentKey,\n unwrapped,\n \"Blob content-key targets unwrap to conflicting keys\",\n );\n continue;\n }\n contentKey = unwrapped;\n }\n\n if (!contentKey) {\n throw new Error(\"Blob content key could not be unwrapped\");\n }\n return contentKey;\n}\n"]}
1
+ {"version":3,"file":"projection.js","sourceRoot":"","sources":["projection.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAE3B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,qCAAqC,CAAC;AACpF,OAAO,EACL,0CAA0C,EAC1C,sBAAsB,EACtB,6BAA6B,EAC7B,2BAA2B,GAC5B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,gBAAgB,EAChB,kCAAkC,GACnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAEL,6BAA6B,GAC9B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,4BAA4B,EAAE,MAAM,0EAA0E,CAAC;AAExH,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAG5C,SAAS,cAAc,CACrB,KAAgD,EAChD,OAA4C;IAE5C,OAAO,eAAe,CACpB,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACvB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,GAAG,MAAM;KACV,CAAC,CAAC,CACJ,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,6CAA6C,CAAC,KAI7D;IACC,OAAO,cAAc,CACnB,KAAK,EACL,2BAA2B,CAAC;QAC1B,kBAAkB,EAAE,0CAA0C,CAC5D,KAAK,CAAC,gBAAgB,CACvB;QACD,aAAa,EAAE,kCAAkC,CAC/C,KAAK,CAAC,gBAAgB,CAAC,kBAAkB,CAC1C;QACD,gBAAgB,EAAE,KAA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SUITE,\n type DocumentContentKeyTarget,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { BlobContentKeyTargetEnvelopeRequest } from \"@tearleads/validators/request\";\nimport type {\n BlobContentKeyBundleResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentKekPathsCurrent } from \"../../documents/shared/containerKek\";\nimport {\n readLinkedContainerIdsFromDocumentManifest,\n unwrapContainerKekPath,\n unwrapContentKeyTargetForKind,\n verifiedDocumentWrapTargets,\n} from \"../../documents/shared/projection\";\nimport {\n assertEqualBytes,\n normalizeDocumentKekTargetResponse,\n} from \"../../documents/shared/readers\";\nimport {\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../documents/shared/types\";\nimport { documentContainerProjections } from \"../../keyingProjectionVerification/document/documentContainerProjections\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { sortBlobTargets } from \"./readers\";\nimport type { BlobContentKeyTarget, BlobEncryptedBytesHeader } from \"./types\";\n\nfunction blobTargetsFor(\n input: { bindingId: string; documentId: string },\n targets: readonly DocumentContentKeyTarget[],\n): BlobContentKeyTarget[] {\n return sortBlobTargets(\n targets.map((target) => ({\n bindingId: input.bindingId,\n documentId: input.documentId,\n ...target,\n })),\n );\n}\n\n/**\n * The targets a blob content key may be wrapped to: the verified current\n * heads of the document's linked containers. The server list only names which\n * containers a bundle must cover.\n */\nexport function verifiedBlobWrapTargetsFromDocumentProjection(input: {\n bindingId: string;\n documentId: string;\n writerProjection: DocumentWriterProjectionResponse;\n}): BlobContentKeyTarget[] {\n return blobTargetsFor(\n input,\n verifiedDocumentWrapTargets({\n linkedContainerIds: readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n ),\n serverTargets: normalizeDocumentKekTargetResponse(\n input.writerProjection.documentKekTargets,\n ),\n writerProjection: input.writerProjection,\n }),\n );\n}\n\n// Not collectContainerKeksForDocumentSync: the blob upload retry classifier\n// keys on the bare \"Container writer projection KEK… could not be unwrapped\"\n// message, which the sync collector would wrap with document-sync context.\nasync function collectContainerKeks(\n input: {\n execSql?: ExecSql | undefined;\n secretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<ReadonlyMap<string, Uint8Array>> {\n const keksByEpochId = new Map<string, Uint8Array>();\n\n for (const projection of documentContainerProjections(\n input.writerProjection,\n )) {\n const projectionKeks = await unwrapContainerKekPath({\n execSql: input.execSql,\n projection,\n secretKey: input.secretKey,\n ...projectionVerificationOptions(input),\n });\n\n for (const [containerKeyEpochId, keyMaterial] of projectionKeks) {\n const existing = keksByEpochId.get(containerKeyEpochId);\n if (existing) {\n assertEqualBytes(\n existing,\n keyMaterial,\n \"Blob writer projection contains conflicting container KEKs\",\n );\n continue;\n }\n keksByEpochId.set(containerKeyEpochId, keyMaterial);\n }\n }\n\n return keksByEpochId;\n}\n\nexport async function wrapBlobContentKey(\n input: {\n blobId: string;\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n execSql?: ExecSql | undefined;\n secretKey: Uint8Array;\n targets: readonly BlobContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<BlobContentKeyTargetEnvelopeRequest[]> {\n assertDocumentKekPathsCurrent(\n input.writerProjection,\n new Set(input.targets.map((target) => target.containerId)),\n );\n const keksByEpochId = await collectContainerKeks({\n execSql: input.execSql,\n secretKey: input.secretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n\n return Promise.all(\n input.targets.map(async (target) => {\n const targetKek = keksByEpochId.get(target.containerKeyEpochId);\n if (!targetKek) {\n throw new Error(\n `Blob target KEK could not be unwrapped for ${target.containerKeyEpochId}`,\n );\n }\n\n const wrapped = await wrapContentKey(input.contentKey, targetKek, {\n kind: \"Blob\",\n objectId: input.blobId,\n contentKeyEpoch: input.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n }),\n );\n}\n\nasync function unwrapBlobContentKeyTarget(input: {\n blobId: string;\n containerKek: Uint8Array;\n contentKeyEpoch: number;\n envelope: BlobContentKeyTargetEnvelopeRequest;\n}): Promise<Uint8Array> {\n return unwrapContentKeyTargetForKind({\n containerKek: input.containerKek,\n contentKeyEpoch: input.contentKeyEpoch,\n envelope: input.envelope,\n kind: \"Blob\",\n objectId: input.blobId,\n });\n}\n\nexport async function unwrapBlobContentKey(\n input: {\n /** The blob being read; its wraps must be sealed to it. */\n blobId: string;\n contentKeyBundle: BlobContentKeyBundleResponse;\n documentId: string;\n encrypted: BlobEncryptedBytesHeader;\n execSql?: ExecSql | undefined;\n expectedBindingId: string;\n secretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<Uint8Array> {\n const keksByEpochId = await collectContainerKeks({\n execSql: input.execSql,\n secretKey: input.secretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n let contentKey: Uint8Array | null = null;\n const attachmentTargets = input.contentKeyBundle.targets.filter(\n (envelope) =>\n envelope.bindingId === input.expectedBindingId &&\n envelope.documentId === input.documentId,\n );\n\n if (attachmentTargets.length === 0) {\n throw new Error(\"Blob content-key bundle is missing attachment target\");\n }\n\n for (const envelope of attachmentTargets) {\n const containerKek = keksByEpochId.get(envelope.containerKeyEpochId);\n if (!containerKek) {\n continue;\n }\n const unwrapped = await unwrapBlobContentKeyTarget({\n blobId: input.blobId,\n containerKek,\n contentKeyEpoch: input.contentKeyBundle.contentKeyEpoch,\n envelope,\n });\n if (contentKey) {\n assertEqualBytes(\n contentKey,\n unwrapped,\n \"Blob content-key targets unwrap to conflicting keys\",\n );\n continue;\n }\n contentKey = unwrapped;\n }\n\n if (!contentKey) {\n throw new Error(\"Blob content key could not be unwrapped\");\n }\n return contentKey;\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export declare const DEFAULT_DOCUMENT_ACCESS_EPOCH = 1;
2
2
  export declare const DEFAULT_DOCUMENT_KIND = "note";
3
+ export declare const DOCUMENTS_APP_KIND = "documents";
3
4
  export declare const ORGANIZATION_PROFILE_DOCUMENT_KIND = "organization_profile";
4
5
  export declare function createDocumentSignerDeviceId(signingFingerprint: string): string;
@@ -1,5 +1,6 @@
1
1
  export const DEFAULT_DOCUMENT_ACCESS_EPOCH = 1;
2
2
  export const DEFAULT_DOCUMENT_KIND = "note";
3
+ export const DOCUMENTS_APP_KIND = "documents";
3
4
  // SDK-owned structured kind: the organization profile document every
4
5
  // registration provisions. Homed in the data layer (like the "note" kind)
5
6
  // so the projector registry can give it a stable untitled title on hosts
@@ -1 +1 @@
1
- {"version":3,"file":"documentConstants.js","sourceRoot":"","sources":["documentConstants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,6BAA6B,GAAG,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAC5C,qEAAqE;AACrE,0EAA0E;AAC1E,yEAAyE;AACzE,0CAA0C;AAC1C,MAAM,CAAC,MAAM,kCAAkC,GAAG,sBAAsB,CAAC;AACzE,MAAM,gCAAgC,GAAG,cAAc,CAAC;AAExD,MAAM,UAAU,4BAA4B,CAC1C,kBAA0B;IAE1B,OAAO,GAAG,gCAAgC,GAAG,kBAAkB,EAAE,CAAC;AACpE,CAAC","sourcesContent":["export const DEFAULT_DOCUMENT_ACCESS_EPOCH = 1;\nexport const DEFAULT_DOCUMENT_KIND = \"note\";\n// SDK-owned structured kind: the organization profile document every\n// registration provisions. Homed in the data layer (like the \"note\" kind)\n// so the projector registry can give it a stable untitled title on hosts\n// that never register a projector for it.\nexport const ORGANIZATION_PROFILE_DOCUMENT_KIND = \"organization_profile\";\nconst DOCUMENT_SIGNER_DEVICE_ID_PREFIX = \"signing-key:\";\n\nexport function createDocumentSignerDeviceId(\n signingFingerprint: string,\n): string {\n return `${DOCUMENT_SIGNER_DEVICE_ID_PREFIX}${signingFingerprint}`;\n}\n"]}
1
+ {"version":3,"file":"documentConstants.js","sourceRoot":"","sources":["documentConstants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,6BAA6B,GAAG,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAC5C,MAAM,CAAC,MAAM,kBAAkB,GAAG,WAAW,CAAC;AAC9C,qEAAqE;AACrE,0EAA0E;AAC1E,yEAAyE;AACzE,0CAA0C;AAC1C,MAAM,CAAC,MAAM,kCAAkC,GAAG,sBAAsB,CAAC;AACzE,MAAM,gCAAgC,GAAG,cAAc,CAAC;AAExD,MAAM,UAAU,4BAA4B,CAC1C,kBAA0B;IAE1B,OAAO,GAAG,gCAAgC,GAAG,kBAAkB,EAAE,CAAC;AACpE,CAAC","sourcesContent":["export const DEFAULT_DOCUMENT_ACCESS_EPOCH = 1;\nexport const DEFAULT_DOCUMENT_KIND = \"note\";\nexport const DOCUMENTS_APP_KIND = \"documents\";\n// SDK-owned structured kind: the organization profile document every\n// registration provisions. Homed in the data layer (like the \"note\" kind)\n// so the projector registry can give it a stable untitled title on hosts\n// that never register a projector for it.\nexport const ORGANIZATION_PROFILE_DOCUMENT_KIND = \"organization_profile\";\nconst DOCUMENT_SIGNER_DEVICE_ID_PREFIX = \"signing-key:\";\n\nexport function createDocumentSignerDeviceId(\n signingFingerprint: string,\n): string {\n return `${DOCUMENT_SIGNER_DEVICE_ID_PREFIX}${signingFingerprint}`;\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import { type ContainerKekKeyringEntry } from "../../../../internal/crypto/index.js";
2
+ /** Bound outstanding key derivations and yield between batches on cold histories. */
3
+ export declare function verifyContainerKekEntries(containerId: string, entries: readonly ContainerKekKeyringEntry[]): Promise<void>;
@@ -0,0 +1,5 @@
1
+ export { assertContainerKekPathCurrent, assertDocumentKekPathsCurrent, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, } from "./containerKekCurrency.js";
2
+ export { verifyContainerKekEntries } from "./containerKekEntryVerification.js";
3
+ export { ContainerKekTargetUnreachableError, unwrapContainerKekPath, } from "./containerKekPath.js";
4
+ export { signedHistoryEpochIds } from "./containerKekPathHistory.js";
5
+ export { type AggregatedContainerKekLog, fetchContainerKekLog, HistoricalWrapUnavailableError, type HistoricalWrapUnavailableReason, type KeyringRebuildResult, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, } from "./keyringRebuild.js";
@@ -0,0 +1,9 @@
1
+ // The container KEK path operations other subsystems use. Container Data
2
+ // creates, moves, rotates, and shares containers and rebuilds their keyrings
3
+ // through them; blob attachments check that a document's KEK paths are current.
4
+ export { assertContainerKekPathCurrent, assertDocumentKekPathsCurrent, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, } from "./containerKekCurrency.js";
5
+ export { verifyContainerKekEntries } from "./containerKekEntryVerification.js";
6
+ export { ContainerKekTargetUnreachableError, unwrapContainerKekPath, } from "./containerKekPath.js";
7
+ export { signedHistoryEpochIds } from "./containerKekPathHistory.js";
8
+ export { fetchContainerKekLog, HistoricalWrapUnavailableError, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, } from "./keyringRebuild.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,gFAAgF;AAChF,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,EAC7B,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,EACL,kCAAkC,EAClC,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAEL,oBAAoB,EACpB,8BAA8B,EAG9B,4BAA4B,EAC5B,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC","sourcesContent":["// The container KEK path operations other subsystems use. Container Data\n// creates, moves, rotates, and shares containers and rebuilds their keyrings\n// through them; blob attachments check that a document's KEK paths are current.\nexport {\n assertContainerKekPathCurrent,\n assertDocumentKekPathsCurrent,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n} from \"./containerKekCurrency\";\nexport { verifyContainerKekEntries } from \"./containerKekEntryVerification\";\nexport {\n ContainerKekTargetUnreachableError,\n unwrapContainerKekPath,\n} from \"./containerKekPath\";\nexport { signedHistoryEpochIds } from \"./containerKekPathHistory\";\nexport {\n type AggregatedContainerKekLog,\n fetchContainerKekLog,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n type KeyringRebuildResult,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n} from \"./keyringRebuild\";\n"]}