@tearleads/client-sdk 0.1.217 → 0.1.218

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 (139) hide show
  1. package/client/containerContents/documentDiscovery.js +6 -4
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/containerContents/index.js +3 -4
  4. package/client/containerContents/index.js.map +1 -1
  5. package/client/deviceFirst/index.js +2 -2
  6. package/client/deviceFirst/index.js.map +1 -1
  7. package/client/documents/index.js +2 -2
  8. package/client/documents/index.js.map +1 -1
  9. package/client/organizations/organizationGroupHistory.js +1 -2
  10. package/client/organizations/organizationGroupHistory.js.map +1 -1
  11. package/client/organizations/organizationGroupNameHydration.js +1 -2
  12. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  13. package/client/organizations/organizationHistory.js +2 -4
  14. package/client/organizations/organizationHistory.js.map +1 -1
  15. package/client/organizations/principalContainerMutations.js +1 -2
  16. package/client/organizations/principalContainerMutations.js.map +1 -1
  17. package/client/organizations/principalMutations.js +1 -2
  18. package/client/organizations/principalMutations.js.map +1 -1
  19. package/client/organizations/rosterAdmissionEvidence.js +1 -2
  20. package/client/organizations/rosterAdmissionEvidence.js.map +1 -1
  21. package/client/runtime/workflowRuntime.d.ts +3 -2
  22. package/client/runtime/workflowRuntime.js +13 -3
  23. package/client/runtime/workflowRuntime.js.map +1 -1
  24. package/index.d.ts +1 -1
  25. package/index.js.map +1 -1
  26. package/package.json +1 -1
  27. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  28. package/stores/documents/documentStore/attachments/attachmentHydration.js +3 -2
  29. package/stores/documents/documentStore/attachments/attachmentHydration.js.map +1 -1
  30. package/stores/documents/documentStore/rotation/index.js +1 -2
  31. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  32. package/stores/documents/documentStore/rotation/rotationSettlement.js +1 -1
  33. package/stores/documents/documentStore/rotation/rotationSettlement.js.map +1 -1
  34. package/stores/documents/documentStore/state.js.map +1 -1
  35. package/stores/documents/documentStore/sync/carriedFirstUpdate.js.map +1 -1
  36. package/stores/documents/documentStore/sync/index.js.map +1 -1
  37. package/stores/documents/documentStore/sync/syncAttachments.js +3 -2
  38. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  39. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -2
  40. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  41. package/stores/documents/documentStore/sync/syncRequest.js +3 -2
  42. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  43. package/stores/documents/documentStore/sync/syncRevalidation.js.map +1 -1
  44. package/stores/documents/documentStore/sync/syncSeededCreate.js.map +1 -1
  45. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  46. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  47. package/workflows/container-contents/container-state/create/createAdoption.js +1 -2
  48. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  49. package/workflows/container-contents/container-state/create/createWithMetadata.js +1 -2
  50. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  51. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +1 -2
  52. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
  53. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -2
  54. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  55. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -2
  56. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  57. package/workflows/container-contents/container-state/remote.js +3 -4
  58. package/workflows/container-contents/container-state/remote.js.map +1 -1
  59. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
  60. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  61. package/workflows/container-contents/container-state/share/index.js +2 -3
  62. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  63. package/workflows/container-contents/container-state/types.js.map +1 -1
  64. package/workflows/container-contents/documentLinks/documentLinksMove.js +4 -2
  65. package/workflows/container-contents/documentLinks/documentLinksMove.js.map +1 -1
  66. package/workflows/container-contents/documentLinks/index.js +3 -2
  67. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  68. package/workflows/container-contents/index.d.ts +1 -1
  69. package/workflows/container-contents/index.js +1 -1
  70. package/workflows/container-contents/index.js.map +1 -1
  71. package/workflows/container-contents/metadata/index.d.ts +1 -1
  72. package/workflows/container-contents/metadata/index.js.map +1 -1
  73. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +3 -3
  74. package/workflows/container-contents/metadata/metadataRemoteSync.js +3 -2
  75. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  76. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -2
  77. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  78. package/workflows/container-contents/remoteHydration/index.js +1 -2
  79. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  80. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +4 -2
  81. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  82. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  83. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  84. package/workflows/container-contents/runtime.d.ts +13 -2
  85. package/workflows/container-contents/runtime.js +33 -21
  86. package/workflows/container-contents/runtime.js.map +1 -1
  87. package/workflows/container-contents/syncLane.d.ts +1 -1
  88. package/workflows/container-contents/syncLane.js.map +1 -1
  89. package/workflows/container-contents/tombstones/documentPurge.d.ts +2 -3
  90. package/workflows/container-contents/tombstones/documentPurge.js +1 -2
  91. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  92. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +3 -2
  93. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  94. package/workflows/documents/index.d.ts +1 -1
  95. package/workflows/documents/index.js +1 -1
  96. package/workflows/documents/index.js.map +1 -1
  97. package/workflows/documents/runtime.d.ts +12 -1
  98. package/workflows/documents/runtime.js +24 -16
  99. package/workflows/documents/runtime.js.map +1 -1
  100. package/workflows/documents/sync/syncLane.d.ts +1 -1
  101. package/workflows/documents/sync/syncLane.js.map +1 -1
  102. package/workflows/organizations/currentOrganizationAuthority.d.ts +1 -2
  103. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  104. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +5 -4
  105. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js +2 -4
  106. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -1
  107. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js +1 -2
  108. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -1
  109. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  110. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -2
  111. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +2 -2
  112. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  113. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js +4 -8
  114. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js.map +1 -1
  115. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +2 -3
  116. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
  117. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
  118. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +2 -2
  119. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
  120. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +2 -2
  121. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  122. package/workflows/principals/index.d.ts +1 -0
  123. package/workflows/principals/index.js.map +1 -1
  124. package/workflows/principals/principalPolicyService.d.ts +64 -0
  125. package/workflows/principals/principalPolicyService.js +117 -0
  126. package/workflows/principals/principalPolicyService.js.map +1 -0
  127. package/workflows/principals/runtimePolicyRecovery.d.ts +13 -10
  128. package/workflows/principals/runtimePolicyRecovery.js +9 -17
  129. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  130. package/workflows/principals/runtimeProjectionPolicyRecovery.js +7 -8
  131. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  132. package/data/principals/principalHistoryRuntime.js +0 -12
  133. package/data/principals/principalHistoryRuntime.js.map +0 -1
  134. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.d.ts +0 -16
  135. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js +0 -39
  136. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js.map +0 -1
  137. package/workflows/principals/runtimePolicyWarmer.d.ts +0 -26
  138. package/workflows/principals/runtimePolicyWarmer.js +0 -48
  139. package/workflows/principals/runtimePolicyWarmer.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"documentTombstoneEvidence.js","sourceRoot":"","sources":["documentTombstoneEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,yCAAyC,EAAE,MAAM,kDAAkD,CAAC;AAC7G,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAE7G,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AAEpH,OAAO,EACL,kCAAkC,GAEnC,MAAM,sCAAsC,CAAC;AAM9C,OAAO,EAAE,+BAA+B,EAAE,MAAM,wCAAwC,CAAC;AAkCzF,MAAM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I,GAAG,MAAM,cAAc,CAAC,UAAU,CAAC,CAAC;gBAC9C,IAAI,IAAI,KAAK,IAAI;oBAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACpE,CAAC;QACH,CAAC,CAAC;QACF,MAAM,OAAO,CAAC,GAAG,CACf,KAAK,CAAC,IAAI,CACR,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EACnE,MAAM,CACP,CACF,CAAC;QACF,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/keyingProjectionVerification/error\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { DocumentPurgeCheckpoint } from \"../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../principals/runtimePolicyWarmer\";\nimport type {\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n ContainerDocumentTombstoneVerifier,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"../documentDiscovery/documentHeadScope\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport interface VerifiedDocumentHeadLinkSet {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n /** Present for a signed head; a terminal purge has no live access state. */\n readonly accessStateHash?: string;\n readonly linkedContainerIds: ReadonlyArray<string>;\n}\n\n/**\n * The document's verified head link set, or `null` when no verified head is\n * available: the projection could not be fetched (the requester may no\n * longer read the document, or it was purged) or failed verification.\n */\nexport type DocumentHeadLinkSetLoader = (\n documentId: string,\n expectedManifestHash?: string,\n) => Promise<VerifiedDocumentHeadLinkSet | \"not-found\" | null>;\n\n/** The highest access epoch local state records for the document. */\nexport type LocalDocumentAccessEpochLoader = (\n documentId: string,\n) => Promise<number>;\n\nexport interface DocumentHeadLinkSetLoaderDeps {\n readonly assertDocumentWriterProjectionConsistent: typeof assertDocumentWriterProjectionConsistent;\n readonly loadDocumentPurgeCheckpoint: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<DocumentPurgeCheckpoint | null>;\n}\n\nexport const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;\n/**\n * Head loads per settle. Tombstones beyond it stay unverified and are held\n * for a later, backed-off retry, so a bulk move out of a folder does not cost\n * every device an unbounded burst of fetches before the watermark advances.\n */\nexport const HEAD_LINK_SET_LOADS_PER_RUN = 32;\n\nasync function verifiedHeadLinkSet(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps,\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n policyOperation: PrincipalPolicyOperation | undefined,\n): Promise<VerifiedDocumentHeadLinkSet> {\n const verified: { value?: VerifiedDocumentHeadLinkSet } = {};\n await deps.assertDocumentWriterProjectionConsistent(projection, {\n // Only the link set is read; a bundle wrapped to superseded KEK targets\n // still carries the signed head.\n allowStaleContentKeyBundle: true,\n execSql: runtime.infra.execSql,\n onVerifiedAuthorization: (authorization) => {\n const head = authorization.documentManifestByHash.get(\n projection.documentManifest.manifestHash,\n );\n if (head && head.state.documentId === documentId) {\n verified.value = {\n organizationId: head.state.organizationId,\n accessEpoch: head.state.epoch,\n accessStateHash: head.manifestHash,\n linkedContainerIds: uniqueSortedStrings(\n head.state.linkedContainerIds,\n ),\n };\n }\n },\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: policyOperation },\n ),\n });\n if (!verified.value) {\n throw new Error(\"Tombstone evidence lacks a verified document head\");\n }\n return verified.value;\n}\n\nasync function reportUnavailableHead(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n error: unknown,\n): Promise<void> {\n const integrityFailure = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: \"document.tombstone-evidence\",\n },\n );\n try {\n if (\n !integrityFailure &&\n error instanceof ProjectionDependencyUnavailableError\n ) {\n // A policy can advance without changing this document's hash. Drop its\n // cached evidence so the held head can recover on the next run.\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is awaiting current policy history`,\n );\n return;\n }\n runtime.util.logError?.(\n \"Container contents: tombstone evidence is unavailable\",\n error,\n );\n } catch {\n // A host logger that throws must not fail the discovery pass.\n }\n}\n\n/** Only a typed 404 proves absence; any other failure leaves the head unavailable. */\nfunction failedHeadVerdict(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n failure: {\n readonly code?: string | undefined;\n readonly status?: number | null | undefined;\n },\n): \"not-found\" | null {\n if (failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE)\n return \"not-found\";\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is unavailable (${failure.status ?? \"offline\"})`,\n );\n return null;\n}\n\n/** `policyOperation` lets one discovery pass share a directory discovery. */\nexport function createDocumentHeadLinkSetLoader(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps = {\n assertDocumentWriterProjectionConsistent,\n loadDocumentPurgeCheckpoint: (execSql, documentId) =>\n new KeyingCheckpointRepository(execSql).loadDocumentPurgeCheckpoint(\n documentId,\n ),\n },\n policyOperation?: PrincipalPolicyOperation,\n): DocumentHeadLinkSetLoader {\n return async (documentId, expectedManifestHash) => {\n try {\n // A verified purge proof is terminal signed evidence that the document\n // links nothing any more.\n if (\n await deps.loadDocumentPurgeCheckpoint(\n runtime.infra.execSql,\n documentId,\n )\n ) {\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n }\n // Tombstones require a fresh head. Listings can reuse a matching cached\n // projection, whose signature and local checkpoint are still verified.\n if (!expectedManifestHash)\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n let result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n if (\n expectedManifestHash &&\n result.ok &&\n result.data.documentManifest.manifestHash !== expectedManifestHash\n ) {\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n }\n if (!result.ok) return failedHeadVerdict(runtime, documentId, result);\n return await verifiedHeadLinkSet(\n runtime,\n deps,\n documentId,\n result.data,\n policyOperation,\n );\n } catch (error) {\n // Any failure leaves the tombstone unverified (held and retried); a\n // thrown error here must not fail the whole discovery pass.\n await reportUnavailableHead(runtime, documentId, error);\n return null;\n }\n };\n}\n\nfunction judgeTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n head: VerifiedDocumentHeadLinkSet | null,\n): ContainerDocumentTombstoneVerdict[] {\n return tombstones.map((tombstone): ContainerDocumentTombstoneVerdict => {\n if (head === null) {\n return { kind: \"unverified\", tombstone };\n }\n if (head.linkedContainerIds.includes(tombstone.containerId)) {\n return {\n kind: \"refuted\",\n linkedContainerIds: head.linkedContainerIds,\n tombstone,\n };\n }\n return {\n kind: \"verified\",\n tombstone: {\n ...tombstone,\n accessEpoch: head.accessEpoch,\n linkedContainerIds: head.linkedContainerIds,\n },\n };\n });\n}\n\n/**\n * Judge listing tombstones against each document's verified head link set,\n * fetched once per document with bounded concurrency and a per-run cap. A\n * head whose epoch is below local document state is no evidence: it may be a\n * lagging replica or a replay, and applying it could delete rows a newer\n * listing or settled move wrote.\n */\nexport function createContainerDocumentTombstoneVerifier(\n organizationId: string | undefined,\n loadDocumentHeadLinkSet: DocumentHeadLinkSetLoader,\n loadLocalDocumentAccessEpoch: LocalDocumentAccessEpochLoader,\n): ContainerDocumentTombstoneVerifier {\n return async (tombstones) => {\n const byDocumentId = new Map<string, ContainerDocumentTombstone[]>();\n for (const tombstone of tombstones) {\n const group = byDocumentId.get(tombstone.documentId) ?? [];\n group.push(tombstone);\n byDocumentId.set(tombstone.documentId, group);\n }\n const groups = [...byDocumentId.entries()];\n const verdicts: ContainerDocumentTombstoneVerdict[][] = groups.map(\n ([, group], index): ContainerDocumentTombstoneVerdict[] =>\n index < HEAD_LINK_SET_LOADS_PER_RUN\n ? judgeTombstones(group, null)\n : group.map((tombstone) => ({ kind: \"deferred\", tombstone })),\n );\n // A missing, foreign, or older-than-local head is no evidence.\n const evidentialHead = async (documentId: string) => {\n const head = await loadDocumentHeadLinkSet(documentId);\n if (head === null || head === \"not-found\") return null;\n if (!documentHeadMatchesOrganization(head, organizationId)) return null;\n // A local-state read that fails is treated like an unavailable head:\n // the tombstones stay held rather than failing the discovery pass.\n const localEpoch = await loadLocalDocumentAccessEpoch(documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n return head.accessEpoch < localEpoch ? null : head;\n };\n let next = 0;\n const worker = async () => {\n while (next < Math.min(groups.length, HEAD_LINK_SET_LOADS_PER_RUN)) {\n const index = next++;\n const entry = groups[index];\n if (!entry) break;\n const [documentId, group] = entry;\n const head = await evidentialHead(documentId);\n if (head !== null) verdicts[index] = judgeTombstones(group, head);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, groups.length) },\n worker,\n ),\n );\n return verdicts.flat();\n };\n}\n"]}
