@tearleads/client-sdk 0.1.223 → 0.1.225

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 (89) hide show
  1. package/client/organizations/organizationMemberships.d.ts +1 -1
  2. package/client/organizations/organizationMemberships.js +1 -1
  3. package/client/organizations/organizationMemberships.js.map +1 -1
  4. package/data/documents/shared/containerKek/containerKekPathVerification.js +2 -0
  5. package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -1
  6. package/data/documents/shared/projection/index.js +2 -0
  7. package/data/documents/shared/projection/index.js.map +1 -1
  8. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +3 -0
  9. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +2 -1
  10. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  11. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +2 -1
  12. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +1 -0
  13. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  14. package/data/keyingProjectionVerification/container/containerProjectionVerification.d.ts +3 -2
  15. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +2 -0
  16. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  17. package/data/keyingProjectionVerification/document/documentProjectionVerification.d.ts +2 -1
  18. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +2 -0
  19. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  20. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +3 -2
  21. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  22. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.d.ts +2 -1
  23. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js +7 -3
  24. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js.map +1 -1
  25. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +3 -2
  26. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  27. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +17 -6
  28. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  29. package/data/keyingProjectionVerification/types.d.ts +20 -2
  30. package/data/keyingProjectionVerification/types.js.map +1 -1
  31. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +2 -0
  32. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -1
  33. package/package.json +1 -1
  34. package/stores/container-contents/operations/forgetOrganizationContentOperation.js +1 -1
  35. package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +1 -1
  36. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js +1 -1
  37. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js.map +1 -1
  38. package/stores/documents/documentStore/initialization/index.js +1 -1
  39. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  40. package/stores/documents/documentStore/storedDocument.js +1 -1
  41. package/stores/documents/documentStore/storedDocument.js.map +1 -1
  42. package/stores/documents/documentStore/sync/syncAttachments.js +1 -1
  43. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  44. package/workflows/container-contents/container-state/create/createAdoption.js +2 -0
  45. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  46. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +2 -0
  47. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  48. package/workflows/container-contents/container-state/share/groupGrantVerification.js +2 -0
  49. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  50. package/workflows/container-contents/container-state/share/index.js +2 -0
  51. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  52. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +2 -0
  53. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  54. package/workflows/container-contents/syncPause/documentRemoval.js +1 -1
  55. package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
  56. package/workflows/containers/child/create/index.d.ts +1 -1
  57. package/workflows/containers/child/create/index.js +2 -0
  58. package/workflows/containers/child/create/index.js.map +1 -1
  59. package/workflows/containers/child/move/moveWraps.js +3 -0
  60. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  61. package/workflows/containers/child/rekey/carriedDescendantRekeys.js +2 -0
  62. package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -1
  63. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js +2 -0
  64. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -1
  65. package/workflows/containers/child/share/sharePlanCore.js +2 -0
  66. package/workflows/containers/child/share/sharePlanCore.js.map +1 -1
  67. package/workflows/containers/rematerialization/principalContainerRematerialization.js +2 -0
  68. package/workflows/containers/rematerialization/principalContainerRematerialization.js.map +1 -1
  69. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js +2 -0
  70. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
  71. package/workflows/documents/create/index.js +2 -0
  72. package/workflows/documents/create/index.js.map +1 -1
  73. package/workflows/documents/linkSet/linkSetAuthority.js +2 -0
  74. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
  75. package/workflows/documents/purge/index.js +6 -0
  76. package/workflows/documents/purge/index.js.map +1 -1
  77. package/workflows/documents/sync/syncSubmittedResult.js +2 -0
  78. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  79. package/workflows/documents/syncFailures/syncRepairAccess.js +2 -0
  80. package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -1
  81. package/workflows/organizations/memberships/organizationMemberships.d.ts +1 -1
  82. package/workflows/organizations/memberships/organizationMemberships.js +1 -1
  83. package/workflows/organizations/memberships/organizationMemberships.js.map +1 -1
  84. package/workflows/sync/coordination.d.ts +6 -0
  85. package/workflows/sync/coordination.js +6 -0
  86. package/workflows/sync/coordination.js.map +1 -0
  87. package/workflows/sync/index.d.ts +1 -6
  88. package/workflows/sync/index.js +1 -5
  89. package/workflows/sync/index.js.map +1 -1
@@ -1,5 +1,5 @@
1
1
  import { type OrganizationLeaveRequestResult, type OrganizationMembership, type OrganizationSyncPauseResult } from "../../workflows/organizations/index.js";
2
- import { type DomainScope } from "../../workflows/sync/index.js";
2
+ import { type DomainScope } from "../../workflows/sync/coordination.js";
3
3
  import { type ContainerContents } from "../containerContents/index.js";
4
4
  import type { InternalRuntime } from "../runtime/workflowRuntime.js";
5
5
  /** The user's own conduit to the organizations they belong to. */
@@ -1,6 +1,6 @@
1
1
  import { refreshOrganizationMemberships, setOrganizationLeaveRequested, setOrganizationSyncPaused, } from "../../workflows/organizations/index.js";
2
2
  import { loadCurrentMembersHead } from "../../workflows/organizations/memberships/leaveRequestMembersEvidence.js";