1
+ {"version":3,"file":"documentTombstoneEvidence.js","sourceRoot":"","sources":["documentTombstoneEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,yCAAyC,EAAE,MAAM,kDAAkD,CAAC;AAC7G,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAE7G,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AAQpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,wCAAwC,CAAC;AAkCzF,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAAC,CAAC;AAChD;;;;GAIG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,CAAC;AAE9C,KAAK,UAAU,mBAAmB,CAChC,OAAyC,EACzC,IAAmC,EACnC,UAAkB,EAClB,UAA4C,EAC5C,eAAqD;IAErD,MAAM,QAAQ,GAA4C,EAAE,CAAC;IAC7D,MAAM,IAAI,CAAC,wCAAwC,CAAC,UAAU,EAAE;QAC9D,wEAAwE;QACxE,iCAAiC;QACjC,0BAA0B,EAAE,IAAI;QAChC,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,uBAAuB,EAAE,CAAC,aAAa,EAAE,EAAE;YACzC,MAAM,IAAI,GAAG,aAAa,CAAC,sBAAsB,CAAC,GAAG,CACnD,UAAU,CAAC,gBAAgB,CAAC,YAAY,CACzC,CAAC;YACF,IAAI,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,UAAU,KAAK,UAAU,EAAE,CAAC;gBACjD,QAAQ,CAAC,KAAK,GAAG;oBACf,c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,CAAC,CAAC,KAAK,CACrE,GAAG,EAAE,CAAC,MAAM,CAAC,gBAAgB,CAC9B,CAAC;YACF,OAAO,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACrD,CAAC,CAAC;QACF,IAAI,IAAI,GAAG,CAAC,CAAC;QACb,MAAM,MAAM,GAAG,KAAK,IAAI,EAAE;YACxB,OAAO,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC,EAAE,CAAC;gBACnE,MAAM,KAAK,GAAG,IAAI,EAAE,CAAC;gBACrB,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;gBAC5B,IAAI,CAAC,KAAK;oBAAE,MAAM;gBAClB,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,KAAK,CAAC;gBAClC,MAAM,IAAI,GAAG,MAAM,cAAc,CAAC,UAAU,CAAC,CAAC;gBAC9C,IAAI,IAAI,KAAK,IAAI;oBAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACpE,CAAC;QACH,CAAC,CAAC;QACF,MAAM,OAAO,CAAC,GAAG,CACf,KAAK,CAAC,IAAI,CACR,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EACnE,MAAM,CACP,CACF,CAAC;QACF,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/keyingProjectionVerification/error\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { DocumentPurgeCheckpoint } from \"../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport type {\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n ContainerDocumentTombstoneVerifier,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"../documentDiscovery/documentHeadScope\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport interface VerifiedDocumentHeadLinkSet {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n /** Present for a signed head; a terminal purge has no live access state. */\n readonly accessStateHash?: string;\n readonly linkedContainerIds: ReadonlyArray<string>;\n}\n\n/**\n * The document's verified head link set, or `null` when no verified head is\n * available: the projection could not be fetched (the requester may no\n * longer read the document, or it was purged) or failed verification.\n */\nexport type DocumentHeadLinkSetLoader = (\n documentId: string,\n expectedManifestHash?: string,\n) => Promise<VerifiedDocumentHeadLinkSet | \"not-found\" | null>;\n\n/** The highest access epoch local state records for the document. */\nexport type LocalDocumentAccessEpochLoader = (\n documentId: string,\n) => Promise<number>;\n\nexport interface DocumentHeadLinkSetLoaderDeps {\n readonly assertDocumentWriterProjectionConsistent: typeof assertDocumentWriterProjectionConsistent;\n readonly loadDocumentPurgeCheckpoint: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<DocumentPurgeCheckpoint | null>;\n}\n\nexport const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;\n/**\n * Head loads per settle. Tombstones beyond it stay unverified and are held\n * for a later, backed-off retry, so a bulk move out of a folder does not cost\n * every device an unbounded burst of fetches before the watermark advances.\n */\nexport const HEAD_LINK_SET_LOADS_PER_RUN = 32;\n\nasync function verifiedHeadLinkSet(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps,\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n policyOperation: PrincipalPolicyOperation | undefined,\n): Promise<VerifiedDocumentHeadLinkSet> {\n const verified: { value?: VerifiedDocumentHeadLinkSet } = {};\n await deps.assertDocumentWriterProjectionConsistent(projection, {\n // Only the link set is read; a bundle wrapped to superseded KEK targets\n // still carries the signed head.\n allowStaleContentKeyBundle: true,\n execSql: runtime.infra.execSql,\n onVerifiedAuthorization: (authorization) => {\n const head = authorization.documentManifestByHash.get(\n projection.documentManifest.manifestHash,\n );\n if (head && head.state.documentId === documentId) {\n verified.value = {\n organizationId: head.state.organizationId,\n accessEpoch: head.state.epoch,\n accessStateHash: head.manifestHash,\n linkedContainerIds: uniqueSortedStrings(\n head.state.linkedContainerIds,\n ),\n };\n }\n },\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!verified.value) {\n throw new Error(\"Tombstone evidence lacks a verified document head\");\n }\n return verified.value;\n}\n\nasync function reportUnavailableHead(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n error: unknown,\n): Promise<void> {\n const integrityFailure = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: \"document.tombstone-evidence\",\n },\n );\n try {\n if (\n !integrityFailure &&\n error instanceof ProjectionDependencyUnavailableError\n ) {\n // A policy can advance without changing this document's hash. Drop its\n // cached evidence so the held head can recover on the next run.\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is awaiting current policy history`,\n );\n return;\n }\n runtime.util.logError?.(\n \"Container contents: tombstone evidence is unavailable\",\n error,\n );\n } catch {\n // A host logger that throws must not fail the discovery pass.\n }\n}\n\n/** Only a typed 404 proves absence; any other failure leaves the head unavailable. */\nfunction failedHeadVerdict(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n failure: {\n readonly code?: string | undefined;\n readonly status?: number | null | undefined;\n },\n): \"not-found\" | null {\n if (failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE)\n return \"not-found\";\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is unavailable (${failure.status ?? \"offline\"})`,\n );\n return null;\n}\n\n/** `policyOperation` lets one discovery pass share a directory discovery. */\nexport function createDocumentHeadLinkSetLoader(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps = {\n assertDocumentWriterProjectionConsistent,\n loadDocumentPurgeCheckpoint: (execSql, documentId) =>\n new KeyingCheckpointRepository(execSql).loadDocumentPurgeCheckpoint(\n documentId,\n ),\n },\n policyOperation?: PrincipalPolicyOperation,\n): DocumentHeadLinkSetLoader {\n return async (documentId, expectedManifestHash) => {\n try {\n // A verified purge proof is terminal signed evidence that the document\n // links nothing any more.\n if (\n await deps.loadDocumentPurgeCheckpoint(\n runtime.infra.execSql,\n documentId,\n )\n ) {\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n }\n // Tombstones require a fresh head. Listings can reuse a matching cached\n // projection, whose signature and local checkpoint are still verified.\n if (!expectedManifestHash)\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n let result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n if (\n expectedManifestHash &&\n result.ok &&\n result.data.documentManifest.manifestHash !== expectedManifestHash\n ) {\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n }\n if (!result.ok) return failedHeadVerdict(runtime, documentId, result);\n return await verifiedHeadLinkSet(\n runtime,\n deps,\n documentId,\n result.data,\n policyOperation,\n );\n } catch (error) {\n // Any failure leaves the tombstone unverified (held and retried); a\n // thrown error here must not fail the whole discovery pass.\n await reportUnavailableHead(runtime, documentId, error);\n return null;\n }\n };\n}\n\nfunction judgeTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n head: VerifiedDocumentHeadLinkSet | null,\n): ContainerDocumentTombstoneVerdict[] {\n return tombstones.map((tombstone): ContainerDocumentTombstoneVerdict => {\n if (head === null) {\n return { kind: \"unverified\", tombstone };\n }\n if (head.linkedContainerIds.includes(tombstone.containerId)) {\n return {\n kind: \"refuted\",\n linkedContainerIds: head.linkedContainerIds,\n tombstone,\n };\n }\n return {\n kind: \"verified\",\n tombstone: {\n ...tombstone,\n accessEpoch: head.accessEpoch,\n linkedContainerIds: head.linkedContainerIds,\n },\n };\n });\n}\n\n/**\n * Judge listing tombstones against each document's verified head link set,\n * fetched once per document with bounded concurrency and a per-run cap. A\n * head whose epoch is below local document state is no evidence: it may be a\n * lagging replica or a replay, and applying it could delete rows a newer\n * listing or settled move wrote.\n */\nexport function createContainerDocumentTombstoneVerifier(\n organizationId: string | undefined,\n loadDocumentHeadLinkSet: DocumentHeadLinkSetLoader,\n loadLocalDocumentAccessEpoch: LocalDocumentAccessEpochLoader,\n): ContainerDocumentTombstoneVerifier {\n return async (tombstones) => {\n const byDocumentId = new Map<string, ContainerDocumentTombstone[]>();\n for (const tombstone of tombstones) {\n const group = byDocumentId.get(tombstone.documentId) ?? [];\n group.push(tombstone);\n byDocumentId.set(tombstone.documentId, group);\n }\n const groups = [...byDocumentId.entries()];\n const verdicts: ContainerDocumentTombstoneVerdict[][] = groups.map(\n ([, group], index): ContainerDocumentTombstoneVerdict[] =>\n index < HEAD_LINK_SET_LOADS_PER_RUN\n ? judgeTombstones(group, null)\n : group.map((tombstone) => ({ kind: \"deferred\", tombstone })),\n );\n // A missing, foreign, or older-than-local head is no evidence.\n const evidentialHead = async (documentId: string) => {\n const head = await loadDocumentHeadLinkSet(documentId);\n if (head === null || head === \"not-found\") return null;\n if (!documentHeadMatchesOrganization(head, organizationId)) return null;\n // A local-state read that fails is treated like an unavailable head:\n // the tombstones stay held rather than failing the discovery pass.\n const localEpoch = await loadLocalDocumentAccessEpoch(documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n return head.accessEpoch < localEpoch ? null : head;\n };\n let next = 0;\n const worker = async () => {\n while (next < Math.min(groups.length, HEAD_LINK_SET_LOADS_PER_RUN)) {\n const index = next++;\n const entry = groups[index];\n if (!entry) break;\n const [documentId, group] = entry;\n const head = await evidentialHead(documentId);\n if (head !== null) verdicts[index] = judgeTombstones(group, head);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, groups.length) },\n worker,\n ),\n );\n return verdicts.flat();\n };\n}\n"]}
@@ -27,7 +27,7 @@ export { buildDocumentPurgeRequest } from "./purge/index.js";
27
27
  export { type DiscardedDocumentShellResult, deletePersistedDocument, discardPersistedDocumentToShell, } from "./purge/persistedDocumentRemoval.js";
28
28
  export type { RemoteDocumentServiceApi } from "./remote/remoteDocumentCollaborators.js";
29
29
  export { RemoteDocumentService } from "./remote/remoteDocumentService.js";
30
- export { createDocumentsWorkflowRuntime, type DocumentsWorkflowRuntime, type DocumentsWorkflowRuntimeGroups, type DocumentsWorkflowRuntimeInfra, type DocumentsWorkflowRuntimeInput, type DocumentsWorkflowRuntimeInputGroups, } from "./runtime.js";
30
+ export { createDocumentsWorkflowRuntime, createDocumentsWorkflowRuntimeFromSnapshot, type DocumentsWorkflowRuntime, type DocumentsWorkflowRuntimeGroups, type DocumentsWorkflowRuntimeInfra, type DocumentsWorkflowRuntimeInput, type DocumentsWorkflowRuntimeInputGroups, type DocumentsWorkflowRuntimeSnapshot, } from "./runtime.js";
31
31
  export { syncRemoteDocument } from "./sync/index.js";
32
32
  export { documentCreateSeedCandidate } from "./sync/initialSync.js";
33
33
  export type { SyncRemoteDocumentInput } from "./sync/readOnlySync.js";
@@ -24,7 +24,7 @@ export { createDocumentProjectionUserKeyResolver, didDocumentProjectionKeyRuntim
24
24
  export { buildDocumentPurgeRequest } from "./purge/index.js";
25
25
  export { deletePersistedDocument, discardPersistedDocumentToShell, } from "./purge/persistedDocumentRemoval.js";
26
26
  export { RemoteDocumentService } from "./remote/remoteDocumentService.js";
27
- export { createDocumentsWorkflowRuntime, } from "./runtime.js";
27
+ export { createDocumentsWorkflowRuntime, createDocumentsWorkflowRuntimeFromSnapshot, } from "./runtime.js";
28
28
  export { syncRemoteDocument } from "./sync/index.js";
29
29
  export { documentCreateSeedCandidate } from "./sync/initialSync.js";
30
30
  export { registerDocumentSyncLane, requestDocumentSyncLaneAndWait, } from "./sync/syncLane.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,8BAA8B,GAC/B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,wCAAwC,EAAE,MAAM,uCAAuC,CAAC;AACjG,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAC7G,OAAO,EAGL,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,8DAA8D,CAAC;AACtE,OAAO,EAEL,kCAAkC,EAClC,oBAAoB,GACrB,MAAM,iDAAiD,CAAC;AAQzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,EACL,qCAAqC,EACrC,oCAAoC,GACrC,MAAM,qEAAqE,CAAC;AAE7E,OAAO,EAAE,gCAAgC,EAAE,MAAM,0CAA0C,CAAC;AAC5F,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,6BAA6B,EAC7B,+BAA+B,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,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,mCAAmC,EACnC,iCAAiC,GAElC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uCAAuC,EAAE,MAAM,qCAAqC,CAAC;AAC9F,OAAO,EAAE,kCAAkC,EAAE,MAAM,4BAA4B,CAAC;AAEhF,OAAO,EAAE,qCAAqC,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export {\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n} from \"../../data/documents/shared/projection\";\nexport { persistedDocumentCreateStateFromResponse } from \"../../data/documents/shared/responses\";\nexport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\nexport { selectDocumentSyncOutgoingBatch } from \"../../data/documents/shared/sync/documentSyncOutgoingBatch\";\nexport {\n type DocumentSyncUpdateIsolationError,\n type IncomingDocumentSyncUpdateValidator,\n isDocumentSyncUpdateIsolationError,\n validateDocumentSyncUpdateImports,\n} from \"../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nexport {\n type DocumentSyncPullContinuation,\n documentSyncPullContinuationsEqual,\n readPullContinuation,\n} from \"../../data/documents/shared/sync/syncPagination\";\nexport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationFailure,\n DocumentRotationProofMode,\n RelinkRemoteDocumentResult,\n} from \"../../data/documents/shared/types\";\nexport { DocumentRecordRepository } from \"../../data/persistence/documents/records\";\nexport {\n DOCUMENT_HISTORY_COMPACTION_MAX_BYTES,\n DOCUMENT_HISTORY_COMPACTION_MAX_ROWS,\n} from \"../../data/persistence/documents/records/documentHistoryPersistence\";\nexport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nexport { settleOutgoingPassAndDecideReArm } from \"../../data/sync/outgoingUpdateSettlement\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n deleteLocalDocumentAttachment,\n deletePendingDocumentAttachment,\n markLocalDocumentAttachmentDetached,\n saveLocalDocumentAttachments,\n savePendingDocumentAttachment,\n} from \"./attachments/attachmentPersistence\";\nexport { runSerializedDocumentBlobMutation } from \"./attachments/blobMutationLock\";\nexport { reclaimDocumentOrphanBlobs } from \"./attachments/orphanBlobReclaims\";\nexport { resolveDocumentCreateAuthor } from \"./author\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createRemoteDocument,\n documentWriterProjectionFromCreateResponse,\n} from \"./create\";\nexport {\n type DocumentHistory,\n type DocumentHistoryStop,\n type DocumentHistoryVersion,\n type DocumentHistoryVersionEntry,\n type DocumentHistoryView,\n openDocumentHistory,\n} from \"./history/documentHistory\";\nexport {\n type DocumentHistoryChange,\n type DocumentHistoryRowChange,\n type DocumentHistoryTextChange,\n isEmptyDocumentHistoryChange,\n} from \"./history/documentHistoryChange\";\nexport {\n importDocumentHistoryTailUpdates,\n loadPersistedDocumentContent,\n mergePersistedDocumentHistory,\n} from \"./historyContent\";\nexport { buildMaterializedDocumentLinkSetMutationPlan } from \"./linkSet\";\nexport {\n createLinkSetAttachmentReuse,\n type LinkSetAttachmentReuse,\n} from \"./linkSet/linkSetBlobRewraps\";\nexport {\n enqueuePendingDocumentUpdate,\n listPendingDocumentUpdates,\n} from \"./pendingUpdatePersistence\";\nexport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n DOCUMENTS_APP_KIND,\n type DocumentBirthResult,\n type DocumentRecord,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n type LocalAttachmentRecord,\n loadPersistedDocumentStoreState,\n type PendingAttachmentRecord,\n type PendingAttachmentUploadIdentity,\n type PendingUpdateInsert,\n type PendingUpdateRecord,\n persistDocumentState,\n type QueuedPendingUpdateRecord,\n type RelinkPersistedDocumentInput,\n runSerializedSqlMutation,\n} from \"./persistence\";\nexport {\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionKeyRuntime,\n type DocumentProjectionUserKeyResolver,\n didDocumentProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport { buildDocumentPurgeRequest } from \"./purge\";\nexport {\n type DiscardedDocumentShellResult,\n deletePersistedDocument,\n discardPersistedDocumentToShell,\n} from \"./purge/persistedDocumentRemoval\";\nexport type { RemoteDocumentServiceApi } from \"./remote/remoteDocumentCollaborators\";\nexport { RemoteDocumentService } from \"./remote/remoteDocumentService\";\nexport {\n createDocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntimeGroups,\n type DocumentsWorkflowRuntimeInfra,\n type DocumentsWorkflowRuntimeInput,\n type DocumentsWorkflowRuntimeInputGroups,\n} from \"./runtime\";\nexport { syncRemoteDocument } from \"./sync\";\nexport { documentCreateSeedCandidate } from \"./sync/initialSync\";\nexport type { SyncRemoteDocumentInput } from \"./sync/readOnlySync\";\nexport type { DocumentSyncContainerRekeyBuilder } from \"./sync/syncAttemptState\";\nexport {\n type DocumentSyncLane,\n registerDocumentSyncLane,\n requestDocumentSyncLaneAndWait,\n} from \"./sync/syncLane\";\nexport {\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n} from \"./sync/syncTrace\";\nexport {\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type TerminalSubmitFailureHandler,\n} from \"./syncFailures/syncFailureClassification\";\nexport { shouldClearDocumentSyncFailureAfterPass } from \"./syncFailures/syncFailureClearance\";\nexport { DocumentRawHistoryUnavailableError } from \"./syncPlan/syncContentKeys\";\nexport type { RekeyPendingUpdate } from \"./syncRekeys/syncRecoveryRekey\";\nexport { createDocumentWriterPublicKeyResolver } from \"./writerKeys\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,8BAA8B,GAC/B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,wCAAwC,EAAE,MAA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GL,kBAAkB,EAIlB,2BAA2B,EAE3B,+BAA+B,EAK/B,oBAAoB,EAGpB,wBAAwB,GACzB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,uCAAuC,EAGvC,qCAAqC,GACtC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAEL,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EACL,8BAA8B,EAC9B,0CAA0C,GAO3C,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAC5C,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAGjE,OAAO,EAEL,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,mCAAmC,EACnC,iCAAiC,GAElC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uCAAuC,EAAE,MAAM,qCAAqC,CAAC;AAC9F,OAAO,EAAE,kCAAkC,EAAE,MAAM,4BAA4B,CAAC;AAEhF,OAAO,EAAE,qCAAqC,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export {\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n} from \"../../data/documents/shared/projection\";\nexport { persistedDocumentCreateStateFromResponse } from \"../../data/documents/shared/responses\";\nexport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\nexport { selectDocumentSyncOutgoingBatch } from \"../../data/documents/shared/sync/documentSyncOutgoingBatch\";\nexport {\n type DocumentSyncUpdateIsolationError,\n type IncomingDocumentSyncUpdateValidator,\n isDocumentSyncUpdateIsolationError,\n validateDocumentSyncUpdateImports,\n} from \"../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nexport {\n type DocumentSyncPullContinuation,\n documentSyncPullContinuationsEqual,\n readPullContinuation,\n} from \"../../data/documents/shared/sync/syncPagination\";\nexport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationFailure,\n DocumentRotationProofMode,\n RelinkRemoteDocumentResult,\n} from \"../../data/documents/shared/types\";\nexport { DocumentRecordRepository } from \"../../data/persistence/documents/records\";\nexport {\n DOCUMENT_HISTORY_COMPACTION_MAX_BYTES,\n DOCUMENT_HISTORY_COMPACTION_MAX_ROWS,\n} from \"../../data/persistence/documents/records/documentHistoryPersistence\";\nexport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nexport { settleOutgoingPassAndDecideReArm } from \"../../data/sync/outgoingUpdateSettlement\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n deleteLocalDocumentAttachment,\n deletePendingDocumentAttachment,\n markLocalDocumentAttachmentDetached,\n saveLocalDocumentAttachments,\n savePendingDocumentAttachment,\n} from \"./attachments/attachmentPersistence\";\nexport { runSerializedDocumentBlobMutation } from \"./attachments/blobMutationLock\";\nexport { reclaimDocumentOrphanBlobs } from \"./attachments/orphanBlobReclaims\";\nexport { resolveDocumentCreateAuthor } from \"./author\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createRemoteDocument,\n documentWriterProjectionFromCreateResponse,\n} from \"./create\";\nexport {\n type DocumentHistory,\n type DocumentHistoryStop,\n type DocumentHistoryVersion,\n type DocumentHistoryVersionEntry,\n type DocumentHistoryView,\n openDocumentHistory,\n} from \"./history/documentHistory\";\nexport {\n type DocumentHistoryChange,\n type DocumentHistoryRowChange,\n type DocumentHistoryTextChange,\n isEmptyDocumentHistoryChange,\n} from \"./history/documentHistoryChange\";\nexport {\n importDocumentHistoryTailUpdates,\n loadPersistedDocumentContent,\n mergePersistedDocumentHistory,\n} from \"./historyContent\";\nexport { buildMaterializedDocumentLinkSetMutationPlan } from \"./linkSet\";\nexport {\n createLinkSetAttachmentReuse,\n type LinkSetAttachmentReuse,\n} from \"./linkSet/linkSetBlobRewraps\";\nexport {\n enqueuePendingDocumentUpdate,\n listPendingDocumentUpdates,\n} from \"./pendingUpdatePersistence\";\nexport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n DOCUMENTS_APP_KIND,\n type DocumentBirthResult,\n type DocumentRecord,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n type LocalAttachmentRecord,\n loadPersistedDocumentStoreState,\n type PendingAttachmentRecord,\n type PendingAttachmentUploadIdentity,\n type PendingUpdateInsert,\n type PendingUpdateRecord,\n persistDocumentState,\n type QueuedPendingUpdateRecord,\n type RelinkPersistedDocumentInput,\n runSerializedSqlMutation,\n} from \"./persistence\";\nexport {\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionKeyRuntime,\n type DocumentProjectionUserKeyResolver,\n didDocumentProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport { buildDocumentPurgeRequest } from \"./purge\";\nexport {\n type DiscardedDocumentShellResult,\n deletePersistedDocument,\n discardPersistedDocumentToShell,\n} from \"./purge/persistedDocumentRemoval\";\nexport type { RemoteDocumentServiceApi } from \"./remote/remoteDocumentCollaborators\";\nexport { RemoteDocumentService } from \"./remote/remoteDocumentService\";\nexport {\n createDocumentsWorkflowRuntime,\n createDocumentsWorkflowRuntimeFromSnapshot,\n type DocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntimeGroups,\n type DocumentsWorkflowRuntimeInfra,\n type DocumentsWorkflowRuntimeInput,\n type DocumentsWorkflowRuntimeInputGroups,\n type DocumentsWorkflowRuntimeSnapshot,\n} from \"./runtime\";\nexport { syncRemoteDocument } from \"./sync\";\nexport { documentCreateSeedCandidate } from \"./sync/initialSync\";\nexport type { SyncRemoteDocumentInput } from \"./sync/readOnlySync\";\nexport type { DocumentSyncContainerRekeyBuilder } from \"./sync/syncAttemptState\";\nexport {\n type DocumentSyncLane,\n registerDocumentSyncLane,\n requestDocumentSyncLaneAndWait,\n} from \"./sync/syncLane\";\nexport {\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n} from \"./sync/syncTrace\";\nexport {\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type TerminalSubmitFailureHandler,\n} from \"./syncFailures/syncFailureClassification\";\nexport { shouldClearDocumentSyncFailureAfterPass } from \"./syncFailures/syncFailureClearance\";\nexport { DocumentRawHistoryUnavailableError } from \"./syncPlan/syncContentKeys\";\nexport type { RekeyPendingUpdate } from \"./syncRekeys/syncRecoveryRekey\";\nexport { createDocumentWriterPublicKeyResolver } from \"./writerKeys\";\n"]}