3
- import { getOrCreateOrganizationSyncPauses, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../workflows/sync/index.js";
3
+ import { getOrCreateOrganizationSyncPauses, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../workflows/sync/coordination.js";
4
4
  import { carriesLocalWrites, } from "../containerContents/index.js";
5
5
  // Long enough for a typical upload burst, short enough to answer a tap.
6
6
  const PAUSE_FLUSH_TIMEOUT_MS = 10_000;
@@ -1 +1 @@
1
- {"version":3,"file":"organizationMemberships.js","sourceRoot":"","sources":["organizationMemberships.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,8BAA8B,EAC9B,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,uEAAuE,CAAC;AAC/G,OAAO,EAEL,iCAAiC,EACjC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,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ACV,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC7B,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type OrganizationContentHost,\n type OrganizationLeaveRequestResult,\n type OrganizationMembership,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationLeaveRequested,\n setOrganizationSyncPaused,\n} from \"../../workflows/organizations\";\nimport { loadCurrentMembersHead } from \"../../workflows/organizations/memberships/leaveRequestMembersEvidence\";\nimport {\n type DomainScope,\n getOrCreateOrganizationSyncPauses,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../workflows/sync\";\nimport {\n type ContainerContents,\n carriesLocalWrites,\n} from \"../containerContents\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\n\n// Long enough for a typical upload burst, short enough to answer a tap.\nconst PAUSE_FLUSH_TIMEOUT_MS = 10_000;\n\n/** The user's own conduit to the organizations they belong to. */\nexport interface OrganizationMemberships {\n /**\n * Reads the user's memberships and applies their pause choices on this\n * device. Null when offline or the list could not be read.\n */\n refresh(): Promise<OrganizationMembership[] | null>;\n /** Pauses or resumes one organization for all of the user's devices. */\n setSyncPaused(\n organizationId: string,\n paused: boolean,\n ): Promise<OrganizationSyncPauseResult>;\n /**\n * Asks the organization's administrators to remove the user, or withdraws\n * that request. Signed with the user's identity key; an administrator still\n * has to approve it.\n */\n setLeaveRequested(\n organizationId: string,\n requested: boolean,\n ): Promise<OrganizationLeaveRequestResult>;\n /** The organizations paused on this device, read from local storage. */\n loadPausedOrganizationIds(): Promise<ReadonlySet<string>>;\n /** Notifies when the paused set for the current scope changes. */\n subscribeToSyncPauses(listener: () => void): () => void;\n /**\n * Hands each membership list a refresh reads for the current scope, so a\n * choice made on another device reaches every view of it.\n */\n subscribeToMemberships(\n listener: (memberships: readonly OrganizationMembership[]) => void,\n ): () => void;\n}\n\ntype MembershipsListener = (\n memberships: readonly OrganizationMembership[],\n) => void;\n\nconst membershipListenersByScope = new WeakMap<\n DomainScope,\n Set<MembershipsListener>\n>();\n\n/**\n * The scope's document reconciler. Containers it reconciled before a pause\n * stay marked as listed, so a resume has to forget that before reconciling.\n */\nexport interface OrganizationContentReconciler {\n resetDiscovered(): void;\n reconcileNow(options: { readonly freshListing: true }): Promise<void>;\n}\n\ninterface SettleRetry {\n retry: () => Promise<boolean>;\n running: boolean;\n unsubscribe: () => void;\n}\n\nconst settleRetriesByScope = new WeakMap<DomainScope, SettleRetry>();\n\n// One retry per scope: it runs whenever the scope's sync lanes go idle and\n// stops once it reports the work done.\nexport function retryWhenWritesSettle(\n domainScope: DomainScope,\n retry: () => Promise<boolean>,\n): void {\n const existing = settleRetriesByScope.get(domainScope);\n if (existing) {\n existing.retry = retry;\n return;\n }\n const entry: SettleRetry = { retry, running: false, unsubscribe: () => {} };\n settleRetriesByScope.set(domainScope, entry);\n const attempt = () => {\n if (entry.running || hasDomainSyncCoordinatorPendingWork(domainScope)) {\n return;\n }\n entry.running = true;\n void entry\n .retry()\n .then(\n (done) => {\n if (!done) return;\n entry.unsubscribe();\n settleRetriesByScope.delete(domainScope);\n },\n () => undefined,\n )\n .finally(() => {\n entry.running = false;\n });\n };\n entry.unsubscribe = subscribeToDomainSyncCoordinator(domainScope, attempt);\n // The lanes may already have gone idle before the subscription existed.\n attempt();\n}\n\n// Bound to the scope the operation started in: the tree is opened once, and\n// every action re-checks the scope so stale work never reaches another\n// identity's device state.\nfunction createOrganizationContentHost(\n runtime: InternalWorkflowRuntimeInput,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n isCurrent: () => boolean,\n): OrganizationContentHost {\n const { domainScope } = runtime.state;\n const tree = containerContents.openTree();\n return {\n async forgetOrganizationContent(organizationId) {\n // A scope that ended has nothing left to retry.\n if (!isCurrent()) return true;\n return tree.forgetOrganizationContent(organizationId);\n },\n async hasUnsyncedOrganizationWrites(organizationId) {\n if (!isCurrent()) return true;\n const pending = await containerContents\n .documentQueries()\n .listPendingWrites();\n return pending.some(\n (item) =>\n item.organizationId === organizationId && carriesLocalWrites(item),\n );\n },\n async flushWrites() {\n requestAllDomainSyncLanes(domainScope);\n await waitForDomainSyncCoordinatorToSettle(domainScope, {\n timeoutMs: PAUSE_FLUSH_TIMEOUT_MS,\n });\n },\n async refetchContent() {\n if (!isCurrent()) return;\n // Re-lists the whole tree and every container's documents. The resumed\n // organization's folders were listed before the pause, and a hydration\n // may already have restored them, so they must be forgotten explicitly.\n // A sweep that started listing while paused would miss them, so this\n // one queues behind it rather than joining it.\n const reconciler = openReconciler();\n reconciler.resetDiscovered();\n await reconciler.reconcileNow({ freshListing: true });\n },\n retryWhenWritesSettle: (retry) => retryWhenWritesSettle(domainScope, retry),\n };\n}\n\nfunction canReachServer(runtime: InternalWorkflowRuntimeInput): boolean {\n return (\n runtime.infra.dbStatus === \"ready\" &&\n runtime.auth.isAuthenticated &&\n runtime.state.online\n );\n}\n\nfunction setLeaveRequestedFor(\n runtimeService: InternalRuntime,\n organizationId: string,\n requested: boolean,\n): Promise<OrganizationLeaveRequestResult> {\n const runtime = runtimeService.workflowInput();\n const { userId } = runtime.auth;\n const { signingKeyPair } = runtime.crypto;\n if (!canReachServer(runtime) || !userId || !signingKeyPair) {\n return Promise.resolve({\n httpStatus: null,\n message: \"Connect to ask to leave an organization.\",\n status: \"failed\",\n });\n }\n const { domainScope } = runtime.state;\n return setOrganizationLeaveRequested({\n apiClient: runtime.apiClient,\n loadMembersHead: () =>\n loadCurrentMembersHead({\n organizationId,\n runtime,\n stillCurrent: () =>\n runtimeService.workflowInput().state.domainScope === domainScope,\n }),\n organizationId,\n requested,\n signer: { signingKeyPair, userId },\n });\n}\n\nexport function createOrganizationMemberships(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n): OrganizationMemberships {\n const membershipInput = (runtime: InternalWorkflowRuntimeInput) => {\n const { domainScope } = runtime.state;\n const isCurrent = () =>\n runtimeService.workflowInput().state.domainScope === domainScope;\n return {\n apiClient: runtime.apiClient,\n domainScope,\n execSql: runtime.infra.execSql,\n host: createOrganizationContentHost(\n runtime,\n containerContents,\n openReconciler,\n isCurrent,\n ),\n isCurrent,\n };\n };\n return {\n async refresh() {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) return null;\n const memberships = await refreshOrganizationMemberships(\n membershipInput(runtime),\n );\n const listeners = membershipListenersByScope.get(\n runtime.state.domainScope,\n );\n if (memberships && listeners) {\n for (const listener of [...listeners]) listener(memberships);\n }\n return memberships;\n },\n async setSyncPaused(organizationId, paused) {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) {\n return {\n httpStatus: null,\n message: \"Connect to change sync for an organization.\",\n status: \"failed\",\n };\n }\n return setOrganizationSyncPaused({\n ...membershipInput(runtime),\n organizationId,\n paused,\n });\n },\n setLeaveRequested: (organizationId, requested) =>\n setLeaveRequestedFor(runtimeService, organizationId, requested),\n async loadPausedOrganizationIds() {\n const runtime = runtimeService.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") return new Set<string>();\n const pauses = getOrCreateOrganizationSyncPauses(\n runtime.state.domainScope,\n );\n await pauses.load(runtime.infra.execSql);\n return pauses.pausedOrganizationIds();\n },\n subscribeToSyncPauses(listener) {\n return getOrCreateOrganizationSyncPauses(\n runtimeService.workflowInput().state.domainScope,\n ).subscribe(listener);\n },\n subscribeToMemberships(listener) {\n const { domainScope } = runtimeService.workflowInput().state;\n const listeners =\n membershipListenersByScope.get(domainScope) ?? new Set();\n membershipListenersByScope.set(domainScope, listeners);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n"]}
1
+ {"version":3,"file":"organizationMemberships.js","sourceRoot":"","sources":["organizationMemberships.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,8BAA8B,EAC9B,6BAA6B,E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C,IAAI,IAAI,GAAG,EAAE,CAAC;YAC3D,0BAA0B,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;YACvD,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,OAAO,GAAG,EAAE;gBACV,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC7B,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type OrganizationContentHost,\n type OrganizationLeaveRequestResult,\n type OrganizationMembership,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationLeaveRequested,\n setOrganizationSyncPaused,\n} from \"../../workflows/organizations\";\nimport { loadCurrentMembersHead } from \"../../workflows/organizations/memberships/leaveRequestMembersEvidence\";\nimport {\n type DomainScope,\n getOrCreateOrganizationSyncPauses,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../workflows/sync/coordination\";\nimport {\n type ContainerContents,\n carriesLocalWrites,\n} from \"../containerContents\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\n\n// Long enough for a typical upload burst, short enough to answer a tap.\nconst PAUSE_FLUSH_TIMEOUT_MS = 10_000;\n\n/** The user's own conduit to the organizations they belong to. */\nexport interface OrganizationMemberships {\n /**\n * Reads the user's memberships and applies their pause choices on this\n * device. Null when offline or the list could not be read.\n */\n refresh(): Promise<OrganizationMembership[] | null>;\n /** Pauses or resumes one organization for all of the user's devices. */\n setSyncPaused(\n organizationId: string,\n paused: boolean,\n ): Promise<OrganizationSyncPauseResult>;\n /**\n * Asks the organization's administrators to remove the user, or withdraws\n * that request. Signed with the user's identity key; an administrator still\n * has to approve it.\n */\n setLeaveRequested(\n organizationId: string,\n requested: boolean,\n ): Promise<OrganizationLeaveRequestResult>;\n /** The organizations paused on this device, read from local storage. */\n loadPausedOrganizationIds(): Promise<ReadonlySet<string>>;\n /** Notifies when the paused set for the current scope changes. */\n subscribeToSyncPauses(listener: () => void): () => void;\n /**\n * Hands each membership list a refresh reads for the current scope, so a\n * choice made on another device reaches every view of it.\n */\n subscribeToMemberships(\n listener: (memberships: readonly OrganizationMembership[]) => void,\n ): () => void;\n}\n\ntype MembershipsListener = (\n memberships: readonly OrganizationMembership[],\n) => void;\n\nconst membershipListenersByScope = new WeakMap<\n DomainScope,\n Set<MembershipsListener>\n>();\n\n/**\n * The scope's document reconciler. Containers it reconciled before a pause\n * stay marked as listed, so a resume has to forget that before reconciling.\n */\nexport interface OrganizationContentReconciler {\n resetDiscovered(): void;\n reconcileNow(options: { readonly freshListing: true }): Promise<void>;\n}\n\ninterface SettleRetry {\n retry: () => Promise<boolean>;\n running: boolean;\n unsubscribe: () => void;\n}\n\nconst settleRetriesByScope = new WeakMap<DomainScope, SettleRetry>();\n\n// One retry per scope: it runs whenever the scope's sync lanes go idle and\n// stops once it reports the work done.\nexport function retryWhenWritesSettle(\n domainScope: DomainScope,\n retry: () => Promise<boolean>,\n): void {\n const existing = settleRetriesByScope.get(domainScope);\n if (existing) {\n existing.retry = retry;\n return;\n }\n const entry: SettleRetry = { retry, running: false, unsubscribe: () => {} };\n settleRetriesByScope.set(domainScope, entry);\n const attempt = () => {\n if (entry.running || hasDomainSyncCoordinatorPendingWork(domainScope)) {\n return;\n }\n entry.running = true;\n void entry\n .retry()\n .then(\n (done) => {\n if (!done) return;\n entry.unsubscribe();\n settleRetriesByScope.delete(domainScope);\n },\n () => undefined,\n )\n .finally(() => {\n entry.running = false;\n });\n };\n entry.unsubscribe = subscribeToDomainSyncCoordinator(domainScope, attempt);\n // The lanes may already have gone idle before the subscription existed.\n attempt();\n}\n\n// Bound to the scope the operation started in: the tree is opened once, and\n// every action re-checks the scope so stale work never reaches another\n// identity's device state.\nfunction createOrganizationContentHost(\n runtime: InternalWorkflowRuntimeInput,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n isCurrent: () => boolean,\n): OrganizationContentHost {\n const { domainScope } = runtime.state;\n const tree = containerContents.openTree();\n return {\n async forgetOrganizationContent(organizationId) {\n // A scope that ended has nothing left to retry.\n if (!isCurrent()) return true;\n return tree.forgetOrganizationContent(organizationId);\n },\n async hasUnsyncedOrganizationWrites(organizationId) {\n if (!isCurrent()) return true;\n const pending = await containerContents\n .documentQueries()\n .listPendingWrites();\n return pending.some(\n (item) =>\n item.organizationId === organizationId && carriesLocalWrites(item),\n );\n },\n async flushWrites() {\n requestAllDomainSyncLanes(domainScope);\n await waitForDomainSyncCoordinatorToSettle(domainScope, {\n timeoutMs: PAUSE_FLUSH_TIMEOUT_MS,\n });\n },\n async refetchContent() {\n if (!isCurrent()) return;\n // Re-lists the whole tree and every container's documents. The resumed\n // organization's folders were listed before the pause, and a hydration\n // may already have restored them, so they must be forgotten explicitly.\n // A sweep that started listing while paused would miss them, so this\n // one queues behind it rather than joining it.\n const reconciler = openReconciler();\n reconciler.resetDiscovered();\n await reconciler.reconcileNow({ freshListing: true });\n },\n retryWhenWritesSettle: (retry) => retryWhenWritesSettle(domainScope, retry),\n };\n}\n\nfunction canReachServer(runtime: InternalWorkflowRuntimeInput): boolean {\n return (\n runtime.infra.dbStatus === \"ready\" &&\n runtime.auth.isAuthenticated &&\n runtime.state.online\n );\n}\n\nfunction setLeaveRequestedFor(\n runtimeService: InternalRuntime,\n organizationId: string,\n requested: boolean,\n): Promise<OrganizationLeaveRequestResult> {\n const runtime = runtimeService.workflowInput();\n const { userId } = runtime.auth;\n const { signingKeyPair } = runtime.crypto;\n if (!canReachServer(runtime) || !userId || !signingKeyPair) {\n return Promise.resolve({\n httpStatus: null,\n message: \"Connect to ask to leave an organization.\",\n status: \"failed\",\n });\n }\n const { domainScope } = runtime.state;\n return setOrganizationLeaveRequested({\n apiClient: runtime.apiClient,\n loadMembersHead: () =>\n loadCurrentMembersHead({\n organizationId,\n runtime,\n stillCurrent: () =>\n runtimeService.workflowInput().state.domainScope === domainScope,\n }),\n organizationId,\n requested,\n signer: { signingKeyPair, userId },\n });\n}\n\nexport function createOrganizationMemberships(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n): OrganizationMemberships {\n const membershipInput = (runtime: InternalWorkflowRuntimeInput) => {\n const { domainScope } = runtime.state;\n const isCurrent = () =>\n runtimeService.workflowInput().state.domainScope === domainScope;\n return {\n apiClient: runtime.apiClient,\n domainScope,\n execSql: runtime.infra.execSql,\n host: createOrganizationContentHost(\n runtime,\n containerContents,\n openReconciler,\n isCurrent,\n ),\n isCurrent,\n };\n };\n return {\n async refresh() {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) return null;\n const memberships = await refreshOrganizationMemberships(\n membershipInput(runtime),\n );\n const listeners = membershipListenersByScope.get(\n runtime.state.domainScope,\n );\n if (memberships && listeners) {\n for (const listener of [...listeners]) listener(memberships);\n }\n return memberships;\n },\n async setSyncPaused(organizationId, paused) {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) {\n return {\n httpStatus: null,\n message: \"Connect to change sync for an organization.\",\n status: \"failed\",\n };\n }\n return setOrganizationSyncPaused({\n ...membershipInput(runtime),\n organizationId,\n paused,\n });\n },\n setLeaveRequested: (organizationId, requested) =>\n setLeaveRequestedFor(runtimeService, organizationId, requested),\n async loadPausedOrganizationIds() {\n const runtime = runtimeService.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") return new Set<string>();\n const pauses = getOrCreateOrganizationSyncPauses(\n runtime.state.domainScope,\n );\n await pauses.load(runtime.infra.execSql);\n return pauses.pausedOrganizationIds();\n },\n subscribeToSyncPauses(listener) {\n return getOrCreateOrganizationSyncPauses(\n runtimeService.workflowInput().state.domainScope,\n ).subscribe(listener);\n },\n subscribeToMemberships(listener) {\n const { domainScope } = runtimeService.workflowInput().state;\n const listeners =\n membershipListenersByScope.get(domainScope) ?? new Set();\n membershipListenersByScope.set(domainScope, listeners);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { collectContainerWriterProjectionPrincipalPolicies, } from "../../../keyingProjectionVerification/index.js";
2
+ import { openPrincipalPolicyBundleReader } from "../../../persistence/principalPolicy/principalPolicyBundleRepository.js";
2
3
  import { resolveProjectionVerifier } from "../projection/projectionVerificationOptions.js";
3
4
  export async function verifyContainerKekPathProjection(input) {
4
5
  if (input.projection.path.length !== input.projection.containerKeks.length) {
@@ -11,6 +12,7 @@ export async function verifyContainerKekPathProjection(input) {
11
12
  }
12
13
  await collectContainerWriterProjectionPrincipalPolicies({
13
14
  execSql: input.execSql,
15
+ openPrincipalPolicyBundleReader,
14
16
  persistVerificationCheckpoints: input.persistVerificationCheckpoints,
15
17
  principalPolicyCache: input.principalPolicyCache,
16
18
  projection: input.projection,
@@ -1 +1 @@
1
- {"version":3,"file":"containerKekPathVerification.js","sourceRoot":"","sources":["containerKekPathVerification.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,iDAAiD,GAElD,MAAM,uCAAuC,CAAC;AAG/C,OAAO,EAAE,yBAAyB,EAAE,MAAM,6CAA6C,CAAC;AAYxF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAkC;IAElC,IAAI,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,UAAU,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC;QAC3E,MAAM,IAAI,KAAK,CACb,4DAA4D,CAC7D,CAAC;IACJ,CAAC;IACD,MAAM,wBAAwB,GAAG,yBAAyB,CACxD,KAAK,EACL,sBAAsB,CACvB,CAAC;IACF,IACE,KAAK,CAAC,sBAAsB,KAAK,IAAI;QACrC,wBAAwB,KAAK,IAAI,EACjC,CAAC;QACD,OAAO;IACT,CAAC;IAED,MAAM,iDAAiD,CAAC;QACtD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,8BAA8B,EAAE,KAAK,CAAC,8BAA8B;QACpE,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,cAAc,EAAE,wBAAwB;QACxC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n} from \"../../../keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { ProjectionVerificationOptions } from \"../projection/projectionVerificationOptions\";\nimport { resolveProjectionVerifier } from \"../projection/projectionVerificationOptions\";\n\nexport type UnwrapContainerKekPathInput = {\n execSql?: ExecSql | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n projection: ContainerWriterProjectionResponse;\n secretKey: Uint8Array;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n} & ProjectionVerificationOptions;\n\nexport async function verifyContainerKekPathProjection(\n input: UnwrapContainerKekPathInput,\n): Promise<void> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n const resolveProjectionUserKey = resolveProjectionVerifier(\n input,\n \"Container KEK unwrap\",\n );\n if (\n input.trustedLocalProjection === true ||\n resolveProjectionUserKey === null\n ) {\n return;\n }\n\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.projection,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
1
+ {"version":3,"file":"containerKekPathVerification.js","sourceRoot":"","sources":["containerKekPathVerification.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,iDAAiD,GAElD,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,+BAA+B,EAAE,MAAM,sEAAsE,CAAC;AAGvH,OAAO,EAAE,yBAAyB,EAAE,MAAM,6CAA6C,CAAC;AAYxF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAkC;IAElC,IAAI,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,UAAU,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC;QAC3E,MAAM,IAAI,KAAK,CACb,4DAA4D,CAC7D,CAAC;IACJ,CAAC;IACD,MAAM,wBAAwB,GAAG,yBAAyB,CACxD,KAAK,EACL,sBAAsB,CACvB,CAAC;IACF,IACE,KAAK,CAAC,sBAAsB,KAAK,IAAI;QACrC,wBAAwB,KAAK,IAAI,EACjC,CAAC;QACD,OAAO;IACT,CAAC;IAED,MAAM,iDAAiD,CAAC;QACtD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,+BAA+B;QAC/B,8BAA8B,EAAE,KAAK,CAAC,8BAA8B;QACpE,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,cAAc,EAAE,wBAAwB;QACxC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n} from \"../../../keyingProjectionVerification\";\nimport { openPrincipalPolicyBundleReader } from \"../../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { ProjectionVerificationOptions } from \"../projection/projectionVerificationOptions\";\nimport { resolveProjectionVerifier } from \"../projection/projectionVerificationOptions\";\n\nexport type UnwrapContainerKekPathInput = {\n execSql?: ExecSql | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n projection: ContainerWriterProjectionResponse;\n secretKey: Uint8Array;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n} & ProjectionVerificationOptions;\n\nexport async function verifyContainerKekPathProjection(\n input: UnwrapContainerKekPathInput,\n): Promise<void> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n const resolveProjectionUserKey = resolveProjectionVerifier(\n input,\n \"Container KEK unwrap\",\n );\n if (\n input.trustedLocalProjection === true ||\n resolveProjectionUserKey === null\n ) {\n return;\n }\n\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.projection,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { computeDocumentContentKeyTargetHash } from "../../../../internal/crypto/index.js";
2
2
  import { verifyDocumentWriterProjectionAuthorization, } from "../../../keyingProjectionVerification/index.js";
3
3
  import { throwKeyingVerificationShapeFailure } from "../../../keyingProjectionVerification/error.js";
4
+ import { openPrincipalPolicyBundleReader } from "../../../persistence/principalPolicy/principalPolicyBundleRepository.js";
4
5
  import { errorMessage } from "../../../shared/errorMessage.js";
5
6
  import { assertDocumentManifestBundleConsistent, normalizeDocumentKekTargetResponse, sortDocumentTargets, targetEnvelopeReference, targetKey, uniqueSortedStrings, } from "../readers.js";
6
7
  import { currentDocumentTargets, deriveDocumentTargetFromProjection, readLinkedContainerIdsFromDocumentManifest, } from "./projectionTargets.js";
@@ -77,6 +78,7 @@ async function assertDocumentWriterProjectionConsistentInternal(writerProjection
77
78
  resolveProjectionUserKey !== null) {
78
79
  const authorization = await verifyDocumentWriterProjectionAuthorization({
79
80
  execSql: input.execSql,
81
+ openPrincipalPolicyBundleReader,
80
82
  persistVerificationCheckpoints: input.persistVerificationCheckpoints,
81
83
  principalPolicyCache: input.principalPolicyCache,
82
84
  projection: writerProjection,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EAGL,2CAA2C,GAC5C,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,mCAAmC,EAAE,MAAM,6CAA6C,CAAC;AAClG,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE5D,OAAO,EACL,sCAAsC,EACtC,kCAAkC,EAClC,mBAAmB,EACnB,uBAAuB,EACvB,SAAS,EACT,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,sBAAsB,EACtB,kCAAkC,EAClC,0CAA0C,GAC3C,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAAE,mCAAmC,EAAE,MAAM,yCAAyC,CAAC;AAC9F,OAAO,EAAE,8BAA8B,EAAE,MAAM,wBAAwB,CAAC;AACxE,OAAO,EACL,oCAAoC,EACpC,mCAAmC,EACnC,kCAAkC,EAClC,+BAA+B,EAC/B,6BA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,CAAC,gBAAgB,CAAC,kBAAkB,CAAC;QACzE,CAAC,CAAC,sBAAsB,CAAC,gBAAgB,CAAC,CAAC;IAC7C,MAAM,mBAAmB,GACvB,MAAM,mCAAmC,CAAC,OAAO,CAAC,CAAC;IACrD,IACE,mBAAmB;QACnB,gBAAgB,CAAC,kBAAkB,CAAC,qBAAqB,EACzD,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IAC7E,CAAC;IAED,0CAA0C,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAC;IACtE,mDAAmD,CAAC;QAClD,OAAO;QACP,gBAAgB;KACjB,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,GAAG,KAA0E;IAE7E,IAAI,CAAC;QACH,OAAO,MAAM,gDAAgD,CAAC,GAAG,KAAK,CAAC,CAAC;IAC1E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { computeDocumentContentKeyTargetHash } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n type DocumentWriterProjectionAuthorization,\n type PrincipalPolicyCache,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../keyingProjectionVerification\";\nimport { throwKeyingVerificationShapeFailure } from \"../../../keyingProjectionVerification/error\";\nimport { errorMessage } from \"../../../shared/errorMessage\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n assertDocumentManifestBundleConsistent,\n normalizeDocumentKekTargetResponse,\n sortDocumentTargets,\n targetEnvelopeReference,\n targetKey,\n uniqueSortedStrings,\n} from \"../readers\";\nimport {\n currentDocumentTargets,\n deriveDocumentTargetFromProjection,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"./projectionTargets\";\n\nexport { unwrapContainerKekPath } from \"../containerKek/containerKekPath\";\nexport { ContainerKekHistoryUnavailableError } from \"../containerKek/containerKekPathHistory\";\nexport { shouldRetryWithFreshProjection } from \"./freshProjectionRetry\";\nexport {\n buildRotatedDocumentContentKeyBundle,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapContentKeyTargetForKind,\n unwrapDocumentContentKeyFromBundle,\n unwrapDocumentContentKeyFromWriterProjection,\n unwrapDocumentContentKeyTarget,\n wrapDocumentContentKeyForCreate,\n} from \"./projectionContentKeys\";\nexport {\n authorizingContainerPathRefs,\n authorizingContainerPathRefsForLinkSet,\n containerPathRefs,\n currentDocumentTargets,\n deriveDocumentCreateTargets,\n deriveDocumentTargetFromProjection,\n mergeTargetEnvelopes,\n readLinkedContainerIdsFromDocumentManifest,\n verifiedDocumentWrapTargets,\n} from \"./projectionTargets\";\n\nimport type { ProjectionVerificationOptions } from \"./projectionVerificationOptions\";\nimport { resolveProjectionVerifier } from \"./projectionVerificationOptions\";\n\nfunction assertSortedStringsEqual(\n left: readonly string[],\n right: readonly string[],\n message: string,\n): void {\n if (\n left.length !== right.length ||\n left.some((value, index) => value !== right[index])\n ) {\n throw new Error(message);\n }\n}\n\nfunction assertAuthorizingContainerPathsMatchDocumentTargets(input: {\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}): void {\n if (input.writerProjection.authorizingContainerPaths.length === 0) {\n throw new Error(\"Document writer projection authorization paths missing\");\n }\n\n const targetKeys = new Set(input.targets.map(targetKey));\n for (const [\n index,\n projection,\n ] of input.writerProjection.authorizingContainerPaths.entries()) {\n let projectionTarget: DocumentContentKeyTarget;\n try {\n projectionTarget = deriveDocumentTargetFromProjection(projection);\n } catch (error) {\n throw new Error(\n `Document writer projection authorization path[${index}] is invalid: ${errorMessage(error)}`,\n );\n }\n\n if (targetKeys.has(targetKey(projectionTarget))) {\n continue;\n }\n\n // Bind server-supplied KEK paths to committed document targets before\n // using any unwrapped path KEK for document content-key material.\n throw new Error(\n `Document writer projection authorization path[${index}] is not a document target`,\n );\n }\n}\n\nfunction assertDocumentTargetsCoverLinkedContainers(\n targets: readonly DocumentContentKeyTarget[],\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n // One target per linked container: a second epoch for the same container\n // would let a re-wrap land on a KEK a revoked member still holds.\n if (\n new Set(targets.map((target) => target.containerId)).size !== targets.length\n ) {\n throw new Error(\n \"Document writer projection targets name a linked container more than once\",\n );\n }\n assertSortedStringsEqual(\n uniqueSortedStrings(targets.map((target) => target.containerId)),\n readLinkedContainerIdsFromDocumentManifest(writerProjection),\n \"Document writer projection targets do not match linked containers\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerManifestHashes,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerManifestHash)),\n \"Document writer projection target manifest summary mismatch\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerKeyEpochIds,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerKeyEpochId)),\n \"Document writer projection target KEK summary mismatch\",\n );\n}\n\nasync function assertProjectionContentKeyBundleConsistent(\n writerProjection: DocumentWriterProjectionResponse,\n staleContentKeyBundle: boolean,\n): Promise<void> {\n const { manifestHash } = writerProjection.documentManifest;\n // A stale bundle may lag the link-set head, but it must still descend from\n // this document's manifest chain.\n if (\n writerProjection.contentKeyBundle.linkSetManifestHash !== manifestHash &&\n (!staleContentKeyBundle ||\n !writerProjection.documentManifestHistory.some(\n (bundle) =>\n bundle.manifestHash ===\n writerProjection.contentKeyBundle.linkSetManifestHash,\n ))\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n\n if (!staleContentKeyBundle) {\n if (\n writerProjection.documentKekTargets.documentKeyTargetHash !==\n writerProjection.contentKeyBundle.targetHash\n ) {\n throw new Error(\"Document writer projection target hash mismatch\");\n }\n return;\n }\n\n // The stale bundle cannot match the current targets; pin it to its own\n // canonical hash instead so a tampered envelope set still fails closed.\n const staleBundleTargetHash = await computeDocumentContentKeyTargetHash(\n sortDocumentTargets(\n writerProjection.contentKeyBundle.targets.map(targetEnvelopeReference),\n ),\n );\n if (staleBundleTargetHash !== writerProjection.contentKeyBundle.targetHash) {\n throw new Error(\n \"Document writer projection stale bundle target hash is not canonical\",\n );\n }\n}\n\nasync function assertDocumentWriterProjectionConsistentInternal(\n writerProjection: DocumentWriterProjectionResponse,\n input: ProjectionVerificationOptions & {\n /**\n * Accept a projection whose content-key bundle is marked stale (wrapped\n * to superseded KEK targets after e.g. a revoke rotation). Document sync\n * opts in to heal the bundle. Attachment reads opt in because their DEK\n * is independent and opens through verified retained container KEKs.\n */\n allowStaleContentKeyBundle?: boolean | undefined;\n execSql?: ExecSql | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n onVerifiedAuthorization?:\n | ((authorization: DocumentWriterProjectionAuthorization) => void)\n | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n stillCurrent?: (() => boolean) | undefined;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n },\n): Promise<DocumentContentKeyTarget[]> {\n const resolveProjectionUserKey = resolveProjectionVerifier(\n input,\n \"Document writer projection\",\n );\n if (\n input.trustedLocalProjection !== true &&\n resolveProjectionUserKey !== null\n ) {\n const authorization = await verifyDocumentWriterProjectionAuthorization({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: writerProjection,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n input.onVerifiedAuthorization?.(authorization);\n }\n\n const staleContentKeyBundle = writerProjection.contentKeyBundleStale === true;\n if (staleContentKeyBundle && input.allowStaleContentKeyBundle !== true) {\n throw new Error(\"Document writer projection content-key bundle is stale\");\n }\n\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: writerProjection.documentManifest,\n label: \"Document writer projection manifest\",\n });\n const { documentId } = manifestIdentity;\n if (\n writerProjection.documentId !== documentId ||\n writerProjection.documentKekTargets.documentId !== documentId ||\n writerProjection.contentKeyBundle.documentId !== documentId\n ) {\n throw new Error(\"Document writer projection document id mismatch\");\n }\n if (\n writerProjection.documentKekTargets.linkSetManifestHash !==\n writerProjection.documentManifest.manifestHash\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n await assertProjectionContentKeyBundleConsistent(\n writerProjection,\n staleContentKeyBundle,\n );\n\n const targets = staleContentKeyBundle\n ? normalizeDocumentKekTargetResponse(writerProjection.documentKekTargets)\n : currentDocumentTargets(writerProjection);\n const canonicalTargetHash =\n await computeDocumentContentKeyTargetHash(targets);\n if (\n canonicalTargetHash !==\n writerProjection.documentKekTargets.documentKeyTargetHash\n ) {\n throw new Error(\"Document writer projection target hash is not canonical\");\n }\n\n assertDocumentTargetsCoverLinkedContainers(targets, writerProjection);\n assertAuthorizingContainerPathsMatchDocumentTargets({\n targets,\n writerProjection,\n });\n\n return targets;\n}\n\nexport async function assertDocumentWriterProjectionConsistent(\n ...input: Parameters<typeof assertDocumentWriterProjectionConsistentInternal>\n): ReturnType<typeof assertDocumentWriterProjectionConsistentInternal> {\n try {\n return await assertDocumentWriterProjectionConsistentInternal(...input);\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EAGL,2CAA2C,GAC5C,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,mCAAmC,EAAE,MAAM,6CAA6C,CAAC;AAClG,OAAO,EAAE,+BAA+B,EAAE,MAAM,sEAAs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VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { computeDocumentContentKeyTargetHash } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n type DocumentWriterProjectionAuthorization,\n type PrincipalPolicyCache,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../keyingProjectionVerification\";\nimport { throwKeyingVerificationShapeFailure } from \"../../../keyingProjectionVerification/error\";\nimport { openPrincipalPolicyBundleReader } from \"../../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { errorMessage } from \"../../../shared/errorMessage\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n assertDocumentManifestBundleConsistent,\n normalizeDocumentKekTargetResponse,\n sortDocumentTargets,\n targetEnvelopeReference,\n targetKey,\n uniqueSortedStrings,\n} from \"../readers\";\nimport {\n currentDocumentTargets,\n deriveDocumentTargetFromProjection,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"./projectionTargets\";\n\nexport { unwrapContainerKekPath } from \"../containerKek/containerKekPath\";\nexport { ContainerKekHistoryUnavailableError } from \"../containerKek/containerKekPathHistory\";\nexport { shouldRetryWithFreshProjection } from \"./freshProjectionRetry\";\nexport {\n buildRotatedDocumentContentKeyBundle,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapContentKeyTargetForKind,\n unwrapDocumentContentKeyFromBundle,\n unwrapDocumentContentKeyFromWriterProjection,\n unwrapDocumentContentKeyTarget,\n wrapDocumentContentKeyForCreate,\n} from \"./projectionContentKeys\";\nexport {\n authorizingContainerPathRefs,\n authorizingContainerPathRefsForLinkSet,\n containerPathRefs,\n currentDocumentTargets,\n deriveDocumentCreateTargets,\n deriveDocumentTargetFromProjection,\n mergeTargetEnvelopes,\n readLinkedContainerIdsFromDocumentManifest,\n verifiedDocumentWrapTargets,\n} from \"./projectionTargets\";\n\nimport type { ProjectionVerificationOptions } from \"./projectionVerificationOptions\";\nimport { resolveProjectionVerifier } from \"./projectionVerificationOptions\";\n\nfunction assertSortedStringsEqual(\n left: readonly string[],\n right: readonly string[],\n message: string,\n): void {\n if (\n left.length !== right.length ||\n left.some((value, index) => value !== right[index])\n ) {\n throw new Error(message);\n }\n}\n\nfunction assertAuthorizingContainerPathsMatchDocumentTargets(input: {\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}): void {\n if (input.writerProjection.authorizingContainerPaths.length === 0) {\n throw new Error(\"Document writer projection authorization paths missing\");\n }\n\n const targetKeys = new Set(input.targets.map(targetKey));\n for (const [\n index,\n projection,\n ] of input.writerProjection.authorizingContainerPaths.entries()) {\n let projectionTarget: DocumentContentKeyTarget;\n try {\n projectionTarget = deriveDocumentTargetFromProjection(projection);\n } catch (error) {\n throw new Error(\n `Document writer projection authorization path[${index}] is invalid: ${errorMessage(error)}`,\n );\n }\n\n if (targetKeys.has(targetKey(projectionTarget))) {\n continue;\n }\n\n // Bind server-supplied KEK paths to committed document targets before\n // using any unwrapped path KEK for document content-key material.\n throw new Error(\n `Document writer projection authorization path[${index}] is not a document target`,\n );\n }\n}\n\nfunction assertDocumentTargetsCoverLinkedContainers(\n targets: readonly DocumentContentKeyTarget[],\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n // One target per linked container: a second epoch for the same container\n // would let a re-wrap land on a KEK a revoked member still holds.\n if (\n new Set(targets.map((target) => target.containerId)).size !== targets.length\n ) {\n throw new Error(\n \"Document writer projection targets name a linked container more than once\",\n );\n }\n assertSortedStringsEqual(\n uniqueSortedStrings(targets.map((target) => target.containerId)),\n readLinkedContainerIdsFromDocumentManifest(writerProjection),\n \"Document writer projection targets do not match linked containers\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerManifestHashes,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerManifestHash)),\n \"Document writer projection target manifest summary mismatch\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerKeyEpochIds,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerKeyEpochId)),\n \"Document writer projection target KEK summary mismatch\",\n );\n}\n\nasync function assertProjectionContentKeyBundleConsistent(\n writerProjection: DocumentWriterProjectionResponse,\n staleContentKeyBundle: boolean,\n): Promise<void> {\n const { manifestHash } = writerProjection.documentManifest;\n // A stale bundle may lag the link-set head, but it must still descend from\n // this document's manifest chain.\n if (\n writerProjection.contentKeyBundle.linkSetManifestHash !== manifestHash &&\n (!staleContentKeyBundle ||\n !writerProjection.documentManifestHistory.some(\n (bundle) =>\n bundle.manifestHash ===\n writerProjection.contentKeyBundle.linkSetManifestHash,\n ))\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n\n if (!staleContentKeyBundle) {\n if (\n writerProjection.documentKekTargets.documentKeyTargetHash !==\n writerProjection.contentKeyBundle.targetHash\n ) {\n throw new Error(\"Document writer projection target hash mismatch\");\n }\n return;\n }\n\n // The stale bundle cannot match the current targets; pin it to its own\n // canonical hash instead so a tampered envelope set still fails closed.\n const staleBundleTargetHash = await computeDocumentContentKeyTargetHash(\n sortDocumentTargets(\n writerProjection.contentKeyBundle.targets.map(targetEnvelopeReference),\n ),\n );\n if (staleBundleTargetHash !== writerProjection.contentKeyBundle.targetHash) {\n throw new Error(\n \"Document writer projection stale bundle target hash is not canonical\",\n );\n }\n}\n\nasync function assertDocumentWriterProjectionConsistentInternal(\n writerProjection: DocumentWriterProjectionResponse,\n input: ProjectionVerificationOptions & {\n /**\n * Accept a projection whose content-key bundle is marked stale (wrapped\n * to superseded KEK targets after e.g. a revoke rotation). Document sync\n * opts in to heal the bundle. Attachment reads opt in because their DEK\n * is independent and opens through verified retained container KEKs.\n */\n allowStaleContentKeyBundle?: boolean | undefined;\n execSql?: ExecSql | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n onVerifiedAuthorization?:\n | ((authorization: DocumentWriterProjectionAuthorization) => void)\n | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n stillCurrent?: (() => boolean) | undefined;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n },\n): Promise<DocumentContentKeyTarget[]> {\n const resolveProjectionUserKey = resolveProjectionVerifier(\n input,\n \"Document writer projection\",\n );\n if (\n input.trustedLocalProjection !== true &&\n resolveProjectionUserKey !== null\n ) {\n const authorization = await verifyDocumentWriterProjectionAuthorization({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: writerProjection,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n input.onVerifiedAuthorization?.(authorization);\n }\n\n const staleContentKeyBundle = writerProjection.contentKeyBundleStale === true;\n if (staleContentKeyBundle && input.allowStaleContentKeyBundle !== true) {\n throw new Error(\"Document writer projection content-key bundle is stale\");\n }\n\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: writerProjection.documentManifest,\n label: \"Document writer projection manifest\",\n });\n const { documentId } = manifestIdentity;\n if (\n writerProjection.documentId !== documentId ||\n writerProjection.documentKekTargets.documentId !== documentId ||\n writerProjection.contentKeyBundle.documentId !== documentId\n ) {\n throw new Error(\"Document writer projection document id mismatch\");\n }\n if (\n writerProjection.documentKekTargets.linkSetManifestHash !==\n writerProjection.documentManifest.manifestHash\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n await assertProjectionContentKeyBundleConsistent(\n writerProjection,\n staleContentKeyBundle,\n );\n\n const targets = staleContentKeyBundle\n ? normalizeDocumentKekTargetResponse(writerProjection.documentKekTargets)\n : currentDocumentTargets(writerProjection);\n const canonicalTargetHash =\n await computeDocumentContentKeyTargetHash(targets);\n if (\n canonicalTargetHash !==\n writerProjection.documentKekTargets.documentKeyTargetHash\n ) {\n throw new Error(\"Document writer projection target hash is not canonical\");\n }\n\n assertDocumentTargetsCoverLinkedContainers(targets, writerProjection);\n assertAuthorizingContainerPathsMatchDocumentTargets({\n targets,\n writerProjection,\n });\n\n return targets;\n}\n\nexport async function assertDocumentWriterProjectionConsistent(\n ...input: Parameters<typeof assertDocumentWriterProjectionConsistentInternal>\n): ReturnType<typeof assertDocumentWriterProjectionConsistentInternal> {\n try {\n return await assertDocumentWriterProjectionConsistentInternal(...input);\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
@@ -4,9 +4,11 @@ import type { DocumentPurgeCheckpoint } from "../../persistence/keyingCheckpoint
4
4
  import type { VerifiedManifestBundle } from "../../persistence/verifiedManifestBundlePersistence.js";
5
5
  import type { PrincipalPolicyCheckpointEvidence } from "../../principals/principalPolicyEvidence.js";
6
6
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
7
+ import { type OpenPrincipalPolicyBundleReader } from "../types.js";
7
8
  export interface ProjectionCheckpointContext {
8
9
  readonly heldContainerHeads: VerifiedContainerAccessManifest[];
9
10
  readonly execSql: ExecSql;
11
+ readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;
10
12
  readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;
11
13
  organizationId?: string | undefined;
12
14
  readonly policies: PrincipalPolicyCheckpointEvidence[];
@@ -17,6 +19,7 @@ export interface ProjectionCheckpointContext {
17
19
  }
18
20
  export declare function createProjectionCheckpointContext(input: {
19
21
  readonly execSql: ExecSql;
22
+ readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;
20
23
  readonly organizationId?: string | undefined;
21
24
  }): ProjectionCheckpointContext;
22
25
  export declare function observeAccessManifestCheckpoints(context: ProjectionCheckpointContext, input: {
@@ -4,7 +4,7 @@ import { rememberVerifiedContainerHeads } from "../../containers/shared/heldCont
4
4
  import { PrincipalAuthorizationCheckpointUnavailableError } from "../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js";
5
5
  import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
6
6
  import { projectionLifetimeGuard } from "../projectionLifetimes.js";
7
- import { assertProjectionVerificationCurrent } from "../types.js";
7
+ import { assertProjectionVerificationCurrent, } from "../types.js";
8
8
  import { enforceAccessManifestCheckpoints, validateAccessManifestCheckpoints, } from "./accessManifestCheckpointEnforcement.js";
9
9
  import { matchesVerifiedBundleBytes } from "./verifiedBundleBytes.js";
10
10
  export function createProjectionCheckpointContext(input) {
@@ -14,6 +14,7 @@ export function createProjectionCheckpointContext(input) {
14
14
  return {
15
15
  heldContainerHeads: [],
16
16
  execSql: input.execSql,
17
+ openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,
17
18
  localCheckpoints: new Map(),
18
19
  organizationId: input.organizationId,
19
20
  policies: [],
@@ -1 +1 @@
1
- {"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,qBAAqB,GACtB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAE5F,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAGzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAiBnE,MAAM,UAAU,iCAAiC,CAAC,KAGjD;IACC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACxC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EAC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OAAO;IAC7C,MAAM,cAAc,GAClB,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport { rememberVerifiedContainerHeads } from \"../../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
1
+ {"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpoint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AK,EAAE,YAAY;QACjC,eAAe,EAAE,OAAO,CAAC,eAAe;QACxC,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC7C,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC1B,IAAI,KAAK,YAAY,gDAAgD;YACnE,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AAC3D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAoC,EACpC,KAIC;IAED,IAAI,KAAK,CAAC,8BAA8B,KAAK,KAAK,EAAE,CAAC;QACnD,MAAM,6BAA6B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACpD,OAAO;IACT,CAAC;IACD,MAAM,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAClD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO;IAC7C,MAAM,cAAc,GAClB,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport { rememberVerifiedContainerHeads } from \"../../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type OpenPrincipalPolicyBundleReader,\n} from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // The caller's principal policy bundle store, opened per executor.\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
@@ -1,10 +1,11 @@
1
1
  import type { VerifiedContainerAccessManifest } from "../../../internal/crypto/index.js";
2
2
  import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
3
3
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
4
- import type { ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";
4
+ import type { OpenPrincipalPolicyBundleReader, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";
5
5
  /** Authenticate immutable destination roles without advancing write-authority pins. */
6
6
  export declare function verifyContainerDestinationProjection(input: {
7
7
  readonly execSql: ExecSql;
8
+ readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;
8
9
  readonly projection: ContainerWriterProjectionResponse;
9
10
  readonly resolveUserKey: ProjectionUserKeyResolver;
10
11
  readonly stillCurrent?: (() => boolean) | undefined;
@@ -11,6 +11,7 @@ export async function verifyContainerDestinationProjection(input) {
11
11
  const verifiedByHash = new Map();
12
12
  const checkpointContext = createProjectionCheckpointContext({
13
13
  execSql: input.execSql,
14
+ openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,
14
15
  organizationId: input.projection.organizationId,
15
16
  });
16
17
  const principalPolicyCache = new Map();
@@ -1 +1 @@
1
- {"version":3,"file":"containerDestinationVerification.js","sourceRoot":"","sources":["containerDestinationVerification.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAKjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AAExF,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAQ1D;IAKC,MAAM,aAAa,GAAG,IAAI,GAAG,EAA4C,CAAC;IAC1E,mCAAmC,CACjC,aAAa,EACb,KAAK,CAAC,UAAU,EAChB,uBAAuB,CACxB,CAAC;IACF,MAAM,cAAc,GAAG,IAAI,GAAG,EAA2C,CAAC;IAC1E,MAAM,iBAAiB,GAAG,iCAAiC,CAAC;QAC1D,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC,cAAc;KAChD,CAAC,CAAC;IACH,MA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C,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\nimport { addContainerWriterProjectionBundles } from \"./containerProjectionVerification\";\n\n/** Authenticate immutable destination roles without advancing write-authority pins. */\nexport async function verifyContainerDestinationProjection(input: {\n readonly execSql: ExecSql;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<{\n readonly path: VerifiedContainerAccessManifest[];\n /** Every manifest verified on the way, including each head's lineage. */\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n input.projection,\n \"Container destination\",\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const principalPolicyCache = new Map();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [...bundlesByHash.values()],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const path = await verifyContainerManifestPath({\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext,\n enforceLocalCheckpoints: false,\n servedAsCurrent: false,\n label: \"Container destination\",\n path: input.projection.path,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n });\n const current = projectionLifetimeGuard(\n checkpointContext,\n input.stillCurrent,\n );\n // Authenticated bytes, not authority: a later read may cite them.\n observeVerifiedProjectionBundles(\n checkpointContext,\n bundlesByHash,\n verifiedByHash,\n );\n // Destination roles never unwrap these levels; a citation refills them only\n // where the API's current level has the same digest, and the reading\n // verification then checks them like served bytes.\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, {\n stillCurrent: current,\n persistVerificationCheckpoints: false,\n });\n assertProjectionVerificationCurrent(current);\n return { path, verifiedByHash };\n}\n"]}
1
+ {"version":3,"file":"containerDestinationVerification.js","sourceRoot":"","sources":["containerDestinationVerification.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAMjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AAExF,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAS1D;IAKC,MAAM,aAAa,GAAG,IAAI,GAAG,EAA4C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CAAC;IACF,4EAA4E;IAC5E,qEAAqE;IACrE,mDAAmD;IACnD,wBAAwB,CAAC,iBAAiB,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;IAChE,MAAM,6BAA6B,CAAC,iBAAiB,EAAE;QACrD,YAAY,EAAE,OAAO;QACrB,8BAA8B,EAAE,KAAK;KACtC,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAClC,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\nimport { addContainerWriterProjectionBundles } from \"./containerProjectionVerification\";\n\n/** Authenticate immutable destination roles without advancing write-authority pins. */\nexport async function verifyContainerDestinationProjection(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<{\n readonly path: VerifiedContainerAccessManifest[];\n /** Every manifest verified on the way, including each head's lineage. */\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n input.projection,\n \"Container destination\",\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const principalPolicyCache = new Map();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [...bundlesByHash.values()],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const path = await verifyContainerManifestPath({\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext,\n enforceLocalCheckpoints: false,\n servedAsCurrent: false,\n label: \"Container destination\",\n path: input.projection.path,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n });\n const current = projectionLifetimeGuard(\n checkpointContext,\n input.stillCurrent,\n );\n // Authenticated bytes, not authority: a later read may cite them.\n observeVerifiedProjectionBundles(\n checkpointContext,\n bundlesByHash,\n verifiedByHash,\n );\n // Destination roles never unwrap these levels; a citation refills them only\n // where the API's current level has the same digest, and the reading\n // verification then checks them like served bytes.\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, {\n stillCurrent: current,\n persistVerificationCheckpoints: false,\n });\n assertProjectionVerificationCurrent(current);\n return { path, verifiedByHash };\n}\n"]}
@@ -4,9 +4,10 @@ import type { AccessManifestBundleWireResponse, ContainerWriterProjectionRespons
4
4
  import type { PrincipalPolicyCurrentEvidence } from "../../principals/principalPolicyEvidence.js";
5
5
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
6
6
  import { type ProjectionCheckpointContext } from "../checkpoints/checkpointContext.js";
7
- import type { PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";
7
+ import type { OpenPrincipalPolicyBundleReader, PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";
8
8
  interface ContainerWriterProjectionVerificationInput {
9
9
  readonly execSql: ExecSql;
10
+ readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;
10
11
  readonly persistVerificationCheckpoints?: boolean | undefined;
11
12
  readonly principalPolicyCache?: PrincipalPolicyCache | undefined;
12
13
  readonly projection: ContainerWriterProjectionResponse;
@@ -16,7 +17,7 @@ interface ContainerWriterProjectionVerificationInput {
16
17
  readonly warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
17
18
  }
18
19
  export declare function verifiedContainerManifestsForBundles(bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>, verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>): VerifiedContainerAccessManifest[];
19
- export declare function verifyContainerWriterProjectionWithContext(input: Omit<ContainerWriterProjectionVerificationInput, "execSql"> & {
20
+ export declare function verifyContainerWriterProjectionWithContext(input: Omit<ContainerWriterProjectionVerificationInput, "execSql" | "openPrincipalPolicyBundleReader"> & {
20
21
  readonly authorizationEvidence?: readonly PrincipalPolicyAuthorization[];
21
22
  }, checkpointContext: ProjectionCheckpointContext): Promise<VerifiedContainerAccessManifest[]>;
22
23
  export declare function verifyContainerWriterProjection(input: ContainerWriterProjectionVerificationInput): Promise<VerifiedContainerAccessManifest[]>;
@@ -180,6 +180,7 @@ export async function verifyContainerWriterProjection(input) {
180
180
  };
181
181
  const checkpointContext = createProjectionCheckpointContext({
182
182
  execSql: input.execSql,
183
+ openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,
183
184
  organizationId: input.projection.organizationId,
184
185
  });
185
186
  const verifiedPath = await verifyContainerWriterProjectionWithContext(guardedInput, checkpointContext);
@@ -203,6 +204,7 @@ export async function collectContainerWriterProjectionPrincipalPolicies(input) {
203
204
  new Map();
204
205
  const checkpointContext = createProjectionCheckpointContext({
205
206
  execSql: input.execSql,
207
+ openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,
206
208
  organizationId: input.projection.organizationId,
207
209
  });
208
210
  const verifiedPath = await verifyContainerWriterProjectionWithContext({
@@ -1 +1 @@
1
- {"version":3,"file":"containerProjectionVerification.js","sourceRoot":"","sources":["containerProjectionVerification.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,sCAAsC,EACtC,4BAA4B,EAC5B,aAAa,EAGb,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AACpG,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EACL,+BAA+B,EAC/B,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAMpB,OAAO,EACL,mCAAmC,EACnC,sCAAsC,EACtC,iCAAiC,GAClC,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAE1E,KAAK,UAAU,iCAAiC,CAAC,KAGhD;IACC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,GAAG,CACR,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rD,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC;AAED,KAAK,UAAU,yCAAyC,CAAC,KAOxD;IACC,MAAM,wBAAwB,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAC5D,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAC5E,CAAC;IAEF,OAAO,kCAAkC,CAAC;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,wBAAwB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyAuthorization } from \"@tearleads/crypto\";\nimport {\n type ContainerUserRecipientKey,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n toFingerprint,\n type VerifiedContainerAccessManifest,\n type VerifiedContainerKekState,\n verifyContainerKekState,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { collectReferencedPrincipalPolicies } from \"../principalPolicy/principalPolicyVerification\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport {\n readContainerKekRecipientTarget,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n withGenerationGuardedPolicyWarmer,\n} from \"../types\";\nimport { verifyContainerManifestBundle } from \"./containerManifestVerification\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\n\nasync function collectContainerUserRecipientKeys(input: {\n readonly containerManifest: VerifiedContainerAccessManifest;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<ContainerUserRecipientKey[]> {\n const userIds = [\n ...new Set(\n input.containerManifest.state.directGrants\n .filter((grant) => grant.subjectType === \"user\")\n .map((grant) => grant.subjectId),\n ),\n ].sort();\n const userRecipientKeys: ContainerUserRecipientKey[] = [];\n\n for (const userId of userIds) {\n const userKey = await input.resolveUserKey(userId);\n if (!userKey) {\n throw new ProjectionDependencyUnavailableError(\n `Container writer projection recipient key could not be resolved for ${userId}`,\n );\n }\n const recipientKeyFingerprint = await toFingerprint(\n userKey.encapsulationPublicKey,\n );\n userRecipientKeys.push({\n userId,\n recipientKeyEpochId: `user:${userId}:encapsulation:${recipientKeyFingerprint}`,\n recipientKeyFingerprint,\n });\n }\n\n return userRecipientKeys;\n}\n\nfunction containerKekManifestHistory(input: {\n readonly history: readonly VerifiedContainerAccessManifest[];\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n}): VerifiedContainerAccessManifest[] {\n const historyByHash = new Map<string, VerifiedContainerAccessManifest>();\n\n for (const manifest of input.history) {\n if (\n manifest.state.containerId === input.verifiedManifest.state.containerId &&\n manifest.manifestHash !== input.verifiedManifest.manifestHash\n ) {\n historyByHash.set(manifest.manifestHash, manifest);\n }\n }\n\n return [...historyByHash.values()];\n}\n\nasync function verifyContainerKekProjection(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly kek: ContainerWriterProjectionResponse[\"containerKeks\"][number];\n readonly label: string;\n readonly parentKekState: VerifiedContainerKekState | null;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n readonly verifiedManifestHistory: readonly VerifiedContainerAccessManifest[];\n readonly parentManifestHistory: readonly VerifiedContainerAccessManifest[];\n}): Promise<VerifiedContainerKekState> {\n if (input.verifiedManifest.state.parentContainerId && !input.parentKekState) {\n throw new Error(`${input.label} requires verified parent KEK state`);\n }\n\n const keyEpoch = readContainerKeyEpoch(\n input.kek.keyEpoch,\n `${input.label} key epoch`,\n );\n const wraps = input.kek.wraps.map((wrap, index) =>\n readContainerKeyWrap(wrap, `${input.label} wrap[${index}]`),\n );\n const userRecipientKeys = await collectContainerUserRecipientKeys({\n containerManifest: input.verifiedManifest,\n resolveUserKey: input.resolveUserKey,\n });\n const verifiedKekManifestHistory = containerKekManifestHistory({\n history: input.verifiedManifestHistory,\n verifiedManifest: input.verifiedManifest,\n });\n const verified = await verifyContainerKekState({\n allowHistoricalParentEpoch: true,\n containerManifest: input.verifiedManifest,\n containerManifestHistory: verifiedKekManifestHistory,\n parentManifestHistory: input.parentManifestHistory,\n keyEpoch,\n parentKekState: input.parentKekState,\n principalPolicies: input.authorizationEvidence,\n userRecipientKeys,\n wraps,\n });\n if (!verified.ok) {\n throw new Error(`${input.label} KEK verification failed`);\n }\n\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n if (keyEpochHash !== input.kek.keyEpochHash) {\n throw new Error(`${input.label} key epoch hash mismatch`);\n }\n const recipientTargets = input.kek.recipientTargets.map((target, index) =>\n readContainerKekRecipientTarget(\n target,\n `${input.label} recipient target[${index}]`,\n ),\n );\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n if (\n keyTargetHash !== input.kek.keyTargetHash ||\n keyTargetHash !== verified.value.keyTargetHash\n ) {\n throw new Error(`${input.label} target hash mismatch`);\n }\n if (\n verified.value.containerKeyEpochId !== input.kek.containerKeyEpochId ||\n verified.value.containerKeyEpoch !== input.kek.containerKeyEpoch ||\n verified.value.accessManifestHash !== input.kek.accessManifestHash ||\n verified.value.parentContainerKeyEpochId !==\n input.kek.parentContainerKeyEpochId\n ) {\n throw new Error(`${input.label} identity mismatch`);\n }\n\n return verified.value;\n}\n\ninterface ContainerWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nexport function verifiedContainerManifestsForBundles(\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n): VerifiedContainerAccessManifest[] {\n return [...bundlesByHash.keys()].flatMap((manifestHash) => {\n const verified = verifiedByHash.get(manifestHash);\n return verified ? [verified] : [];\n });\n}\n\nfunction collectContainerProjectionBundles(\n projection: ContainerWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n projection,\n \"Container writer projection\",\n );\n return bundlesByHash;\n}\n\nexport async function verifyContainerWriterProjectionWithContext(\n input: Omit<ContainerWriterProjectionVerificationInput, \"execSql\"> & {\n readonly authorizationEvidence?: readonly PrincipalPolicyAuthorization[];\n },\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedContainerAccessManifest[]> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n\n const bundlesByHash = collectContainerProjectionBundles(input.projection);\n\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verification = {\n checkpointContext,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n };\n const authorizationEvidence =\n input.authorizationEvidence ??\n (await verifyProjectionAuthorizationEvidence({\n ...verification,\n bundles: [...bundlesByHash.values()],\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n stillCurrent: input.stillCurrent,\n }));\n const verifiedPath = await verifyContainerManifestPath({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: true,\n bundlesByHash,\n enforceLocalCheckpoints: true,\n label: \"Container writer projection path\",\n path: input.projection.path,\n verifiedByHash,\n });\n\n const verifiedKekStates: VerifiedContainerKekState[] = [];\n for (const [index, kek] of input.projection.containerKeks.entries()) {\n const verifiedManifest = verifiedPath[index];\n if (!verifiedManifest) {\n throw new Error(`Container writer projection KEK[${index}] is missing`);\n }\n const verifiedManifestHistory: VerifiedContainerAccessManifest[] = [];\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n verifiedManifestHistory.push(\n await verifyContainerManifestBundle({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle,\n bundlesByHash,\n enforceLocalCheckpoint: false,\n label: `Container writer projection KEK[${index}] history[${historyIndex}]`,\n parentPath: verifiedPath.slice(0, index),\n verifiedByHash,\n }),\n );\n }\n\n const verifiedKekState = await verifyContainerKekProjection({\n authorizationEvidence,\n kek,\n label: `Container writer projection KEK[${index}]`,\n parentKekState: index > 0 ? (verifiedKekStates[index - 1] ?? null) : null,\n resolveUserKey: input.resolveUserKey,\n verifiedManifest,\n verifiedManifestHistory,\n parentManifestHistory: [...verifiedByHash.values()],\n });\n verifiedKekStates.push(verifiedKekState);\n }\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: verifiedPath,\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n checkpointContext.heldContainerHeads.push(...verifiedPath);\n return verifiedPath;\n}\n\nexport async function verifyContainerWriterProjection(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<VerifiedContainerAccessManifest[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const guardedInput = {\n ...withGenerationGuardedPolicyWarmer(input),\n verifiedByHash,\n };\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n guardedInput,\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return verifiedPath;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport async function collectContainerWriterProjectionPrincipalPolicies(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<PrincipalPolicyCurrentEvidence[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n {\n principalPolicyCache,\n projection: input.projection,\n verifiedByHash,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n },\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n\n const policies = await collectPrincipalPoliciesForContainerPaths({\n checkpointContext,\n organizationId: input.projection.organizationId,\n paths: [verifiedPath],\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function addContainerWriterProjectionBundles(\n bundlesByHash: Map<string, AccessManifestBundleWireResponse>,\n projection: ContainerWriterProjectionResponse,\n label: string,\n): void {\n for (const [index, bundle] of projection.path.entries()) {\n addBundleByHash(bundlesByHash, bundle, `${label} path[${index}]`);\n }\n for (const [kekIndex, kek] of projection.containerKeks.entries()) {\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `${label} KEK[${kekIndex}] history[${historyIndex}]`,\n );\n }\n }\n}\n\nasync function collectPrincipalPoliciesForContainerPaths(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n paths: readonly (readonly VerifiedContainerAccessManifest[] | undefined)[];\n principalPolicyCache: PrincipalPolicyCache;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const referencedPrincipalHeads = input.paths.flatMap((path) =>\n (path ?? []).flatMap((manifest) => manifest.state.referencedPrincipalHeads),\n );\n\n return collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references: referencedPrincipalHeads,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
1
+ {"version":3,"file":"containerProjectionVerification.js","sourceRoot":"","sources":["containerProjectionVerification.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,sCAAsC,EACtC,4BAA4B,EAC5B,aAAa,EAGb,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AACpG,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EACL,+BAA+B,EAC/B,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAOpB,OAAO,EACL,mCAAmC,EACnC,sCAAsC,EACtC,iCAAiC,GAClC,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAE1E,KAAK,UAAU,iCAAiC,CAAC,KAGhD;IACC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,GAAG,CACR,KAAK,CAAC,iBAAiB,CAAC,KAAK,CAAC,YAAY;aACvC,MAAM,CAAC,CAAC,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AAY,GAAG,CACrD,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC;AAED,KAAK,UAAU,yCAAyC,CAAC,KAOxD;IACC,MAAM,wBAAwB,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAC5D,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAC5E,CAAC;IAEF,OAAO,kCAAkC,CAAC;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,wBAAwB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyAuthorization } from \"@tearleads/crypto\";\nimport {\n type ContainerUserRecipientKey,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n toFingerprint,\n type VerifiedContainerAccessManifest,\n type VerifiedContainerKekState,\n verifyContainerKekState,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { collectReferencedPrincipalPolicies } from \"../principalPolicy/principalPolicyVerification\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport {\n readContainerKekRecipientTarget,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../readers\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n withGenerationGuardedPolicyWarmer,\n} from \"../types\";\nimport { verifyContainerManifestBundle } from \"./containerManifestVerification\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\n\nasync function collectContainerUserRecipientKeys(input: {\n readonly containerManifest: VerifiedContainerAccessManifest;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<ContainerUserRecipientKey[]> {\n const userIds = [\n ...new Set(\n input.containerManifest.state.directGrants\n .filter((grant) => grant.subjectType === \"user\")\n .map((grant) => grant.subjectId),\n ),\n ].sort();\n const userRecipientKeys: ContainerUserRecipientKey[] = [];\n\n for (const userId of userIds) {\n const userKey = await input.resolveUserKey(userId);\n if (!userKey) {\n throw new ProjectionDependencyUnavailableError(\n `Container writer projection recipient key could not be resolved for ${userId}`,\n );\n }\n const recipientKeyFingerprint = await toFingerprint(\n userKey.encapsulationPublicKey,\n );\n userRecipientKeys.push({\n userId,\n recipientKeyEpochId: `user:${userId}:encapsulation:${recipientKeyFingerprint}`,\n recipientKeyFingerprint,\n });\n }\n\n return userRecipientKeys;\n}\n\nfunction containerKekManifestHistory(input: {\n readonly history: readonly VerifiedContainerAccessManifest[];\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n}): VerifiedContainerAccessManifest[] {\n const historyByHash = new Map<string, VerifiedContainerAccessManifest>();\n\n for (const manifest of input.history) {\n if (\n manifest.state.containerId === input.verifiedManifest.state.containerId &&\n manifest.manifestHash !== input.verifiedManifest.manifestHash\n ) {\n historyByHash.set(manifest.manifestHash, manifest);\n }\n }\n\n return [...historyByHash.values()];\n}\n\nasync function verifyContainerKekProjection(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly kek: ContainerWriterProjectionResponse[\"containerKeks\"][number];\n readonly label: string;\n readonly parentKekState: VerifiedContainerKekState | null;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n readonly verifiedManifestHistory: readonly VerifiedContainerAccessManifest[];\n readonly parentManifestHistory: readonly VerifiedContainerAccessManifest[];\n}): Promise<VerifiedContainerKekState> {\n if (input.verifiedManifest.state.parentContainerId && !input.parentKekState) {\n throw new Error(`${input.label} requires verified parent KEK state`);\n }\n\n const keyEpoch = readContainerKeyEpoch(\n input.kek.keyEpoch,\n `${input.label} key epoch`,\n );\n const wraps = input.kek.wraps.map((wrap, index) =>\n readContainerKeyWrap(wrap, `${input.label} wrap[${index}]`),\n );\n const userRecipientKeys = await collectContainerUserRecipientKeys({\n containerManifest: input.verifiedManifest,\n resolveUserKey: input.resolveUserKey,\n });\n const verifiedKekManifestHistory = containerKekManifestHistory({\n history: input.verifiedManifestHistory,\n verifiedManifest: input.verifiedManifest,\n });\n const verified = await verifyContainerKekState({\n allowHistoricalParentEpoch: true,\n containerManifest: input.verifiedManifest,\n containerManifestHistory: verifiedKekManifestHistory,\n parentManifestHistory: input.parentManifestHistory,\n keyEpoch,\n parentKekState: input.parentKekState,\n principalPolicies: input.authorizationEvidence,\n userRecipientKeys,\n wraps,\n });\n if (!verified.ok) {\n throw new Error(`${input.label} KEK verification failed`);\n }\n\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n if (keyEpochHash !== input.kek.keyEpochHash) {\n throw new Error(`${input.label} key epoch hash mismatch`);\n }\n const recipientTargets = input.kek.recipientTargets.map((target, index) =>\n readContainerKekRecipientTarget(\n target,\n `${input.label} recipient target[${index}]`,\n ),\n );\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n if (\n keyTargetHash !== input.kek.keyTargetHash ||\n keyTargetHash !== verified.value.keyTargetHash\n ) {\n throw new Error(`${input.label} target hash mismatch`);\n }\n if (\n verified.value.containerKeyEpochId !== input.kek.containerKeyEpochId ||\n verified.value.containerKeyEpoch !== input.kek.containerKeyEpoch ||\n verified.value.accessManifestHash !== input.kek.accessManifestHash ||\n verified.value.parentContainerKeyEpochId !==\n input.kek.parentContainerKeyEpochId\n ) {\n throw new Error(`${input.label} identity mismatch`);\n }\n\n return verified.value;\n}\n\ninterface ContainerWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nexport function verifiedContainerManifestsForBundles(\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n): VerifiedContainerAccessManifest[] {\n return [...bundlesByHash.keys()].flatMap((manifestHash) => {\n const verified = verifiedByHash.get(manifestHash);\n return verified ? [verified] : [];\n });\n}\n\nfunction collectContainerProjectionBundles(\n projection: ContainerWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n projection,\n \"Container writer projection\",\n );\n return bundlesByHash;\n}\n\nexport async function verifyContainerWriterProjectionWithContext(\n input: Omit<\n ContainerWriterProjectionVerificationInput,\n \"execSql\" | \"openPrincipalPolicyBundleReader\"\n > & {\n readonly authorizationEvidence?: readonly PrincipalPolicyAuthorization[];\n },\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedContainerAccessManifest[]> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n\n const bundlesByHash = collectContainerProjectionBundles(input.projection);\n\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verification = {\n checkpointContext,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n };\n const authorizationEvidence =\n input.authorizationEvidence ??\n (await verifyProjectionAuthorizationEvidence({\n ...verification,\n bundles: [...bundlesByHash.values()],\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n stillCurrent: input.stillCurrent,\n }));\n const verifiedPath = await verifyContainerManifestPath({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: true,\n bundlesByHash,\n enforceLocalCheckpoints: true,\n label: \"Container writer projection path\",\n path: input.projection.path,\n verifiedByHash,\n });\n\n const verifiedKekStates: VerifiedContainerKekState[] = [];\n for (const [index, kek] of input.projection.containerKeks.entries()) {\n const verifiedManifest = verifiedPath[index];\n if (!verifiedManifest) {\n throw new Error(`Container writer projection KEK[${index}] is missing`);\n }\n const verifiedManifestHistory: VerifiedContainerAccessManifest[] = [];\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n verifiedManifestHistory.push(\n await verifyContainerManifestBundle({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle,\n bundlesByHash,\n enforceLocalCheckpoint: false,\n label: `Container writer projection KEK[${index}] history[${historyIndex}]`,\n parentPath: verifiedPath.slice(0, index),\n verifiedByHash,\n }),\n );\n }\n\n const verifiedKekState = await verifyContainerKekProjection({\n authorizationEvidence,\n kek,\n label: `Container writer projection KEK[${index}]`,\n parentKekState: index > 0 ? (verifiedKekStates[index - 1] ?? null) : null,\n resolveUserKey: input.resolveUserKey,\n verifiedManifest,\n verifiedManifestHistory,\n parentManifestHistory: [...verifiedByHash.values()],\n });\n verifiedKekStates.push(verifiedKekState);\n }\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: verifiedPath,\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n checkpointContext.heldContainerHeads.push(...verifiedPath);\n return verifiedPath;\n}\n\nexport async function verifyContainerWriterProjection(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<VerifiedContainerAccessManifest[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const guardedInput = {\n ...withGenerationGuardedPolicyWarmer(input),\n verifiedByHash,\n };\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n guardedInput,\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return verifiedPath;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport async function collectContainerWriterProjectionPrincipalPolicies(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<PrincipalPolicyCurrentEvidence[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n {\n principalPolicyCache,\n projection: input.projection,\n verifiedByHash,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n },\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n\n const policies = await collectPrincipalPoliciesForContainerPaths({\n checkpointContext,\n organizationId: input.projection.organizationId,\n paths: [verifiedPath],\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function addContainerWriterProjectionBundles(\n bundlesByHash: Map<string, AccessManifestBundleWireResponse>,\n projection: ContainerWriterProjectionResponse,\n label: string,\n): void {\n for (const [index, bundle] of projection.path.entries()) {\n addBundleByHash(bundlesByHash, bundle, `${label} path[${index}]`);\n }\n for (const [kekIndex, kek] of projection.containerKeks.entries()) {\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `${label} KEK[${kekIndex}] history[${historyIndex}]`,\n );\n }\n }\n}\n\nasync function collectPrincipalPoliciesForContainerPaths(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n paths: readonly (readonly VerifiedContainerAccessManifest[] | undefined)[];\n principalPolicyCache: PrincipalPolicyCache;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const referencedPrincipalHeads = input.paths.flatMap((path) =>\n (path ?? []).flatMap((manifest) => manifest.state.referencedPrincipalHeads),\n );\n\n return collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references: referencedPrincipalHeads,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
@@ -1,11 +1,12 @@
1
1
  import type { PrincipalPolicyAuthorization, VerifiedContainerAccessManifest, VerifiedDocumentLinkSetManifest } from "../../../internal/crypto/index.js";
2
2
  import type { DocumentWriterProjectionResponse } from "../../../internal/validators/response/index.js";
3
3
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
4
- import type { PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";
4
+ import type { OpenPrincipalPolicyBundleReader, PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";
5
5
  type VerifiedManifestMap = Map<string, VerifiedContainerAccessManifest>;
6
6
  type PolicyWarmer = ReferencedPrincipalPolicyWarmer | undefined;
7
7
  interface DocumentWriterProjectionVerificationInput {
8
8
  readonly execSql: ExecSql;
9
+ readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;
9
10
  readonly persistVerificationCheckpoints?: boolean | undefined;
10
11
  readonly principalPolicyCache?: PrincipalPolicyCache | undefined;
11
12
  readonly projection: DocumentWriterProjectionResponse;
@@ -150,6 +150,7 @@ function observeVerifiedDocumentProjectionBundles(checkpointContext, projection,
150
150
  export async function verifyDocumentWriterProjection(input) {
151
151
  const checkpointContext = createProjectionCheckpointContext({
152
152
  execSql: input.execSql,
153
+ openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,
153
154
  });
154
155
  const verified = await verifyDocumentWriterProjectionWithContext(withGenerationGuardedPolicyWarmer(input), checkpointContext);
155
156
  observeVerifiedDocumentProjectionBundles(checkpointContext, input.projection, verified.authorization);
@@ -160,6 +161,7 @@ export async function verifyDocumentWriterProjectionAuthorization(input) {
160
161
  try {
161
162
  const checkpointContext = createProjectionCheckpointContext({
162
163
  execSql: input.execSql,
164
+ openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,
163
165
  });
164
166
  const verified = await verifyDocumentWriterProjectionWithContext(withGenerationGuardedPolicyWarmer(input), checkpointContext);
165
167
  observeVerifiedDocumentProjectionBundles(checkpointContext, input.projection, verified.authorization);