@@ -3,6 +3,7 @@ import { type DocumentProjectorRegistryInput } from "../../data/documents/docume
3
3
  import type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
4
4
  import { type TrustedUserIdentityResolver } from "../../data/trustedUserIdentity/index.js";
5
5
  import { BlobAttachmentService } from "../blobs/blobAttachmentService.js";
6
+ import { PrincipalPolicyService } from "../principals/principalPolicyService.js";
6
7
  import type { WorkflowRuntimeAuthInput, WorkflowRuntimeCryptoInput, WorkflowRuntimeInfraInput, WorkflowRuntimeStateInput, WorkflowRuntimeUtilInput } from "../shared/runtimeInput.js";
7
8
  interface DocumentsWorkflowRuntimeUtilInput extends Omit<WorkflowRuntimeUtilInput, "logError"> {
8
9
  /** Receives handled quarantine errors without converting them to strings. */
@@ -29,16 +30,26 @@ export interface DocumentsWorkflowRuntimeInputGroups {
29
30
  readonly util: DocumentsWorkflowRuntimeUtilInput;
30
31
  }
31
32
  export interface DocumentsWorkflowRuntimeInput extends DocumentsWorkflowRuntimeInputGroups {
32
- /** Private host custody, inherited without exposing it on runtime views. */
33
+ /** Private host custody, held by the runtime's policy service and never exposed on runtime views. */
33
34
  readonly withPrincipalHistoryProtection?: PrincipalHistoryProtectionLease | undefined;
34
35
  readonly apiClient: ApiClient;
35
36
  readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
36
37
  }
38
+ /** A runtime snapshot whose producer already bound its policy service, such as `workflowInput()`. */
39
+ export interface DocumentsWorkflowRuntimeSnapshot extends DocumentsWorkflowRuntimeInputGroups {
40
+ readonly apiClient: ApiClient;
41
+ readonly principalPolicies: PrincipalPolicyService;
42
+ readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
43
+ }
37
44
  export interface DocumentsWorkflowRuntime extends DocumentsWorkflowRuntimeGroups {
38
45
  readonly apiClient: ApiClient;
39
46
  /** Bound to this snapshot's API client, executor, and key material. */
40
47
  readonly blobAttachments: BlobAttachmentService;
48
+ /** Bound to this snapshot's API client, executor, and history custody. */
49
+ readonly principalPolicies: PrincipalPolicyService;
41
50
  readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
42
51
  }
52
+ /** Standalone hosts supply their own lease; the view never carries it. */
43
53
  export declare function createDocumentsWorkflowRuntime(input: DocumentsWorkflowRuntimeInput): DocumentsWorkflowRuntime;
54
+ export declare function createDocumentsWorkflowRuntimeFromSnapshot(snapshot: DocumentsWorkflowRuntimeSnapshot): DocumentsWorkflowRuntime;
44
55
  export {};
@@ -1,28 +1,36 @@
1
1
  import { resolveDocumentProjectorRegistry, } from "../../data/documents/documentKinds.js";
2
- import { inheritPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
3
2
  import { requireTrustedUserIdentityResolver, } from "../../data/trustedUserIdentity/index.js";
4
3
  import { BlobAttachmentService } from "../blobs/blobAttachmentService.js";
4
+ import { PrincipalPolicyService } from "../principals/principalPolicyService.js";
5
+ /** Standalone hosts supply their own lease; the view never carries it. */
5
6
  export function createDocumentsWorkflowRuntime(input) {
6
- const documentProjectors = resolveDocumentProjectorRegistry(input.infra.documentProjectors);
7
+ return createDocumentsWorkflowRuntimeFromSnapshot({
8
+ ...input,
9
+ principalPolicies: new PrincipalPolicyService(input),
10
+ });
11
+ }
12
+ export function createDocumentsWorkflowRuntimeFromSnapshot(snapshot) {
13
+ const documentProjectors = resolveDocumentProjectorRegistry(snapshot.infra.documentProjectors);
7
14
  const infra = {
8
- ...input.infra,
15
+ ...snapshot.infra,
9
16
  documentProjectors,
10
17
  };
11
- return inheritPrincipalHistoryProtection(input, {
12
- apiClient: input.apiClient,
18
+ return {
19
+ apiClient: snapshot.apiClient,
13
20
  blobAttachments: new BlobAttachmentService({
14
- api: input.apiClient,
15
- encapsulationSecretKey: input.crypto.encapsulationKeyPair?.secretKey ?? null,
16
- execSql: input.infra.execSql,
17
- log: input.util.log,
18
- reportSecurityIncident: input.util.reportSecurityIncident,
21
+ api: snapshot.apiClient,
22
+ encapsulationSecretKey: snapshot.crypto.encapsulationKeyPair?.secretKey ?? null,
23
+ execSql: snapshot.infra.execSql,
24
+ log: snapshot.util.log,
25
+ reportSecurityIncident: snapshot.util.reportSecurityIncident,
19
26
  }),
20
- auth: input.auth,
21
- crypto: input.crypto,
27
+ auth: snapshot.auth,
28
+ crypto: snapshot.crypto,
22
29
  infra,
23
- resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(input.resolveTrustedUserIdentity),
24
- state: input.state,
25
- util: input.util,
26
- });
30
+ principalPolicies: snapshot.principalPolicies,
31
+ resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(snapshot.resolveTrustedUserIdentity),
32
+ state: snapshot.state,
33
+ util: snapshot.util,
34
+ };
27
35
  }
28
36
  //# sourceMappingURL=runtime.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,gCAAgC,GACjC,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EACL,kCAAkC,GAEnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AA2DvE,MAAM,UAAU,8BAA8B,CAC5C,KAAoC;IAEpC,MAAM,kBAAkB,GAAG,gCAAgC,CACzD,KAAK,CAAC,KAAK,CAAC,kBAAkB,CAC/B,CAAC;IACF,MAAM,KAAK,GAAG;QACZ,GAAG,KAAK,CAAC,KAAK;QACd,kBAAkB;KACnB,CAAC;IAEF,OAAO,iCAAiC,CAAC,KAAK,EAAE;QAC9C,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,eAAe,EAAE,IAAI,qBAAqB,CAAC;YACzC,GAAG,EAAE,KAAK,CAAC,SAAS;YACpB,sBAAsB,EACpB,KAAK,CAAC,MAAM,CAAC,oBAAoB,EAAE,SAAS,IAAI,IAAI;YACtD,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO;YAC5B,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG;YACnB,sBAAsB,EAAE,KAAK,CAAC,IAAI,CAAC,sBAAsB;SAC1D,CAAC;QACF,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,KAAK;QACL,0BAA0B,EAAE,kCAAkC,CAC5D,KAAK,CAAC,0BAA0B,CACjC;QACD,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,IAAI,EAAE,KAAK,CAAC,IAAI;KACjB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../data/documents/documentKinds\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { inheritPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport { BlobAttachmentService } from \"../blobs/blobAttachmentService\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../shared/runtimeInput\";\n\ninterface DocumentsWorkflowRuntimeUtilInput\n extends Omit<WorkflowRuntimeUtilInput, \"logError\"> {\n /** Receives handled quarantine errors without converting them to strings. */\n readonly logError?: WorkflowRuntimeUtilInput[\"logError\"] | undefined;\n}\n\nexport interface DocumentsWorkflowRuntimeInfra\n extends Omit<WorkflowRuntimeInfraInput, \"dbStatus\"> {\n readonly dbStatus: string;\n}\n\ninterface DocumentsWorkflowRuntimeInputInfra\n extends Omit<DocumentsWorkflowRuntimeInfra, \"documentProjectors\"> {\n readonly documentProjectors: DocumentProjectorRegistryInput;\n}\n\nexport interface DocumentsWorkflowRuntimeGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: DocumentsWorkflowRuntimeInfra;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: DocumentsWorkflowRuntimeUtilInput;\n}\n\nexport interface DocumentsWorkflowRuntimeInputGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: DocumentsWorkflowRuntimeInputInfra;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: DocumentsWorkflowRuntimeUtilInput;\n}\n\nexport interface DocumentsWorkflowRuntimeInput\n extends DocumentsWorkflowRuntimeInputGroups {\n /** Private host custody, inherited without exposing it on runtime views. */\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport interface DocumentsWorkflowRuntime\n extends DocumentsWorkflowRuntimeGroups {\n readonly apiClient: ApiClient;\n /** Bound to this snapshot's API client, executor, and key material. */\n readonly blobAttachments: BlobAttachmentService;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport function createDocumentsWorkflowRuntime(\n input: DocumentsWorkflowRuntimeInput,\n): DocumentsWorkflowRuntime {\n const documentProjectors = resolveDocumentProjectorRegistry(\n input.infra.documentProjectors,\n );\n const infra = {\n ...input.infra,\n documentProjectors,\n };\n\n return inheritPrincipalHistoryProtection(input, {\n apiClient: input.apiClient,\n blobAttachments: new BlobAttachmentService({\n api: input.apiClient,\n encapsulationSecretKey:\n input.crypto.encapsulationKeyPair?.secretKey ?? null,\n execSql: input.infra.execSql,\n log: input.util.log,\n reportSecurityIncident: input.util.reportSecurityIncident,\n }),\n auth: input.auth,\n crypto: input.crypto,\n infra,\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n ),\n state: input.state,\n util: input.util,\n });\n}\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,gCAAgC,GACjC,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACL,kCAAkC,GAEnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAqE9E,0EAA0E;AAC1E,MAAM,UAAU,8BAA8B,CAC5C,KAAoC;IAEpC,OAAO,0CAA0C,CAAC;QAChD,GAAG,KAAK;QACR,iBAAiB,EAAE,IAAI,sBAAsB,CAAC,KAAK,CAAC;KACrD,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,0CAA0C,CACxD,QAA0C;IAE1C,MAAM,kBAAkB,GAAG,gCAAgC,CACzD,QAAQ,CAAC,KAAK,CAAC,kBAAkB,CAClC,CAAC;IACF,MAAM,KAAK,GAAG;QACZ,GAAG,QAAQ,CAAC,KAAK;QACjB,kBAAkB;KACnB,CAAC;IAEF,OAAO;QACL,SAAS,EAAE,QAAQ,CAAC,SAAS;QAC7B,eAAe,EAAE,IAAI,qBAAqB,CAAC;YACzC,GAAG,EAAE,QAAQ,CAAC,SAAS;YACvB,sBAAsB,EACpB,QAAQ,CAAC,MAAM,CAAC,oBAAoB,EAAE,SAAS,IAAI,IAAI;YACzD,OAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,OAAO;YAC/B,GAAG,EAAE,QAAQ,CAAC,IAAI,CAAC,GAAG;YACtB,sBAAsB,EAAE,QAAQ,CAAC,IAAI,CAAC,sBAAsB;SAC7D,CAAC;QACF,IAAI,EAAE,QAAQ,CAAC,IAAI;QACnB,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,KAAK;QACL,iBAAiB,EAAE,QAAQ,CAAC,iBAAiB;QAC7C,0BAA0B,EAAE,kCAAkC,CAC5D,QAAQ,CAAC,0BAA0B,CACpC;QACD,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,IAAI,EAAE,QAAQ,CAAC,IAAI;KACpB,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../data/documents/documentKinds\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport { BlobAttachmentService } from \"../blobs/blobAttachmentService\";\nimport { PrincipalPolicyService } from \"../principals/principalPolicyService\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../shared/runtimeInput\";\n\ninterface DocumentsWorkflowRuntimeUtilInput\n extends Omit<WorkflowRuntimeUtilInput, \"logError\"> {\n /** Receives handled quarantine errors without converting them to strings. */\n readonly logError?: WorkflowRuntimeUtilInput[\"logError\"] | undefined;\n}\n\nexport interface DocumentsWorkflowRuntimeInfra\n extends Omit<WorkflowRuntimeInfraInput, \"dbStatus\"> {\n readonly dbStatus: string;\n}\n\ninterface DocumentsWorkflowRuntimeInputInfra\n extends Omit<DocumentsWorkflowRuntimeInfra, \"documentProjectors\"> {\n readonly documentProjectors: DocumentProjectorRegistryInput;\n}\n\nexport interface DocumentsWorkflowRuntimeGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: DocumentsWorkflowRuntimeInfra;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: DocumentsWorkflowRuntimeUtilInput;\n}\n\nexport interface DocumentsWorkflowRuntimeInputGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: DocumentsWorkflowRuntimeInputInfra;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: DocumentsWorkflowRuntimeUtilInput;\n}\n\nexport interface DocumentsWorkflowRuntimeInput\n extends DocumentsWorkflowRuntimeInputGroups {\n /** Private host custody, held by the runtime's policy service and never exposed on runtime views. */\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\n/** A runtime snapshot whose producer already bound its policy service, such as `workflowInput()`. */\nexport interface DocumentsWorkflowRuntimeSnapshot\n extends DocumentsWorkflowRuntimeInputGroups {\n readonly apiClient: ApiClient;\n readonly principalPolicies: PrincipalPolicyService;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport interface DocumentsWorkflowRuntime\n extends DocumentsWorkflowRuntimeGroups {\n readonly apiClient: ApiClient;\n /** Bound to this snapshot's API client, executor, and key material. */\n readonly blobAttachments: BlobAttachmentService;\n /** Bound to this snapshot's API client, executor, and history custody. */\n readonly principalPolicies: PrincipalPolicyService;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\n/** Standalone hosts supply their own lease; the view never carries it. */\nexport function createDocumentsWorkflowRuntime(\n input: DocumentsWorkflowRuntimeInput,\n): DocumentsWorkflowRuntime {\n return createDocumentsWorkflowRuntimeFromSnapshot({\n ...input,\n principalPolicies: new PrincipalPolicyService(input),\n });\n}\n\nexport function createDocumentsWorkflowRuntimeFromSnapshot(\n snapshot: DocumentsWorkflowRuntimeSnapshot,\n): DocumentsWorkflowRuntime {\n const documentProjectors = resolveDocumentProjectorRegistry(\n snapshot.infra.documentProjectors,\n );\n const infra = {\n ...snapshot.infra,\n documentProjectors,\n };\n\n return {\n apiClient: snapshot.apiClient,\n blobAttachments: new BlobAttachmentService({\n api: snapshot.apiClient,\n encapsulationSecretKey:\n snapshot.crypto.encapsulationKeyPair?.secretKey ?? null,\n execSql: snapshot.infra.execSql,\n log: snapshot.util.log,\n reportSecurityIncident: snapshot.util.reportSecurityIncident,\n }),\n auth: snapshot.auth,\n crypto: snapshot.crypto,\n infra,\n principalPolicies: snapshot.principalPolicies,\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n snapshot.resolveTrustedUserIdentity,\n ),\n state: snapshot.state,\n util: snapshot.util,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { DomainScope } from "../../../data/shared/domainScope.js";
2
2
  import { type SyncLane } from "../../../data/sync/syncCoordinator.js";
3
- import type { PrincipalPolicyOperation } from "../../principals/runtimePolicyWarmer.js";
3
+ import type { PrincipalPolicyOperation } from "../../principals/principalPolicyService.js";
4
4
  export { sequenceUnchanged } from "../../../data/sync/sequence.js";
5
5
  export type DocumentSyncLane = SyncLane;
6
6
  export declare function registerDocumentSyncLane(input: {
@@ -1 +1 @@
1
- {"version":3,"file":"syncLane.js","sourceRoot":"","sources":["syncLane.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAE3B,MAAM,oCAAoC,CAAC;AAG5C,uEAAuE;AACvE,uEAAuE;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAIhE,SAAS,sBAAsB,CAAC,OAAe;IAC7C,OAAO,aAAa,OAAO,EAAE,CAAC;AAChC,CAAC;AAED,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OAAO,CAAC,SAAS,CAAC,CAAC;QACrB,CAAC,CAAC;QACF,MAAM,WAAW,GAAG,GAAG,EAAE;YACvB,IAAI,OAAO,EAAE,CAAC;gBACZ,OAAO;YACT,CAAC;YACD,KAAK,CAAC,aAAa,EAAE,EAAE,CAAC;YACxB,MAAM,CAAC,KAAK,CAAC,CAAC;QAChB,CAAC,CAAC;QACF,MAAM,OAAO,GAAG,GAAG,EAAE;YACnB,MAAM,OAAO,GAAG,mBAAmB,CACjC,WAAW,EACX,OAAO,EACP,gBAAgB,CACjB,CAAC;YACF,IAAI,OAAO,KAAK,OAAO,EAAE,CAAC;gBACxB,WAAW,EAAE,CAAC;gBACd,OAAO;YACT,CAAC;YACD,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;gBAC1B,MAAM,CAAC,OAAO,KAAK,WAAW,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC,CAAC;YAChE,CAAC;QACH,CAAC,CAAC;QACF,WAAW,GAAG,WAAW,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QAC7C,KAAK,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACrE,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;YAC1B,WAAW,EAAE,CAAC;YACd,OAAO;QACT,CAAC;QACD,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n type SyncLane,\n} from \"../../../data/sync/syncCoordinator\";\nimport type { PrincipalPolicyOperation } from \"../../principals/runtimePolicyWarmer\";\n\n// Facade re-export: document stores must reach this shared sync helper\n// through this workflow boundary, not by importing data/sync directly.\nexport { sequenceUnchanged } from \"../../../data/sync/sequence\";\n\nexport type DocumentSyncLane = SyncLane;\n\nfunction getDocumentSyncLaneKey(localId: string): string {\n return `documents:${localId}`;\n}\n\nexport function registerDocumentSyncLane(input: {\n readonly domainScope: DomainScope;\n readonly localId: string;\n /** Host diagnostics sink; bare runtimes do not structure errors. */\n readonly logError?: ((message: string, error: unknown) => void) | undefined;\n /**\n * Receives the coordinator drain's pass token, which is the principal-policy\n * operation of every sync this run performs.\n */\n readonly run: (policyOperation: PrincipalPolicyOperation) => Promise<void>;\n readonly priority?: (() => number) | undefined;\n}): DocumentSyncLane {\n return getOrCreateDomainSyncCoordinator(input.domainScope).registerLane(\n getDocumentSyncLaneKey(input.localId),\n {\n label: `Document ${input.localId}`,\n onUnexpectedError: (error) => {\n console.error(`Failed to sync document ${input.localId}:`, error);\n },\n phase: \"document\",\n priority: input.priority,\n // Fixed literal: the local id stays in the console line above, never in\n // a report. The mapped stack identifies which lane body threw. Returning\n // the host's result hands a rejection to the lane reporter's wrapper;\n // discarding it would surface as an unhandled rejection instead.\n reportUnexpectedError: (error) =>\n input.logError?.(\"Documents: sync lane failed\", error),\n run: input.run,\n shouldIgnoreError: isDatabaseUnavailableError,\n },\n );\n}\n\n/**\n * How the run requested after `baselineRunCount` ended: abort when the lane\n * or its coordinator is gone or the run was abandoned, pending until a later\n * run settles.\n */\nfunction requestedRunOutcome(\n coordinator: ReturnType<typeof getOrCreateDomainSyncCoordinator>,\n laneKey: string,\n baselineRunCount: number,\n): \"abort\" | \"pending\" | \"completed\" | \"failed\" {\n if (coordinator.isDisposed()) return \"abort\";\n const lane = coordinator\n .getSnapshot()\n .lanes.find((candidate) => candidate.key === laneKey);\n if (!lane || lane.runAbandoned) return \"abort\";\n if (lane.runCount <= baselineRunCount || lane.running || lane.requested) {\n return \"pending\";\n }\n if (lane.lastAction === \"completed\" || lane.lastAction === \"failed\") {\n return lane.lastAction;\n }\n return \"pending\";\n}\n\nexport function requestDocumentSyncLaneAndWait(input: {\n readonly didCompleteRequest: () => boolean;\n readonly domainScope: DomainScope;\n readonly localId: string;\n readonly onInvalidated?: (() => void) | undefined;\n readonly request: () => void;\n readonly signal?: AbortSignal | undefined;\n}): Promise<boolean> {\n if (input.signal?.aborted) {\n input.onInvalidated?.();\n return Promise.resolve(false);\n }\n const coordinator = getOrCreateDomainSyncCoordinator(input.domainScope);\n const laneKey = getDocumentSyncLaneKey(input.localId);\n const initialLane = coordinator\n .getSnapshot()\n .lanes.find((lane) => lane.key === laneKey);\n if (!initialLane) {\n return Promise.resolve(false);\n }\n if (initialLane.runAbandoned) {\n return Promise.resolve(false);\n }\n const baselineRunCount = initialLane.runCount;\n return new Promise((resolve) => {\n let settled = false;\n let unsubscribe: () => void = () => undefined;\n const finish = (completed: boolean) => {\n if (settled) {\n return;\n }\n settled = true;\n unsubscribe();\n input.signal?.removeEventListener(\"abort\", handleAbort);\n resolve(completed);\n };\n const handleAbort = () => {\n if (settled) {\n return;\n }\n input.onInvalidated?.();\n finish(false);\n };\n const inspect = () => {\n const outcome = requestedRunOutcome(\n coordinator,\n laneKey,\n baselineRunCount,\n );\n if (outcome === \"abort\") {\n handleAbort();\n return;\n }\n if (outcome !== \"pending\") {\n finish(outcome === \"completed\" && input.didCompleteRequest());\n }\n };\n unsubscribe = coordinator.subscribe(inspect);\n input.signal?.addEventListener(\"abort\", handleAbort, { once: true });\n if (input.signal?.aborted) {\n handleAbort();\n return;\n }\n input.request();\n inspect();\n });\n}\n"]}
1
+ {"version":3,"file":"syncLane.js","sourceRoot":"","sources":["syncLane.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAE3B,MAAM,oCAAoC,CAAC;AAG5C,uEAAuE;AACvE,uEAAuE;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAIhE,SAAS,sBAAsB,CAAC,OAAe;IAC7C,OAAO,aAAa,OAAO,EAAE,CAAC;AAChC,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,KAWxC;IACC,OAAO,gCAA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ACF,MAAM,WAAW,GAAG,GAAG,EAAE;YACvB,IAAI,OAAO,EAAE,CAAC;gBACZ,OAAO;YACT,CAAC;YACD,KAAK,CAAC,aAAa,EAAE,EAAE,CAAC;YACxB,MAAM,CAAC,KAAK,CAAC,CAAC;QAChB,CAAC,CAAC;QACF,MAAM,OAAO,GAAG,GAAG,EAAE;YACnB,MAAM,OAAO,GAAG,mBAAmB,CACjC,WAAW,EACX,OAAO,EACP,gBAAgB,CACjB,CAAC;YACF,IAAI,OAAO,KAAK,OAAO,EAAE,CAAC;gBACxB,WAAW,EAAE,CAAC;gBACd,OAAO;YACT,CAAC;YACD,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;gBAC1B,MAAM,CAAC,OAAO,KAAK,WAAW,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC,CAAC;YAChE,CAAC;QACH,CAAC,CAAC;QACF,WAAW,GAAG,WAAW,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QAC7C,KAAK,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACrE,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;YAC1B,WAAW,EAAE,CAAC;YACd,OAAO;QACT,CAAC;QACD,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n type SyncLane,\n} from \"../../../data/sync/syncCoordinator\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\n\n// Facade re-export: document stores must reach this shared sync helper\n// through this workflow boundary, not by importing data/sync directly.\nexport { sequenceUnchanged } from \"../../../data/sync/sequence\";\n\nexport type DocumentSyncLane = SyncLane;\n\nfunction getDocumentSyncLaneKey(localId: string): string {\n return `documents:${localId}`;\n}\n\nexport function registerDocumentSyncLane(input: {\n readonly domainScope: DomainScope;\n readonly localId: string;\n /** Host diagnostics sink; bare runtimes do not structure errors. */\n readonly logError?: ((message: string, error: unknown) => void) | undefined;\n /**\n * Receives the coordinator drain's pass token, which is the principal-policy\n * operation of every sync this run performs.\n */\n readonly run: (policyOperation: PrincipalPolicyOperation) => Promise<void>;\n readonly priority?: (() => number) | undefined;\n}): DocumentSyncLane {\n return getOrCreateDomainSyncCoordinator(input.domainScope).registerLane(\n getDocumentSyncLaneKey(input.localId),\n {\n label: `Document ${input.localId}`,\n onUnexpectedError: (error) => {\n console.error(`Failed to sync document ${input.localId}:`, error);\n },\n phase: \"document\",\n priority: input.priority,\n // Fixed literal: the local id stays in the console line above, never in\n // a report. The mapped stack identifies which lane body threw. Returning\n // the host's result hands a rejection to the lane reporter's wrapper;\n // discarding it would surface as an unhandled rejection instead.\n reportUnexpectedError: (error) =>\n input.logError?.(\"Documents: sync lane failed\", error),\n run: input.run,\n shouldIgnoreError: isDatabaseUnavailableError,\n },\n );\n}\n\n/**\n * How the run requested after `baselineRunCount` ended: abort when the lane\n * or its coordinator is gone or the run was abandoned, pending until a later\n * run settles.\n */\nfunction requestedRunOutcome(\n coordinator: ReturnType<typeof getOrCreateDomainSyncCoordinator>,\n laneKey: string,\n baselineRunCount: number,\n): \"abort\" | \"pending\" | \"completed\" | \"failed\" {\n if (coordinator.isDisposed()) return \"abort\";\n const lane = coordinator\n .getSnapshot()\n .lanes.find((candidate) => candidate.key === laneKey);\n if (!lane || lane.runAbandoned) return \"abort\";\n if (lane.runCount <= baselineRunCount || lane.running || lane.requested) {\n return \"pending\";\n }\n if (lane.lastAction === \"completed\" || lane.lastAction === \"failed\") {\n return lane.lastAction;\n }\n return \"pending\";\n}\n\nexport function requestDocumentSyncLaneAndWait(input: {\n readonly didCompleteRequest: () => boolean;\n readonly domainScope: DomainScope;\n readonly localId: string;\n readonly onInvalidated?: (() => void) | undefined;\n readonly request: () => void;\n readonly signal?: AbortSignal | undefined;\n}): Promise<boolean> {\n if (input.signal?.aborted) {\n input.onInvalidated?.();\n return Promise.resolve(false);\n }\n const coordinator = getOrCreateDomainSyncCoordinator(input.domainScope);\n const laneKey = getDocumentSyncLaneKey(input.localId);\n const initialLane = coordinator\n .getSnapshot()\n .lanes.find((lane) => lane.key === laneKey);\n if (!initialLane) {\n return Promise.resolve(false);\n }\n if (initialLane.runAbandoned) {\n return Promise.resolve(false);\n }\n const baselineRunCount = initialLane.runCount;\n return new Promise((resolve) => {\n let settled = false;\n let unsubscribe: () => void = () => undefined;\n const finish = (completed: boolean) => {\n if (settled) {\n return;\n }\n settled = true;\n unsubscribe();\n input.signal?.removeEventListener(\"abort\", handleAbort);\n resolve(completed);\n };\n const handleAbort = () => {\n if (settled) {\n return;\n }\n input.onInvalidated?.();\n finish(false);\n };\n const inspect = () => {\n const outcome = requestedRunOutcome(\n coordinator,\n laneKey,\n baselineRunCount,\n );\n if (outcome === \"abort\") {\n handleAbort();\n return;\n }\n if (outcome !== \"pending\") {\n finish(outcome === \"completed\" && input.didCompleteRequest());\n }\n };\n unsubscribe = coordinator.subscribe(inspect);\n input.signal?.addEventListener(\"abort\", handleAbort, { once: true });\n if (input.signal?.aborted) {\n handleAbort();\n return;\n }\n input.request();\n inspect();\n });\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  import { type ReferencedPrincipalHead } from "../../internal/crypto/index.js";
2
2
  import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
3
- import type { createRuntimePrincipalPolicyCurrentResolver, ResolvedPrincipalPolicyCurrent } from "../principals/runtimePolicyRecovery.js";
4
- type CurrentPolicyResolver = NonNullable<ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>>;
3
+ import type { PrincipalPolicyCurrentResolver as CurrentPolicyResolver, ResolvedPrincipalPolicyCurrent } from "../principals/runtimePolicyRecovery.js";
5
4
  interface CurrentOrganizationAuthorityInput {
6
5
  readonly execSql: ExecSql;
7
6
  readonly organizationId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"currentOrganizationAuthority.js","sourceRoot":"","sources":["currentOrganizationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,uEAAuE,CAAC;AAC3H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAoB/D,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAwC;IAExC,IAAI,KAAK,CAAC,qBAAqB;QAC7B,oBAAoB,CAClB,KAAK,CAAC,qBAAqB,EAC3B,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,MAAM,aAAa,GAAG,KAAK,CAAC,aAAa,IAAI,EAAE,CAAC;IAChD,MAAM,OAAO,GAAG,CAAC,SAA0C,EAAE,EAAE,CAC7D,KAAK,CAAC,oBAAoB,CAAC;QACzB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,SAAS,IAAI,SAAS;QACjC,kBAAkB,EAAE,IAAI;QACxB,aAAa;QACb,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACL,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;IAC7D,MAAM,kBAAkB,CACtB,SAAS,EACT,KAAK,CAAC,qBAAqB,IAAI,SAAS,CAAC,MAAM,CAAC,KAAK,CACtD,CAAC;IACF,MAAM,UAAU,GAAG,oCAAoC,CACrD,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,UAAU,CAC5C,CAAC;IACF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C,EACrC,SAAyC;IAEzC,MAAM,UAAU,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACxC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,cAAc;QACvC,MAAM,CAAC,WAAW,KAAK,SAAS,CAAC,MAAM,CAAC,WAAW,CACtD,CAAC;IACF,IACE,CAAC,UAAU;QACX,CAAC,6BAA6B,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC;QAExE,MAAM,IAAI,oCAAoC,CAC5C,4DAA4D,CAC7D,CAAC;AACN,CAAC;AAED,SAAS,sBAAsB,CAC7B,KAAqC,EACrC,QAAiC;IAEjC,MAAM,SAAS,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACvC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,OAAO;QAChC,MAAM,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,SAAS,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC;QACzE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,wDAAwD,CACzD,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type {\n createRuntimePrincipalPolicyCurrentResolver,\n ResolvedPrincipalPolicyCurrent,\n} from \"../principals/runtimePolicyRecovery\";\n\ntype CurrentPolicyResolver = NonNullable<\n ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>\n>;\n\ninterface CurrentOrganizationAuthorityInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly organizationReference?: ReferencedPrincipalHead | null | undefined;\n readonly resolveCurrentPolicy: CurrentPolicyResolver;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/** One directory view with bounded, authenticated current artifacts for its groups. */\nexport async function loadCurrentOrganizationAuthority(\n input: CurrentOrganizationAuthorityInput,\n) {\n if (input.organizationReference)\n assertReferenceScope(\n input.organizationReference,\n \"organization\",\n input.organizationId,\n );\n const recoveryBatch = input.recoveryBatch ?? {};\n const resolve = (reference?: ReferencedPrincipalHead | null) =>\n input.resolveCurrentPolicy({\n organizationId: input.organizationId,\n reference: reference ?? undefined,\n preferLocalCurrent: true,\n recoveryBatch,\n stillCurrent: input.stillCurrent,\n });\n const directory = await resolve(input.organizationReference);\n await assertExactCurrent(\n directory,\n input.organizationReference ?? directory.policy.state,\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.current.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization current policy payload is outside its scope\",\n );\n const adminHead = requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n );\n const admins = await resolve(adminHead);\n await assertExactCurrent(admins, adminHead);\n assertDirectoryDependency(admins, directory);\n const stillCurrent = () =>\n input.stillCurrent() && directory.stillCurrent() && admins.stillCurrent();\n const validate = async (value: ResolvedPrincipalPolicyCurrent) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: [],\n policies: [...value.dependencies, value.policy],\n stillCurrent: () => stillCurrent() && value.stillCurrent(),\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && value.stillCurrent(),\n );\n };\n await validate(admins);\n return {\n admins,\n descriptor,\n directory,\n stillCurrent,\n async readGroup(groupId: string, reference?: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const head = requireOrganizationGroupHead(descriptor, groupId);\n const selected = reference ?? head;\n assertReferenceScope(selected, \"group\", groupId);\n const result =\n groupId === descriptor.adminGroupId &&\n principalHeadMatchesReference(admins.policy.state, selected)\n ? admins\n : await resolve(selected);\n await assertExactCurrent(result, head);\n assertDirectoryDependency(result, directory);\n if (groupId !== descriptor.adminGroupId)\n assertAdminsDependency(result, adminHead);\n await validate(result);\n return result;\n },\n };\n}\n\nfunction assertReferenceScope(\n reference: ReferencedPrincipalHead,\n principalType: ReferencedPrincipalHead[\"principalType\"],\n principalId: string,\n) {\n if (\n reference.principalType !== principalType ||\n reference.principalId !== principalId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n}\n\nasync function assertExactCurrent(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n assertProjectionVerificationCurrent(value.stillCurrent);\n await assertCurrentMatchesVerifiedPolicy(value);\n if (!principalHeadMatchesReference(value.policy.state, expected))\n throw new ProjectionDependencyUnavailableError(\n \"Current policy changed from the selected organization directory\",\n );\n assertProjectionVerificationCurrent(value.stillCurrent);\n}\n\nfunction assertDirectoryDependency(\n value: ResolvedPrincipalPolicyCurrent,\n directory: ResolvedPrincipalPolicyCurrent,\n) {\n const dependency = value.dependencies.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === directory.policy.principalId,\n );\n if (\n !dependency ||\n !principalHeadMatchesReference(dependency.state, directory.policy.state)\n )\n throw new ProjectionDependencyUnavailableError(\n \"Current policy belongs to a changed organization directory\",\n );\n}\n\nfunction assertAdminsDependency(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n const authority = value.dependencies.find(\n (policy) =>\n policy.principalType === \"group\" &&\n policy.principalId === expected.principalId,\n );\n if (!authority || !principalHeadMatchesReference(authority.state, expected))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Current group policy omits its exact Admins dependency\",\n );\n}\n"]}
1
+ {"version":3,"file":"currentOrganizationAuthority.js","sourceRoot":"","sources":["currentOrganizationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,uEAAuE,CAAC;AAC3H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAgB/D,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAwC;IAExC,IAAI,KAAK,CAAC,qBAAqB;QAC7B,oBAAoB,CAClB,KAAK,CAAC,qBAAqB,EAC3B,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,MAAM,aAAa,GAAG,KAAK,CAAC,aAAa,IAAI,EAAE,CAAC;IAChD,MAAM,OAAO,GAAG,CAAC,SAA0C,EAAE,EAAE,CAC7D,KAAK,CAAC,oBAAoB,CAAC;QACzB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,SAAS,IAAI,SAAS;QACjC,kBAAkB,EAAE,IAAI;QACxB,aAAa;QACb,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACL,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;IAC7D,MAAM,kBAAkB,CACtB,SAAS,EAC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AAE,QAAQ,CAAC;QAC9D,MAAM,IAAI,oCAAoC,CAC5C,iEAAiE,CAClE,CAAC;IACJ,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;AAC1D,CAAC;AAED,SAAS,yBAAyB,CAChC,KAAqC,EACrC,SAAyC;IAEzC,MAAM,UAAU,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACxC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,cAAc;QACvC,MAAM,CAAC,WAAW,KAAK,SAAS,CAAC,MAAM,CAAC,WAAW,CACtD,CAAC;IACF,IACE,CAAC,UAAU;QACX,CAAC,6BAA6B,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC;QAExE,MAAM,IAAI,oCAAoC,CAC5C,4DAA4D,CAC7D,CAAC;AACN,CAAC;AAED,SAAS,sBAAsB,CAC7B,KAAqC,EACrC,QAAiC;IAEjC,MAAM,SAAS,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACvC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,OAAO;QAChC,MAAM,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,SAAS,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC;QACzE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,wDAAwD,CACzD,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type {\n PrincipalPolicyCurrentResolver as CurrentPolicyResolver,\n ResolvedPrincipalPolicyCurrent,\n} from \"../principals/runtimePolicyRecovery\";\n\ninterface CurrentOrganizationAuthorityInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly organizationReference?: ReferencedPrincipalHead | null | undefined;\n readonly resolveCurrentPolicy: CurrentPolicyResolver;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/** One directory view with bounded, authenticated current artifacts for its groups. */\nexport async function loadCurrentOrganizationAuthority(\n input: CurrentOrganizationAuthorityInput,\n) {\n if (input.organizationReference)\n assertReferenceScope(\n input.organizationReference,\n \"organization\",\n input.organizationId,\n );\n const recoveryBatch = input.recoveryBatch ?? {};\n const resolve = (reference?: ReferencedPrincipalHead | null) =>\n input.resolveCurrentPolicy({\n organizationId: input.organizationId,\n reference: reference ?? undefined,\n preferLocalCurrent: true,\n recoveryBatch,\n stillCurrent: input.stillCurrent,\n });\n const directory = await resolve(input.organizationReference);\n await assertExactCurrent(\n directory,\n input.organizationReference ?? directory.policy.state,\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.current.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization current policy payload is outside its scope\",\n );\n const adminHead = requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n );\n const admins = await resolve(adminHead);\n await assertExactCurrent(admins, adminHead);\n assertDirectoryDependency(admins, directory);\n const stillCurrent = () =>\n input.stillCurrent() && directory.stillCurrent() && admins.stillCurrent();\n const validate = async (value: ResolvedPrincipalPolicyCurrent) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: [],\n policies: [...value.dependencies, value.policy],\n stillCurrent: () => stillCurrent() && value.stillCurrent(),\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && value.stillCurrent(),\n );\n };\n await validate(admins);\n return {\n admins,\n descriptor,\n directory,\n stillCurrent,\n async readGroup(groupId: string, reference?: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const head = requireOrganizationGroupHead(descriptor, groupId);\n const selected = reference ?? head;\n assertReferenceScope(selected, \"group\", groupId);\n const result =\n groupId === descriptor.adminGroupId &&\n principalHeadMatchesReference(admins.policy.state, selected)\n ? admins\n : await resolve(selected);\n await assertExactCurrent(result, head);\n assertDirectoryDependency(result, directory);\n if (groupId !== descriptor.adminGroupId)\n assertAdminsDependency(result, adminHead);\n await validate(result);\n return result;\n },\n };\n}\n\nfunction assertReferenceScope(\n reference: ReferencedPrincipalHead,\n principalType: ReferencedPrincipalHead[\"principalType\"],\n principalId: string,\n) {\n if (\n reference.principalType !== principalType ||\n reference.principalId !== principalId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n}\n\nasync function assertExactCurrent(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n assertProjectionVerificationCurrent(value.stillCurrent);\n await assertCurrentMatchesVerifiedPolicy(value);\n if (!principalHeadMatchesReference(value.policy.state, expected))\n throw new ProjectionDependencyUnavailableError(\n \"Current policy changed from the selected organization directory\",\n );\n assertProjectionVerificationCurrent(value.stillCurrent);\n}\n\nfunction assertDirectoryDependency(\n value: ResolvedPrincipalPolicyCurrent,\n directory: ResolvedPrincipalPolicyCurrent,\n) {\n const dependency = value.dependencies.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === directory.policy.principalId,\n );\n if (\n !dependency ||\n !principalHeadMatchesReference(dependency.state, directory.policy.state)\n )\n throw new ProjectionDependencyUnavailableError(\n \"Current policy belongs to a changed organization directory\",\n );\n}\n\nfunction assertAdminsDependency(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n const authority = value.dependencies.find(\n (policy) =>\n policy.principalType === \"group\" &&\n policy.principalId === expected.principalId,\n );\n if (!authority || !principalHeadMatchesReference(authority.state, expected))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Current group policy omits its exact Admins dependency\",\n );\n}\n"]}
@@ -2,18 +2,19 @@ import type { EncapsulationKeyPair } from "../../../internal/crypto/index.js";
2
2
  import type { SecurityIncidentReporter } from "../../../data/shared/securityIncidents.js";
3
3
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
4
4
  import type { TrustedUserIdentityResolver } from "../../../data/trustedUserIdentity/index.js";
5
- import { createRuntimePrincipalPolicyCurrentResolver, type PrincipalPolicyRecoveryRuntime } from "../../principals/runtimePolicyRecovery.js";
5
+ import type { PrincipalPolicyService } from "../../principals/principalPolicyService.js";
6
+ import type { PrincipalPolicyCurrentResolver } from "../../principals/runtimePolicyRecovery.js";
6
7
  import type { PrincipalPolicyReadApi } from "../groupPolicy/groupPolicyMutationContext.js";
7
8
  import { type GroupMetadataAccessInput } from "./groupMetadataAccess.js";
8
9
  interface GroupMetadataRuntime {
9
- readonly state?: PrincipalPolicyRecoveryRuntime["state"];
10
- readonly apiClient: GroupMetadataAccessInput["apiClient"] & PrincipalPolicyReadApi & PrincipalPolicyRecoveryRuntime["apiClient"];
10
+ readonly apiClient: GroupMetadataAccessInput["apiClient"] & PrincipalPolicyReadApi;
11
11
  readonly crypto: {
12
12
  readonly encapsulationKeyPair: EncapsulationKeyPair | null;
13
13
  };
14
14
  readonly infra: {
15
15
  readonly execSql: ExecSql;
16
16
  };
17
+ readonly principalPolicies: PrincipalPolicyService;
17
18
  readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
18
19
  readonly util: {
19
20
  readonly log: (message: string) => void;
@@ -21,7 +22,7 @@ interface GroupMetadataRuntime {
21
22
  };
22
23
  }
23
24
  export declare function createRuntimeGroupMetadataAccess(runtime: GroupMetadataRuntime, organizationId: string, stillCurrent?: () => boolean, verifyMetadataContainer?: GroupMetadataAccessInput["verifyMetadataContainer"], currentRecovery?: {
24
- readonly resolveCurrentPolicy: ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>;
25
+ readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver | undefined;
25
26
  readonly recoveryBatch: object;
26
27
  }): {
27
28
  readName: import("../principalPolicy/principalPolicyRequest.js").GroupPolicyNameReader;
@@ -1,7 +1,5 @@
1
1
  import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
2
  import { createProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/userKeyResolver.js";
3
- import { createRuntimePrincipalPolicyCurrentResolver, } from "../../principals/runtimePolicyRecovery.js";
4
- import { createRuntimePrincipalPolicyWarmer } from "../../principals/runtimePolicyWarmer.js";
5
3
  import { createCurrentGroupMetadataContainerVerifier } from "./currentGroupMetadataAuthority.js";
6
4
  import { createGroupMetadataAccess, } from "./groupMetadataAccess.js";
7
5
  export function createRuntimeGroupMetadataAccess(runtime, organizationId, stillCurrent, verifyMetadataContainer, currentRecovery) {
@@ -10,11 +8,11 @@ export function createRuntimeGroupMetadataAccess(runtime, organizationId, stillC
10
8
  throw new Error("Group metadata identity is locked");
11
9
  // The signed metadata projection selects exact citations. Reuse matching
12
10
  // private evidence with its dependencies and pins before bounded online reads.
13
- const warmer = createRuntimePrincipalPolicyWarmer(runtime, {
11
+ const warmer = runtime.principalPolicies.createWarmer({
14
12
  preferLocalCurrent: true,
15
13
  });
16
14
  const resolveCurrentPolicy = currentRecovery?.resolveCurrentPolicy ??
17
- createRuntimePrincipalPolicyCurrentResolver(runtime);
15
+ runtime.principalPolicies.createCurrentPolicyResolver();
18
16
  const authorityInput = {
19
17
  apiClient: runtime.apiClient,
20
18
  execSql: runtime.infra.execSql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2CAA2C,CAAC;gBAC1C,GAAG,cAAc;gBACjB,oBAAoB,EAAE,sBAAsB,CAAC,oBAAoB,CAAC;gBAClE,aAAa,EAAE,eAAe,EAAE,aAAa;aAC9C,CAAC;QACJ,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,cAAc;QACd,wBAAwB,EAAE,+BAA+B,CAAC,OAAO,CAAC;QAClE,eAAe;QACf,YAAY;QACZ,+BAA+B,EAAE,MAAM;KACxC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,sBAAsB,CAC7B,OAAuE;IAEvE,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { EncapsulationKeyPair } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport {\n createRuntimePrincipalPolicyCurrentResolver,\n type PrincipalPolicyRecoveryRuntime,\n} from \"../../principals/runtimePolicyRecovery\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\nimport {\n createGroupMetadataAccess,\n type GroupMetadataAccessInput,\n} from \"./groupMetadataAccess\";\n\ninterface GroupMetadataRuntime {\n readonly state?: PrincipalPolicyRecoveryRuntime[\"state\"];\n readonly apiClient: GroupMetadataAccessInput[\"apiClient\"] &\n PrincipalPolicyReadApi &\n PrincipalPolicyRecoveryRuntime[\"apiClient\"];\n readonly crypto: {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n };\n readonly infra: { readonly execSql: ExecSql };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: {\n readonly log: (message: string) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n };\n}\n\nexport function createRuntimeGroupMetadataAccess(\n runtime: GroupMetadataRuntime,\n organizationId: string,\n stillCurrent?: () => boolean,\n verifyMetadataContainer?: GroupMetadataAccessInput[\"verifyMetadataContainer\"],\n currentRecovery?: {\n readonly resolveCurrentPolicy: ReturnType<\n typeof createRuntimePrincipalPolicyCurrentResolver\n >;\n readonly recoveryBatch: object;\n },\n) {\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!targetSecretKey) throw new Error(\"Group metadata identity is locked\");\n // The signed metadata projection selects exact citations. Reuse matching\n // private evidence with its dependencies and pins before bounded online reads.\n const warmer = createRuntimePrincipalPolicyWarmer(runtime, {\n preferLocalCurrent: true,\n });\n const resolveCurrentPolicy =\n currentRecovery?.resolveCurrentPolicy ??\n createRuntimePrincipalPolicyCurrentResolver(runtime);\n const authorityInput = {\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: stillCurrent ?? (() => true),\n };\n return createGroupMetadataAccess({\n verifyMetadataContainer:\n verifyMetadataContainer ??\n createCurrentGroupMetadataContainerVerifier({\n ...authorityInput,\n resolveCurrentPolicy: requireCurrentResolver(resolveCurrentPolicy),\n recoveryBatch: currentRecovery?.recoveryBatch,\n }),\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: warmer,\n });\n}\n\nfunction requireCurrentResolver(\n resolve: ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>,\n) {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n return resolve;\n}\n"]}
1
+ {"version":3,"file":"groupMetadataRuntime.js","sourceRoot":"","sources":["groupMetadataRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAO7G,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EACL,yBAAyB,GAE1B,MAAM,uBAAuB,CAAC;AAiB/B,MAAM,UAAU,gCAAgC,CAC9C,OAA6B,EAC7B,cAAsB,EACtB,YAA4B,EAC5B,uBAA6E,EAC7E,eAGC;IAED,MAAM,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,SAAS,CAAC;IACvE,IAAI,CAAC,eAAe;QAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IAC3E,yEAAyE;IACzE,+EAA+E;IAC/E,MAAM,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,YAAY,CAAC;QACpD,kBAAkB,EAAE,IAAI;KACzB,CAAC,CAAC;IACH,MAAM,oBAAoB,GACxB,eAAe,EAAE,oBAAoB;QACrC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IAC1D,MAAM,cAAc,GAAG;QACrB,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,cAAc;QACd,sBAAsB,EAAE,OAAO,CAAC,IAAI,CAAC,sBAAsB;QAC3D,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;QAC9D,YAAY,EAAE,YAAY,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC;KAC3C,CAAC;IACF,OAAO,yBAAyB,CAAC;QAC/B,uBAAuB,EACrB,uBAAuB;YACvB,2CAA2C,CAAC;gBAC1C,GAAG,cAAc;gBACjB,oBAAoB,EAAE,sBAAsB,CAAC,oBAAoB,CAAC;gBAClE,aAAa,EAAE,eAAe,EAAE,aAAa;aAC9C,CAAC;QACJ,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,cAAc;QACd,wBAAwB,EAAE,+BAA+B,CAAC,OAAO,CAAC;QAClE,eAAe;QACf,YAAY;QACZ,+BAA+B,EAAE,MAAM;KACxC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,sBAAsB,CAC7B,OAAmD;IAEnD,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { EncapsulationKeyPair } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { PrincipalPolicyService } from \"../../principals/principalPolicyService\";\nimport type { PrincipalPolicyCurrentResolver } from \"../../principals/runtimePolicyRecovery\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\nimport {\n createGroupMetadataAccess,\n type GroupMetadataAccessInput,\n} from \"./groupMetadataAccess\";\n\ninterface GroupMetadataRuntime {\n readonly apiClient: GroupMetadataAccessInput[\"apiClient\"] &\n PrincipalPolicyReadApi;\n readonly crypto: {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n };\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: {\n readonly log: (message: string) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n };\n}\n\nexport function createRuntimeGroupMetadataAccess(\n runtime: GroupMetadataRuntime,\n organizationId: string,\n stillCurrent?: () => boolean,\n verifyMetadataContainer?: GroupMetadataAccessInput[\"verifyMetadataContainer\"],\n currentRecovery?: {\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver | undefined;\n readonly recoveryBatch: object;\n },\n) {\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!targetSecretKey) throw new Error(\"Group metadata identity is locked\");\n // The signed metadata projection selects exact citations. Reuse matching\n // private evidence with its dependencies and pins before bounded online reads.\n const warmer = runtime.principalPolicies.createWarmer({\n preferLocalCurrent: true,\n });\n const resolveCurrentPolicy =\n currentRecovery?.resolveCurrentPolicy ??\n runtime.principalPolicies.createCurrentPolicyResolver();\n const authorityInput = {\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: stillCurrent ?? (() => true),\n };\n return createGroupMetadataAccess({\n verifyMetadataContainer:\n verifyMetadataContainer ??\n createCurrentGroupMetadataContainerVerifier({\n ...authorityInput,\n resolveCurrentPolicy: requireCurrentResolver(resolveCurrentPolicy),\n recoveryBatch: currentRecovery?.recoveryBatch,\n }),\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: warmer,\n });\n}\n\nfunction requireCurrentResolver(\n resolve: PrincipalPolicyCurrentResolver | undefined,\n) {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n return resolve;\n}\n"]}
@@ -1,9 +1,8 @@
1
1
  import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
- import { createRuntimePrincipalPolicyCurrentResolver, } from "../../principals/runtimePolicyRecovery.js";
3
2
  import { createCurrentGroupMetadataContainerVerifier } from "./currentGroupMetadataAuthority.js";
4
3
  /** Remote metadata destinations require the same private authority as name reads. */
5
4
  export async function verifyRuntimeGroupMetadataAuthority(input) {
6
- const resolveCurrentPolicy = createRuntimePrincipalPolicyCurrentResolver(input.runtime);
5
+ const resolveCurrentPolicy = input.runtime.principalPolicies.createCurrentPolicyResolver();
7
6
  if (!resolveCurrentPolicy)
8
7
  throw new ProjectionDependencyUnavailableError("Group metadata requires private paged recovery");
9
8
  await createCurrentGroupMetadataContainerVerifier({
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeGroupMetadataAuthority.js","sourceRoot":"","sources":["runtimeGroupMetadataAuthority.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EACL,2CAA2C,GAE5C,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAE9F,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAMzD;IACC,MAAM,oBAAoB,GAAG,2CAA2C,CACtE,KAAK,CAAC,OAAO,CACd,CAAC;IACF,IAAI,CAAC,oBAAoB;QACvB,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,MAAM,2CAA2C,CAAC;QAChD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB;QACpB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport {\n createRuntimePrincipalPolicyCurrentResolver,\n type PrincipalPolicyRecoveryRuntime,\n} from \"../../principals/runtimePolicyRecovery\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\n\n/** Remote metadata destinations require the same private authority as name reads. */\nexport async function verifyRuntimeGroupMetadataAuthority(input: {\n readonly runtime: PrincipalPolicyRecoveryRuntime;\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n readonly organizationReference?: ReferencedPrincipalHead | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const resolveCurrentPolicy = createRuntimePrincipalPolicyCurrentResolver(\n input.runtime,\n );\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n await createCurrentGroupMetadataContainerVerifier({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n })(input.state, input.organizationReference);\n}\n"]}
1
+ {"version":3,"file":"runtimeGroupMetadataAuthority.js","sourceRoot":"","sources":["runtimeGroupMetadataAuthority.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AAExH,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAE9F,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAMzD;IACC,MAAM,oBAAoB,GACxB,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IAChE,IAAI,CAAC,oBAAoB;QACvB,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,MAAM,2CAA2C,CAAC;QAChD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB;QACpB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\n\n/** Remote metadata destinations require the same private authority as name reads. */\nexport async function verifyRuntimeGroupMetadataAuthority(input: {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n readonly organizationReference?: ReferencedPrincipalHead | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const resolveCurrentPolicy =\n input.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n await createCurrentGroupMetadataContainerVerifier({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n })(input.state, input.organizationReference);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"currentGroupPolicyMutationContext.js","sourceRoot":"","sources":["currentGroupPolicyMutationContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,GAE7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA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E,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;oBAC9C,IAAI,MAAM,KAAK,SAAS;wBAAE,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;gBACtD,CAAC;gBACD,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;gBACpD,UAAU,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YAC/B,CAAC;YACD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACtD,IAAI,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,OAAO;oBAAE,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5D,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;YAC3D,OAAO,QAAQ,CAAC,MAAM,CAAC;QACzB,CAAC;QACD,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["import {\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { requireOrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { createRuntimePrincipalPolicyCurrentResolver } from \"../../principals/runtimePolicyRecovery\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../groupMetadata/currentGroupMetadataAuthority\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport { loadCurrentOrganizationMutationAuthority } from \"../principalMutations/currentOrganizationMutationAuthority\";\nimport { requireSignerCanManageGroup } from \"./groupMutationAuthorization\";\n\n/** Exact current directory, strict Admins and group evidence for one mutation. */\nexport async function loadCurrentGroupPolicyMutationContext(input: {\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly resolveCurrentPolicy: NonNullable<\n ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>\n >;\n readonly recoverPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<void>;\n readonly stillCurrent: () => boolean;\n}) {\n input = { ...input };\n const { authority, currentOrgAdminUserIds } =\n await loadCurrentOrganizationMutationAuthority(input);\n const group = await authority.readGroup(input.groupId);\n const stillCurrent = () =>\n input.stillCurrent() && authority.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n assertGroupMetadataBinding(group.current, authority.descriptor);\n requireSignerCanManageGroup(\n group.current,\n currentOrgAdminUserIds,\n input.signerUserId,\n );\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: input.organizationId,\n policies: [...group.dependencies, group.policy],\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const adminHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.adminGroupId,\n );\n const externalAuthority: PrincipalPolicyExternalAuthority = {\n currentHead: adminHead,\n states: [\n { head: adminHead, projection: authority.admins.policy.projection },\n ],\n };\n // A reused citation keeps the lifetime of the read that produced it.\n const references = new Map<\n string,\n Promise<{\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly stillCurrent: () => boolean;\n }>\n >();\n return {\n adminGroupId: authority.descriptor.adminGroupId,\n adminCurrent: authority.admins,\n currentPolicy: group.current,\n verifiedCurrentPolicy: group.policy,\n verifyMetadataContainer:\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent,\n }),\n currentOrgAdminUserIds,\n externalAuthority,\n isOrganizationAdminsGroup:\n input.groupId === authority.descriptor.adminGroupId,\n localPolicyCheckpoint: group.policy.checkpoint,\n memberGroupId: authority.descriptor.memberGroupId,\n organizationDescriptor: authority.descriptor,\n organizationCurrent: authority.directory,\n async readPredecessorReference(reference: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const owned = structuredClone(reference);\n const key = serializeKeyingCanonicalJson({ ...owned });\n let pending = references.get(key);\n if (!pending) {\n // Keep at most one bounded selection's citations, even across many paths.\n if (references.size === 128) {\n const oldest = references.keys().next().value;\n if (oldest !== undefined) references.delete(oldest);\n }\n pending = authority.readGroup(input.groupId, owned);\n references.set(key, pending);\n }\n const selected = await pending.catch((error: unknown) => {\n if (references.get(key) === pending) references.delete(key);\n throw error;\n });\n assertProjectionVerificationCurrent(stillCurrent);\n assertProjectionVerificationCurrent(selected.stillCurrent);\n return selected.policy;\n },\n stillCurrent,\n };\n}\n"]}
1
+ {"version":3,"file":"currentGroupPolicyMutationContext.js","sourceRoot":"","sources":["currentGroupPolicyMutationContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,GAE7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AAGxG,OAAO,EAAE,mDAAmD,EAAE,MAAM,gDAAgD,CAAC;AACrH,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAE,wCAAwC,EAAE,MAAM,4DAA4D,CAAC;AACtH,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAE3E,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAU3D;IACC,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;IACrB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AAC,CAAC,KAAc,EAAE,EAAE;gBACtD,IAAI,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,OAAO;oBAAE,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5D,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;YAC3D,OAAO,QAAQ,CAAC,MAAM,CAAC;QACzB,CAAC;QACD,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["import {\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { requireOrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { PrincipalPolicyCurrentResolver } from \"../../principals/runtimePolicyRecovery\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../groupMetadata/currentGroupMetadataAuthority\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport { loadCurrentOrganizationMutationAuthority } from \"../principalMutations/currentOrganizationMutationAuthority\";\nimport { requireSignerCanManageGroup } from \"./groupMutationAuthorization\";\n\n/** Exact current directory, strict Admins and group evidence for one mutation. */\nexport async function loadCurrentGroupPolicyMutationContext(input: {\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver;\n readonly recoverPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<void>;\n readonly stillCurrent: () => boolean;\n}) {\n input = { ...input };\n const { authority, currentOrgAdminUserIds } =\n await loadCurrentOrganizationMutationAuthority(input);\n const group = await authority.readGroup(input.groupId);\n const stillCurrent = () =>\n input.stillCurrent() && authority.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n assertGroupMetadataBinding(group.current, authority.descriptor);\n requireSignerCanManageGroup(\n group.current,\n currentOrgAdminUserIds,\n input.signerUserId,\n );\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: input.organizationId,\n policies: [...group.dependencies, group.policy],\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const adminHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.adminGroupId,\n );\n const externalAuthority: PrincipalPolicyExternalAuthority = {\n currentHead: adminHead,\n states: [\n { head: adminHead, projection: authority.admins.policy.projection },\n ],\n };\n // A reused citation keeps the lifetime of the read that produced it.\n const references = new Map<\n string,\n Promise<{\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly stillCurrent: () => boolean;\n }>\n >();\n return {\n adminGroupId: authority.descriptor.adminGroupId,\n adminCurrent: authority.admins,\n currentPolicy: group.current,\n verifiedCurrentPolicy: group.policy,\n verifyMetadataContainer:\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent,\n }),\n currentOrgAdminUserIds,\n externalAuthority,\n isOrganizationAdminsGroup:\n input.groupId === authority.descriptor.adminGroupId,\n localPolicyCheckpoint: group.policy.checkpoint,\n memberGroupId: authority.descriptor.memberGroupId,\n organizationDescriptor: authority.descriptor,\n organizationCurrent: authority.directory,\n async readPredecessorReference(reference: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const owned = structuredClone(reference);\n const key = serializeKeyingCanonicalJson({ ...owned });\n let pending = references.get(key);\n if (!pending) {\n // Keep at most one bounded selection's citations, even across many paths.\n if (references.size === 128) {\n const oldest = references.keys().next().value;\n if (oldest !== undefined) references.delete(oldest);\n }\n pending = authority.readGroup(input.groupId, owned);\n references.set(key, pending);\n }\n const selected = await pending.catch((error: unknown) => {\n if (references.get(key) === pending) references.delete(key);\n throw error;\n });\n assertProjectionVerificationCurrent(stillCurrent);\n assertProjectionVerificationCurrent(selected.stillCurrent);\n return selected.policy;\n },\n stillCurrent,\n };\n}\n"]}
@@ -1,10 +1,9 @@
1
1
  import { type ReferencedPrincipalHead } from "../../../internal/crypto/index.js";
2
2
  import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
3
3
  import { createRuntimeGroupMetadataAccess } from "../groupMetadata/groupMetadataRuntime.js";
4
- import { createCurrentPrincipalMutationLease } from "../principalMutations/currentPrincipalMutationLease.js";
5
4
  import type { PrincipalMutationRecoveryApi } from "../principalMutations/principalMutationJournalManagement.js";
6
5
  import { type GroupPolicyNameReader } from "../principalPolicy/principalPolicyRequest.js";
7
- type CurrentShareRuntime = Parameters<typeof createRuntimeGroupMetadataAccess>[0] & Parameters<typeof createCurrentPrincipalMutationLease>[0] & {
6
+ type CurrentShareRuntime = Parameters<typeof createRuntimeGroupMetadataAccess>[0] & {
8
7
  readonly apiClient: {
9
8
  readonly recoverPendingPrincipalMutation?: PrincipalMutationRecoveryApi["recoverPendingPrincipalMutation"] | undefined;
10
9
  };
@@ -2,16 +2,16 @@ import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
3
3
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
4
  import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
5
+ import { createCurrentPrincipalMutationLease } from "../../principals/principalPolicyService.js";
5
6
  import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
6
7
  import { createSelectedCurrentGroupMetadataContainerVerifier } from "../groupMetadata/currentGroupMetadataAuthority.js";
7
8
  import { assertGroupMetadataBinding } from "../groupMetadata/groupMetadataBinding.js";
8
9
  import { createRuntimeGroupMetadataAccess } from "../groupMetadata/groupMetadataRuntime.js";
9
- import { createCurrentPrincipalMutationLease } from "../principalMutations/currentPrincipalMutationLease.js";
10
10
  import { groupPolicyNameMismatch, } from "../principalPolicy/principalPolicyRequest.js";
11
11
  import { GroupShareNameMismatchError } from "./sharePrincipalPolicy.js";
12
12
  /** A share read need not be a group administrator; minting a grant checks that separately. */
13
13
  export function createRuntimeCurrentSharePrincipalPolicy(runtime) {
14
- const lease = createCurrentPrincipalMutationLease(runtime);
14
+ const lease = createCurrentPrincipalMutationLease(runtime.principalPolicies);
15
15
  if (!lease)
16
16
  return undefined;
17
17
  return async (input, work) => {