@tearleads/client-sdk 0.1.218 → 0.1.220

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 (131) hide show
  1. package/client/organizations/organizationGroupHistory.js +1 -1
  2. package/client/organizations/organizationGroupHistory.js.map +1 -1
  3. package/client/organizations/organizationGroupPresentation.js +1 -1
  4. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  5. package/client/organizations/organizationHistory.js +1 -1
  6. package/client/organizations/organizationHistory.js.map +1 -1
  7. package/client/organizations/principalMutations.js +1 -1
  8. package/client/organizations/principalMutations.js.map +1 -1
  9. package/client/organizations/recipientAdmission.js +1 -1
  10. package/client/organizations/recipientAdmission.js.map +1 -1
  11. package/data/keyingProjectionVerification/checkpoints/bundleVerification.js +1 -1
  12. package/data/keyingProjectionVerification/checkpoints/bundleVerification.js.map +1 -1
  13. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
  14. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  15. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +1 -1
  16. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  17. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +1 -1
  18. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  19. package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js +1 -1
  20. package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js.map +1 -1
  21. package/data/keyingProjectionVerification/error.js +1 -1
  22. package/data/keyingProjectionVerification/error.js.map +1 -1
  23. package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js +1 -1
  24. package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js.map +1 -1
  25. package/data/keyingProjectionVerification/principalPolicy/projectionPolicyEvidence.js +1 -1
  26. package/data/keyingProjectionVerification/principalPolicy/projectionPolicyEvidence.js.map +1 -1
  27. package/data/principals/principalIdentityCommitments.js +1 -1
  28. package/data/principals/principalIdentityCommitments.js.map +1 -1
  29. package/data/trustedUserIdentity/apiAdapter.js +1 -1
  30. package/data/trustedUserIdentity/apiAdapter.js.map +1 -1
  31. package/index.d.ts +2 -2
  32. package/index.js +1 -1
  33. package/index.js.map +1 -1
  34. package/package.json +1 -1
  35. package/stores/documents/documentStore/history/historyRebuild.js.map +1 -1
  36. package/stores/documents/documentStore/rotation/index.js +10 -6
  37. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  38. package/stores/documents/documentStore/sync/createdDocumentPersistence.js.map +1 -1
  39. package/stores/documents/documentStore/sync/syncRequest.js +9 -6
  40. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  41. package/stores/documents/documentStore/sync/syncShared.js +9 -6
  42. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  43. package/workflows/blobs/verification/attachmentDecryptor.js +1 -1
  44. package/workflows/blobs/verification/attachmentDecryptor.js.map +1 -1
  45. package/workflows/blobs/verification/verifiedWrapScope.js +1 -1
  46. package/workflows/blobs/verification/verifiedWrapScope.js.map +1 -1
  47. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +1 -1
  48. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
  49. package/workflows/container-contents/container-state/remote.js +1 -1
  50. package/workflows/container-contents/container-state/remote.js.map +1 -1
  51. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -1
  52. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  53. package/workflows/container-contents/container-state/share/groupShareEpoch.js +1 -1
  54. package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -1
  55. package/workflows/container-contents/container-state/types.js.map +1 -1
  56. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +4 -6
  57. package/workflows/container-contents/metadata/metadataRemoteSync.js +11 -7
  58. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  59. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
  60. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
  61. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +1 -1
  62. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  63. package/workflows/containers/child/revoke.js +1 -1
  64. package/workflows/containers/child/revoke.js.map +1 -1
  65. package/workflows/containers/child/share/index.js +1 -1
  66. package/workflows/containers/child/share/index.js.map +1 -1
  67. package/workflows/documents/create/createResponse.js +1 -1
  68. package/workflows/documents/create/createResponse.js.map +1 -1
  69. package/workflows/documents/create/index.d.ts +5 -42
  70. package/workflows/documents/create/index.js +12 -1
  71. package/workflows/documents/create/index.js.map +1 -1
  72. package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +47 -0
  73. package/workflows/documents/create/remoteDocumentCreateRequest.js +2 -0
  74. package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -0
  75. package/workflows/documents/index.d.ts +5 -4
  76. package/workflows/documents/index.js +1 -2
  77. package/workflows/documents/index.js.map +1 -1
  78. package/workflows/documents/linkSet/linkSetBlobRewraps.js +1 -1
  79. package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -1
  80. package/workflows/documents/purge/index.js +1 -1
  81. package/workflows/documents/purge/index.js.map +1 -1
  82. package/workflows/documents/remote/remoteDocumentCollaborators.d.ts +6 -4
  83. package/workflows/documents/remote/remoteDocumentCollaborators.js.map +1 -1
  84. package/workflows/documents/remote/remoteDocumentService.d.ts +12 -5
  85. package/workflows/documents/remote/remoteDocumentService.js +14 -4
  86. package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
  87. package/workflows/documents/sync/index.js +18 -6
  88. package/workflows/documents/sync/index.js.map +1 -1
  89. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  90. package/workflows/documents/sync/{readOnlySync.d.ts → remoteDocumentSyncPass.d.ts} +18 -18
  91. package/workflows/documents/sync/remoteDocumentSyncPass.js +2 -0
  92. package/workflows/documents/sync/remoteDocumentSyncPass.js.map +1 -0
  93. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  94. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  95. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  96. package/workflows/documents/syncFailures/syncFailureClassification.js +1 -1
  97. package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
  98. package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -1
  99. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  100. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +4 -3
  101. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js.map +1 -1
  102. package/workflows/documents/syncRekeys/syncContainerRekeys.js.map +1 -1
  103. package/workflows/organizations/currentOrganizationAuthority.js +1 -1
  104. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  105. package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js +1 -1
  106. package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js.map +1 -1
  107. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js +1 -1
  108. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -1
  109. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js +1 -1
  110. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -1
  111. package/workflows/organizations/groupNames/organizationGroupNames.js +1 -1
  112. package/workflows/organizations/groupNames/organizationGroupNames.js.map +1 -1
  113. package/workflows/organizations/groupShare/groupShareReplan.js +1 -1
  114. package/workflows/organizations/groupShare/groupShareReplan.js.map +1 -1
  115. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +1 -1
  116. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
  117. package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js +1 -1
  118. package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -1
  119. package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
  120. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
  121. package/workflows/principals/principalPolicyService.js +1 -1
  122. package/workflows/principals/principalPolicyService.js.map +1 -1
  123. package/workflows/principals/recoveryOperation/principalRecoveryOutage.js +1 -1
  124. package/workflows/principals/recoveryOperation/principalRecoveryOutage.js.map +1 -1
  125. package/workflows/principals/runtimePolicyRecovery.js +1 -1
  126. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  127. package/workflows/principals/runtimeProjectionPolicyRecovery.js +1 -1
  128. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  129. package/workflows/documents/sync/index.d.ts +0 -3
  130. /package/data/{keyingProjectionVerification → shared}/dependencyUnavailable.js +0 -0
  131. /package/data/{keyingProjectionVerification → shared}/dependencyUnavailable.js.map +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"syncContainerRekeyPreparation.js","sourceRoot":"","sources":["syncContainerRekeyPreparation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,yDAAyD,CAAC;AAE5G,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAC9F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EACL,uBAAuB,EACvB,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,oCAAoC,EAAE,MAA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BAAuB,EAAE,IAAI,CAAC,uBAAuB;QACrD,eAAe,EAAE,IAAI,CAAC,eAAe;QACrC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,iBAAiB,EAAE,IAAI,CAAC,uBAAuB;QAC/C,YAAY,EAAE,IAAI,CAAC,YAAY;KAChC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,CAAC,CAAC,+BAA+B,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { acknowledgeContainerMutationBatch } from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n submitContainerRotation,\n submitRotationCarryingDescendants,\n} from \"../../containers/child/mutationSubmit\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { shouldRetrySyncWithFreshWriterProjection } from \"../syncFailures/syncFailureClassification\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\n\n/**\n * Repairs committed during one sync pass, keyed by the pass's own input object\n * (stable across all three attempts). The sync loop explicitly prepares each\n * attempt, so a counter local to one call would not bound the whole pass.\n */\nconst passRepairTotals = new WeakMap<SyncRemoteDocumentInput, number>();\n\n/**\n * Passes whose inline repairs the server refused for stranding a level above a\n * directly granted container. The write's flat rekey list cannot say which\n * descendants each repair must carry; a standalone rekey can, so the rest of\n * the pass commits every repair standalone before writing.\n */\nconst standaloneRepairPasses = new WeakSet<SyncRemoteDocumentInput>();\n\nexport function requiresStandaloneAncestorRepairs(\n sync: SyncRemoteDocumentInput,\n): boolean {\n return standaloneRepairPasses.has(sync);\n}\n\nexport function requireStandaloneAncestorRepairs(\n sync: SyncRemoteDocumentInput,\n): void {\n standaloneRepairPasses.add(sync);\n}\n\n/** A refusal the writer cannot clear by retrying, as opposed to 5xx/offline. */\nfunction isTerminalRepairStatus(status: number | null): boolean {\n return status === 401 || status === 402 || status === 403;\n}\n\n/**\n * One standalone repair. Prefers the status-bearing rekey: a permanent refusal\n * (403 once ancestor write access is revoked, 402) must leave a durable record,\n * while a 5xx or an offline blip must not, and plain `rekeyContainer` collapses\n * both to null. It is also the only way to learn which descendant rekeys this\n * repair must carry. An adapter without it still repairs; its refusals are just\n * reported as an ordinary abandon.\n */\nfunction submitStandaloneRepair(\n sync: SyncRemoteDocumentInput,\n plan: MaterializedContainerRekeyPlan[\"plan\"],\n writerProjection: MaterializedContainerRekeyPlan[\"writerProjection\"],\n) {\n const options = {\n expectedPaymentRequiredOrganizationId: plan.state.organizationId,\n };\n const { getContainerWriterProjection, rekeyContainerResult } = sync.apiClient;\n return submitRotationCarryingDescendants({\n carriedRekeys: getContainerWriterProjection && {\n planning: {\n apiClient: {\n getContainerWriterProjection: getContainerWriterProjection.bind(\n sync.apiClient,\n ),\n },\n author: sync.author,\n execSql: sync.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n sync.resolveProjectionUserKey,\n \"Document ancestor repair\",\n ),\n stillCurrent: sync.stillCurrent,\n targetSecretKey: sync.targetSecretKey,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n },\n rotated: async () => writerProjection,\n },\n stillCurrent: sync.stillCurrent,\n submit: (carried) => {\n const request = carried.length\n ? { ...plan.request, containerRekeys: [...carried] }\n : plan.request;\n return submitContainerRotation({\n plain: () =>\n sync.apiClient.rekeyContainer(plan.containerId, request, options),\n result: rekeyContainerResult\n ? () =>\n rekeyContainerResult.call(\n sync.apiClient,\n plan.containerId,\n request,\n { ...options, reportErrors: false },\n )\n : undefined,\n });\n },\n });\n}\n\nasync function abandonRefusedRepair(\n sync: SyncRemoteDocumentInput,\n containerId: string,\n result: Awaited<ReturnType<typeof submitStandaloneRepair>>[\"result\"],\n): Promise<never> {\n if (!result.ok && isTerminalRepairStatus(result.status)) {\n await sync.onTerminalSubmitFailure?.({\n code: \"document_ancestor_repair_refused\",\n message: `Ancestor repair refused for ${containerId}`,\n ok: false,\n report: () => undefined,\n status: result.status,\n });\n }\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n}\n\n/** A repair and everything it carried committed together. */\nfunction markRepaired(\n repairedIds: Set<string>,\n plan: { readonly containerId: string },\n carriedPlans: readonly { readonly plan: { readonly containerId: string } }[],\n): void {\n repairedIds.add(plan.containerId);\n for (const carried of carriedPlans) {\n repairedIds.add(carried.plan.containerId);\n }\n}\n\nasync function commitRepairPrefix(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n repairedIds: Set<string>;\n sync: SyncRemoteDocumentInput;\n}): Promise<number> {\n let committed = 0;\n for (const { plan, writerProjection } of input.plans) {\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n if (input.sync.isRemoteSyncBlocked?.(plan.state.organizationId)) {\n throw new DocumentAncestorRepairAbandonedError(\"blocked\");\n }\n if (input.repairedIds.has(plan.containerId)) {\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n const { carriedPlans, result } = await submitStandaloneRepair(\n input.sync,\n plan,\n writerProjection,\n );\n const response = result.ok ? result.data : null;\n // Deliberately not ContainerKekRepairRequiredError: that is classified as\n // retryable, so a handled refusal would re-sign the whole prefix before\n // failing again, and the retry never reaches onTerminalSubmitFailure\n // regardless, because this throws before submission.\n if (!response) {\n return abandonRefusedRepair(input.sync, plan.containerId, result);\n }\n // What a repair carried committed with it, so the pins advance together.\n const acknowledged = await acknowledgeContainerMutationBatch({\n execSql: input.sync.execSql,\n plans: [plan, ...carriedPlans.map((carried) => carried.plan)],\n responses: [response, ...(response.containerRekeys ?? [])],\n stillCurrent: input.sync.stillCurrent,\n });\n if (!acknowledged) {\n // A refused guarded transaction is usually a generation flip; surface it\n // as the shared cancellation so syncRemoteDocument returns null instead\n // of reporting a routine flip as a sync failure.\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n throw new Error(\"Document ancestor repair was superseded\");\n }\n markRepaired(input.repairedIds, plan, carriedPlans);\n committed += 1 + carriedPlans.length;\n // The rest of this prefix was signed before the carry. A plan for a carried\n // container extends a superseded head, and one below it pins an epoch that\n // was never minted. Stop here; the caller refetches and re-plans.\n if (carriedPlans.length > 0) return committed;\n }\n return committed;\n}\n\n/**\n * Large repairs commit a bounded prefix; the last batch stays atomic with content.\n * A tighter local resource budget may be used, but never above the protocol cap.\n */\nexport async function prepareAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n maxRepairs = MAX_CONTAINER_PATH_LENGTH,\n): Promise<{\n plans: readonly MaterializedContainerRekeyPlan[];\n projection: DocumentWriterProjectionResponse;\n}> {\n if (initialProjection.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n let projection = initialProjection;\n const repairedIds = new Set<string>();\n // `repairedIds` only breaks a loop within one preparation. An explicit sync\n // retry starts another preparation with a fresh set. Bound the\n // work by the deepest authorizing path the protocol allows, counted across\n // the whole pass rather than per call: no honest chain needs more repairs\n // than that, so re-entry cannot multiply the budget.\n for (;;) {\n const batch = await buildAutomaticContainerRekeys(sync, projection);\n const commitsStandalone =\n batch.hasMore ||\n (batch.plans.length > 0 && standaloneRepairPasses.has(sync));\n if (!commitsStandalone) return { plans: batch.plans, projection };\n // Standalone mutations require authentic document scope before any request.\n // Persist the verified heads here, unlike the inline path: a committed\n // repair is acknowledged against the latest durable pin, and a repaired\n // ancestor is always past epoch 1, so a device that has never pinned it\n // would reject its own acknowledgement after the server already committed\n // the rekey. The inline path needs no pin because the sync response\n // re-verifies and pins before anything is acknowledged.\n await assertDocumentWriterProjectionConsistent(projection, {\n ...projectionVerificationOptions(sync),\n persistVerificationCheckpoints: true,\n allowStaleContentKeyBundle: true,\n });\n // Charge what this prefix can still commit, then settle to what it did: it\n // stops early after a repair that carried something, and charging the plans\n // it never submitted would spend the budget on work that did not happen.\n const committedBefore = passRepairTotals.get(sync) ?? 0;\n if (\n committedBefore + batch.plans.length >\n Math.min(maxRepairs, MAX_CONTAINER_PATH_LENGTH)\n ) {\n throw new DocumentAncestorRepairAbandonedError(\"depth-budget\");\n }\n passRepairTotals.set(\n sync,\n committedBefore +\n (await commitRepairPrefix({ plans: batch.plans, repairedIds, sync })),\n );\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n // Always a write-bearing pass, so a terminal projection failure (a 403\n // after revocation mid-repair) must leave the durable record that the\n // queued writes are blocked. onReadOnlyProjectionFailure is documented\n // for passes without queued writes and would not apply here.\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n if (!fresh) {\n // refreshSyncAttemptWriterProjection returns null on a generation flip.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n // It has already called onSyncAbandoned by this point, and on a coded 404\n // ran the verified local teardown, so a bare Error would double-signal as\n // an abandon plus a sync-lane crash.\n throw new DocumentAncestorRepairAbandonedError(\"unrefreshable\");\n }\n // The scope check above guards the first round only; a refetched projection\n // is server-supplied too, and nothing in the refresh path proves it names\n // the document this repair is for.\n if (fresh.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n projection = fresh;\n }\n}\n\n/** An explicit preparation retry may commit repairs; plan retries never do. */\nexport async function prepareSyncAttemptContainerRekeys(\n sync: SyncRemoteDocumentInput,\n projection: DocumentWriterProjectionResponse,\n) {\n try {\n return await prepareAutomaticContainerRekeys(sync, projection);\n } catch (error) {\n if (\n !sync.apiClient.evictDocumentWriterProjection ||\n !shouldRetrySyncWithFreshWriterProjection(error)\n )\n throw error;\n }\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n return fresh ? prepareAutomaticContainerRekeys(sync, fresh) : null;\n}\n"]}
1
+ {"version":3,"file":"syncContainerRekeyPreparation.js","sourceRoot":"","sources":["syncContainerRekeyPreparation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,yDAAyD,CAAC;AAE5G,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAC9F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EACL,uBAAuB,EACvB,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,oCAAoC,E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;QAC3B,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;QACrD,eAAe,EAAE,IAAI,CAAC,eAAe;QACrC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,iBAAiB,EAAE,IAAI,CAAC,uBAAuB;QAC/C,YAAY,EAAE,IAAI,CAAC,YAAY;KAChC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,CAAC,CAAC,+BAA+B,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { acknowledgeContainerMutationBatch } from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n submitContainerRotation,\n submitRotationCarryingDescendants,\n} from \"../../containers/child/mutationSubmit\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { shouldRetrySyncWithFreshWriterProjection } from \"../syncFailures/syncFailureClassification\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\n\n/**\n * Repairs committed during one sync pass, keyed by the pass object that one\n * `syncRemoteDocument` call builds and hands to all three attempts. The sync\n * loop explicitly prepares each attempt, so a counter local to one call would\n * not bound the whole pass.\n */\nconst passRepairTotals = new WeakMap<RemoteDocumentSyncPass, number>();\n\n/**\n * Passes whose inline repairs the server refused for stranding a level above a\n * directly granted container. The write's flat rekey list cannot say which\n * descendants each repair must carry; a standalone rekey can, so the rest of\n * the pass commits every repair standalone before writing.\n */\nconst standaloneRepairPasses = new WeakSet<RemoteDocumentSyncPass>();\n\nexport function requiresStandaloneAncestorRepairs(\n sync: RemoteDocumentSyncPass,\n): boolean {\n return standaloneRepairPasses.has(sync);\n}\n\nexport function requireStandaloneAncestorRepairs(\n sync: RemoteDocumentSyncPass,\n): void {\n standaloneRepairPasses.add(sync);\n}\n\n/** A refusal the writer cannot clear by retrying, as opposed to 5xx/offline. */\nfunction isTerminalRepairStatus(status: number | null): boolean {\n return status === 401 || status === 402 || status === 403;\n}\n\n/**\n * One standalone repair. Prefers the status-bearing rekey: a permanent refusal\n * (403 once ancestor write access is revoked, 402) must leave a durable record,\n * while a 5xx or an offline blip must not, and plain `rekeyContainer` collapses\n * both to null. It is also the only way to learn which descendant rekeys this\n * repair must carry. An adapter without it still repairs; its refusals are just\n * reported as an ordinary abandon.\n */\nfunction submitStandaloneRepair(\n sync: RemoteDocumentSyncPass,\n plan: MaterializedContainerRekeyPlan[\"plan\"],\n writerProjection: MaterializedContainerRekeyPlan[\"writerProjection\"],\n) {\n const options = {\n expectedPaymentRequiredOrganizationId: plan.state.organizationId,\n };\n const { getContainerWriterProjection, rekeyContainerResult } = sync.apiClient;\n return submitRotationCarryingDescendants({\n carriedRekeys: getContainerWriterProjection && {\n planning: {\n apiClient: {\n getContainerWriterProjection: getContainerWriterProjection.bind(\n sync.apiClient,\n ),\n },\n author: sync.author,\n execSql: sync.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n sync.resolveProjectionUserKey,\n \"Document ancestor repair\",\n ),\n stillCurrent: sync.stillCurrent,\n targetSecretKey: sync.targetSecretKey,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n },\n rotated: async () => writerProjection,\n },\n stillCurrent: sync.stillCurrent,\n submit: (carried) => {\n const request = carried.length\n ? { ...plan.request, containerRekeys: [...carried] }\n : plan.request;\n return submitContainerRotation({\n plain: () =>\n sync.apiClient.rekeyContainer(plan.containerId, request, options),\n result: rekeyContainerResult\n ? () =>\n rekeyContainerResult.call(\n sync.apiClient,\n plan.containerId,\n request,\n { ...options, reportErrors: false },\n )\n : undefined,\n });\n },\n });\n}\n\nasync function abandonRefusedRepair(\n sync: RemoteDocumentSyncPass,\n containerId: string,\n result: Awaited<ReturnType<typeof submitStandaloneRepair>>[\"result\"],\n): Promise<never> {\n if (!result.ok && isTerminalRepairStatus(result.status)) {\n await sync.onTerminalSubmitFailure?.({\n code: \"document_ancestor_repair_refused\",\n message: `Ancestor repair refused for ${containerId}`,\n ok: false,\n report: () => undefined,\n status: result.status,\n });\n }\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n}\n\n/** A repair and everything it carried committed together. */\nfunction markRepaired(\n repairedIds: Set<string>,\n plan: { readonly containerId: string },\n carriedPlans: readonly { readonly plan: { readonly containerId: string } }[],\n): void {\n repairedIds.add(plan.containerId);\n for (const carried of carriedPlans) {\n repairedIds.add(carried.plan.containerId);\n }\n}\n\nasync function commitRepairPrefix(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n repairedIds: Set<string>;\n sync: RemoteDocumentSyncPass;\n}): Promise<number> {\n let committed = 0;\n for (const { plan, writerProjection } of input.plans) {\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n if (input.sync.isRemoteSyncBlocked?.(plan.state.organizationId)) {\n throw new DocumentAncestorRepairAbandonedError(\"blocked\");\n }\n if (input.repairedIds.has(plan.containerId)) {\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n const { carriedPlans, result } = await submitStandaloneRepair(\n input.sync,\n plan,\n writerProjection,\n );\n const response = result.ok ? result.data : null;\n // Deliberately not ContainerKekRepairRequiredError: that is classified as\n // retryable, so a handled refusal would re-sign the whole prefix before\n // failing again, and the retry never reaches onTerminalSubmitFailure\n // regardless, because this throws before submission.\n if (!response) {\n return abandonRefusedRepair(input.sync, plan.containerId, result);\n }\n // What a repair carried committed with it, so the pins advance together.\n const acknowledged = await acknowledgeContainerMutationBatch({\n execSql: input.sync.execSql,\n plans: [plan, ...carriedPlans.map((carried) => carried.plan)],\n responses: [response, ...(response.containerRekeys ?? [])],\n stillCurrent: input.sync.stillCurrent,\n });\n if (!acknowledged) {\n // A refused guarded transaction is usually a generation flip; surface it\n // as the shared cancellation so syncRemoteDocument returns null instead\n // of reporting a routine flip as a sync failure.\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n throw new Error(\"Document ancestor repair was superseded\");\n }\n markRepaired(input.repairedIds, plan, carriedPlans);\n committed += 1 + carriedPlans.length;\n // The rest of this prefix was signed before the carry. A plan for a carried\n // container extends a superseded head, and one below it pins an epoch that\n // was never minted. Stop here; the caller refetches and re-plans.\n if (carriedPlans.length > 0) return committed;\n }\n return committed;\n}\n\n/**\n * Large repairs commit a bounded prefix; the last batch stays atomic with content.\n * A tighter local resource budget may be used, but never above the protocol cap.\n */\nexport async function prepareAutomaticContainerRekeys(\n sync: RemoteDocumentSyncPass,\n initialProjection: DocumentWriterProjectionResponse,\n maxRepairs = MAX_CONTAINER_PATH_LENGTH,\n): Promise<{\n plans: readonly MaterializedContainerRekeyPlan[];\n projection: DocumentWriterProjectionResponse;\n}> {\n if (initialProjection.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n let projection = initialProjection;\n const repairedIds = new Set<string>();\n // `repairedIds` only breaks a loop within one preparation. An explicit sync\n // retry starts another preparation with a fresh set. Bound the\n // work by the deepest authorizing path the protocol allows, counted across\n // the whole pass rather than per call: no honest chain needs more repairs\n // than that, so re-entry cannot multiply the budget.\n for (;;) {\n const batch = await buildAutomaticContainerRekeys(sync, projection);\n const commitsStandalone =\n batch.hasMore ||\n (batch.plans.length > 0 && standaloneRepairPasses.has(sync));\n if (!commitsStandalone) return { plans: batch.plans, projection };\n // Standalone mutations require authentic document scope before any request.\n // Persist the verified heads here, unlike the inline path: a committed\n // repair is acknowledged against the latest durable pin, and a repaired\n // ancestor is always past epoch 1, so a device that has never pinned it\n // would reject its own acknowledgement after the server already committed\n // the rekey. The inline path needs no pin because the sync response\n // re-verifies and pins before anything is acknowledged.\n await assertDocumentWriterProjectionConsistent(projection, {\n ...projectionVerificationOptions(sync),\n persistVerificationCheckpoints: true,\n allowStaleContentKeyBundle: true,\n });\n // Charge what this prefix can still commit, then settle to what it did: it\n // stops early after a repair that carried something, and charging the plans\n // it never submitted would spend the budget on work that did not happen.\n const committedBefore = passRepairTotals.get(sync) ?? 0;\n if (\n committedBefore + batch.plans.length >\n Math.min(maxRepairs, MAX_CONTAINER_PATH_LENGTH)\n ) {\n throw new DocumentAncestorRepairAbandonedError(\"depth-budget\");\n }\n passRepairTotals.set(\n sync,\n committedBefore +\n (await commitRepairPrefix({ plans: batch.plans, repairedIds, sync })),\n );\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n // Always a write-bearing pass, so a terminal projection failure (a 403\n // after revocation mid-repair) must leave the durable record that the\n // queued writes are blocked. onReadOnlyProjectionFailure is documented\n // for passes without queued writes and would not apply here.\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n if (!fresh) {\n // refreshSyncAttemptWriterProjection returns null on a generation flip.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n // It has already called onSyncAbandoned by this point, and on a coded 404\n // ran the verified local teardown, so a bare Error would double-signal as\n // an abandon plus a sync-lane crash.\n throw new DocumentAncestorRepairAbandonedError(\"unrefreshable\");\n }\n // The scope check above guards the first round only; a refetched projection\n // is server-supplied too, and nothing in the refresh path proves it names\n // the document this repair is for.\n if (fresh.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n projection = fresh;\n }\n}\n\n/** An explicit preparation retry may commit repairs; plan retries never do. */\nexport async function prepareSyncAttemptContainerRekeys(\n sync: RemoteDocumentSyncPass,\n projection: DocumentWriterProjectionResponse,\n) {\n try {\n return await prepareAutomaticContainerRekeys(sync, projection);\n } catch (error) {\n if (\n !sync.apiClient.evictDocumentWriterProjection ||\n !shouldRetrySyncWithFreshWriterProjection(error)\n )\n throw error;\n }\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n return fresh ? prepareAutomaticContainerRekeys(sync, fresh) : null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"syncContainerRekeys.js","sourceRoot":"","sources":["syncContainerRekeys.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AAGxH,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,iCAAiC,EAAE,MAAM,8BAA8B,CAAC;AACjF,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAE/D,6EAA6E;AAC7E,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAUjD;IACC,2EAA2E;IAC3E,4EAA4E;IAC5E,yEAAyE;IACzE,8EAA8E;IAC9E,8EAA8E;IAC9E,6EAA6E;IAC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"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { DocumentSyncPreparationRequiredError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildMaterializedDocumentSyncPlan } from \"../syncPlan/syncPlanMaterial\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\nimport { requiresStandaloneAncestorRepairs } from \"./syncContainerRekeyPreparation\";\nimport { applyDocumentSyncContainerRekeys } from \"./syncContainerRekeyProjection\";\nimport { computeInlineRekeyCommitId } from \"./syncRekeyCommit\";\n\n/** Plan only: standalone server repairs belong to the outer sync attempt. */\nexport async function buildRemoteDocumentSyncPlan(input: {\n preparedRekeys?: readonly MaterializedContainerRekeyPlan[] | undefined;\n /** The version the request advertises; defaults to the sync's live one. */\n localVersionVector?: string | null | undefined;\n minLsn?: string | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullCursor?: string | undefined;\n projection: DocumentWriterProjectionResponse;\n regenerateQueuedCheckpoints: boolean;\n sync: SyncRemoteDocumentInput;\n}) {\n // Repairing this document's own container moves its key target hash, which\n // marks the content-key bundle stale. Only a pass that can build a rotation\n // snapshot is able to heal that; rotation settlement deliberately cannot\n // (`syncRequest.ts` omits the builder for `allowRecoveryBaseline: false`), so\n // repairing there would trade a classified \"ancestor repair required\" failure\n // for an unhealable bundle — after a standalone prefix may already have been\n // committed. Such a pass is left to fail as it did before automatic repair.\n const canHealStaleBundle = input.sync.buildRotationSnapshot !== undefined;\n let automaticPlans = input.preparedRekeys;\n if (\n input.pendingUpdates.length &&\n !input.sync.buildContainerRekeys &&\n canHealStaleBundle &&\n automaticPlans === undefined\n ) {\n const batch = await buildAutomaticContainerRekeys(\n input.sync,\n input.projection,\n );\n if (\n batch.hasMore ||\n (batch.plans.length > 0 && requiresStandaloneAncestorRepairs(input.sync))\n ) {\n throw new DocumentSyncPreparationRequiredError();\n }\n automaticPlans = batch.plans;\n }\n const rekeyPlans =\n input.pendingUpdates.length && input.sync.buildContainerRekeys\n ? await input.sync.buildContainerRekeys(input.projection, {\n persistVerificationCheckpoints: false,\n })\n : automaticPlans;\n const writerProjection = rekeyPlans?.length\n ? await applyDocumentSyncContainerRekeys({\n plans: rekeyPlans,\n writerProjection: input.projection,\n })\n : input.projection;\n let inlineRekeyCommitId: string | undefined;\n if (rekeyPlans?.length) {\n const headPendingUpdate = input.pendingUpdates[0];\n if (!headPendingUpdate) {\n throw new Error(\"Document inline rekey pending queue is empty\");\n }\n inlineRekeyCommitId = await computeInlineRekeyCommitId({\n headPendingUpdateId: headPendingUpdate.id,\n projection: input.projection,\n });\n }\n return buildMaterializedDocumentSyncPlan({\n author: input.sync.author,\n buildRotationSnapshot: input.sync.buildRotationSnapshot,\n containerRekeys: rekeyPlans?.map(({ plan }) => plan.request),\n execSql: input.sync.execSql,\n historyMode: input.sync.historyMode,\n inlineRekeyCommitId,\n localVersionVector:\n input.localVersionVector === undefined\n ? input.sync.localVersionVector\n : input.localVersionVector,\n minLsn: input.minLsn,\n onSyncTrace: input.sync.onSyncTrace,\n pendingUpdates: input.pendingUpdates,\n persistVerificationCheckpoints: rekeyPlans?.length ? false : undefined,\n pullCursor: input.pullCursor,\n regenerateQueuedCheckpoints: input.regenerateQueuedCheckpoints,\n signedAt: input.sync.signedAt,\n targetSecretKey: input.sync.targetSecretKey,\n writerProjection,\n ...projectionVerificationOptions(input.sync),\n });\n}\n"]}
1
+ {"version":3,"file":"syncContainerRekeys.js","sourceRoot":"","sources":["syncContainerRekeys.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AAGxH,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,iCAAiC,EAAE,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QACpC,8BAA8B,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;QACtE,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;QAC9D,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ;QAC7B,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe;QAC3C,gBAAgB;QAChB,GAAG,6BAA6B,CAAC,KAAK,CAAC,IAAI,CAAC;KAC7C,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { DocumentSyncPreparationRequiredError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildMaterializedDocumentSyncPlan } from \"../syncPlan/syncPlanMaterial\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\nimport { requiresStandaloneAncestorRepairs } from \"./syncContainerRekeyPreparation\";\nimport { applyDocumentSyncContainerRekeys } from \"./syncContainerRekeyProjection\";\nimport { computeInlineRekeyCommitId } from \"./syncRekeyCommit\";\n\n/** Plan only: standalone server repairs belong to the outer sync attempt. */\nexport async function buildRemoteDocumentSyncPlan(input: {\n preparedRekeys?: readonly MaterializedContainerRekeyPlan[] | undefined;\n /** The version the request advertises; defaults to the sync's live one. */\n localVersionVector?: string | null | undefined;\n minLsn?: string | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullCursor?: string | undefined;\n projection: DocumentWriterProjectionResponse;\n regenerateQueuedCheckpoints: boolean;\n sync: RemoteDocumentSyncPass;\n}) {\n // Repairing this document's own container moves its key target hash, which\n // marks the content-key bundle stale. Only a pass that can build a rotation\n // snapshot is able to heal that; rotation settlement deliberately cannot\n // (`syncRequest.ts` omits the builder for `allowRecoveryBaseline: false`), so\n // repairing there would trade a classified \"ancestor repair required\" failure\n // for an unhealable bundle — after a standalone prefix may already have been\n // committed. Such a pass is left to fail as it did before automatic repair.\n const canHealStaleBundle = input.sync.buildRotationSnapshot !== undefined;\n let automaticPlans = input.preparedRekeys;\n if (\n input.pendingUpdates.length &&\n !input.sync.buildContainerRekeys &&\n canHealStaleBundle &&\n automaticPlans === undefined\n ) {\n const batch = await buildAutomaticContainerRekeys(\n input.sync,\n input.projection,\n );\n if (\n batch.hasMore ||\n (batch.plans.length > 0 && requiresStandaloneAncestorRepairs(input.sync))\n ) {\n throw new DocumentSyncPreparationRequiredError();\n }\n automaticPlans = batch.plans;\n }\n const rekeyPlans =\n input.pendingUpdates.length && input.sync.buildContainerRekeys\n ? await input.sync.buildContainerRekeys(input.projection, {\n persistVerificationCheckpoints: false,\n })\n : automaticPlans;\n const writerProjection = rekeyPlans?.length\n ? await applyDocumentSyncContainerRekeys({\n plans: rekeyPlans,\n writerProjection: input.projection,\n })\n : input.projection;\n let inlineRekeyCommitId: string | undefined;\n if (rekeyPlans?.length) {\n const headPendingUpdate = input.pendingUpdates[0];\n if (!headPendingUpdate) {\n throw new Error(\"Document inline rekey pending queue is empty\");\n }\n inlineRekeyCommitId = await computeInlineRekeyCommitId({\n headPendingUpdateId: headPendingUpdate.id,\n projection: input.projection,\n });\n }\n return buildMaterializedDocumentSyncPlan({\n author: input.sync.author,\n buildRotationSnapshot: input.sync.buildRotationSnapshot,\n containerRekeys: rekeyPlans?.map(({ plan }) => plan.request),\n execSql: input.sync.execSql,\n historyMode: input.sync.historyMode,\n inlineRekeyCommitId,\n localVersionVector:\n input.localVersionVector === undefined\n ? input.sync.localVersionVector\n : input.localVersionVector,\n minLsn: input.minLsn,\n onSyncTrace: input.sync.onSyncTrace,\n pendingUpdates: input.pendingUpdates,\n persistVerificationCheckpoints: rekeyPlans?.length ? false : undefined,\n pullCursor: input.pullCursor,\n regenerateQueuedCheckpoints: input.regenerateQueuedCheckpoints,\n signedAt: input.sync.signedAt,\n targetSecretKey: input.sync.targetSecretKey,\n writerProjection,\n ...projectionVerificationOptions(input.sync),\n });\n}\n"]}
@@ -1,9 +1,9 @@
1
1
  import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
- import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
3
2
  import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
4
3
  import { KeyingCheckpointRepository } from "../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
5
4
  import { assertCurrentMatchesVerifiedPolicy } from "../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js";
6
5
  import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../data/principals/organizationAuthorityDescriptor.js";
6
+ import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
7
7
  /** One directory view with bounded, authenticated current artifacts for its groups. */
8
8
  export async function loadCurrentOrganizationAuthority(input) {
9
9
  if (input.organizationReference)
@@ -1 +1 @@
1
- {"version":3,"file":"currentOrganizationAuthority.js","sourceRoot":"","sources":["currentOrganizationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,uEAAuE,CAAC;AAC3H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAgB/D,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU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AAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,OAAO;QAChC,MAAM,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,SAAS,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC;QACzE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,wDAAwD,CACzD,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type {\n PrincipalPolicyCurrentResolver as CurrentPolicyResolver,\n ResolvedPrincipalPolicyCurrent,\n} from \"../principals/runtimePolicyRecovery\";\n\ninterface CurrentOrganizationAuthorityInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly organizationReference?: ReferencedPrincipalHead | null | undefined;\n readonly resolveCurrentPolicy: CurrentPolicyResolver;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/** One directory view with bounded, authenticated current artifacts for its groups. */\nexport async function loadCurrentOrganizationAuthority(\n input: CurrentOrganizationAuthorityInput,\n) {\n if (input.organizationReference)\n assertReferenceScope(\n input.organizationReference,\n \"organization\",\n input.organizationId,\n );\n const recoveryBatch = input.recoveryBatch ?? {};\n const resolve = (reference?: ReferencedPrincipalHead | null) =>\n input.resolveCurrentPolicy({\n organizationId: input.organizationId,\n reference: reference ?? undefined,\n preferLocalCurrent: true,\n recoveryBatch,\n stillCurrent: input.stillCurrent,\n });\n const directory = await resolve(input.organizationReference);\n await assertExactCurrent(\n directory,\n input.organizationReference ?? directory.policy.state,\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.current.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization current policy payload is outside its scope\",\n );\n const adminHead = requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n );\n const admins = await resolve(adminHead);\n await assertExactCurrent(admins, adminHead);\n assertDirectoryDependency(admins, directory);\n const stillCurrent = () =>\n input.stillCurrent() && directory.stillCurrent() && admins.stillCurrent();\n const validate = async (value: ResolvedPrincipalPolicyCurrent) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: [],\n policies: [...value.dependencies, value.policy],\n stillCurrent: () => stillCurrent() && value.stillCurrent(),\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && value.stillCurrent(),\n );\n };\n await validate(admins);\n return {\n admins,\n descriptor,\n directory,\n stillCurrent,\n async readGroup(groupId: string, reference?: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const head = requireOrganizationGroupHead(descriptor, groupId);\n const selected = reference ?? head;\n assertReferenceScope(selected, \"group\", groupId);\n const result =\n groupId === descriptor.adminGroupId &&\n principalHeadMatchesReference(admins.policy.state, selected)\n ? admins\n : await resolve(selected);\n await assertExactCurrent(result, head);\n assertDirectoryDependency(result, directory);\n if (groupId !== descriptor.adminGroupId)\n assertAdminsDependency(result, adminHead);\n await validate(result);\n return result;\n },\n };\n}\n\nfunction assertReferenceScope(\n reference: ReferencedPrincipalHead,\n principalType: ReferencedPrincipalHead[\"principalType\"],\n principalId: string,\n) {\n if (\n reference.principalType !== principalType ||\n reference.principalId !== principalId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n}\n\nasync function assertExactCurrent(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n assertProjectionVerificationCurrent(value.stillCurrent);\n await assertCurrentMatchesVerifiedPolicy(value);\n if (!principalHeadMatchesReference(value.policy.state, expected))\n throw new ProjectionDependencyUnavailableError(\n \"Current policy changed from the selected organization directory\",\n );\n assertProjectionVerificationCurrent(value.stillCurrent);\n}\n\nfunction assertDirectoryDependency(\n value: ResolvedPrincipalPolicyCurrent,\n directory: ResolvedPrincipalPolicyCurrent,\n) {\n const dependency = value.dependencies.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === directory.policy.principalId,\n );\n if (\n !dependency ||\n !principalHeadMatchesReference(dependency.state, directory.policy.state)\n )\n throw new ProjectionDependencyUnavailableError(\n \"Current policy belongs to a changed organization directory\",\n );\n}\n\nfunction assertAdminsDependency(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n const authority = value.dependencies.find(\n (policy) =>\n policy.principalType === \"group\" &&\n policy.principalId === expected.principalId,\n );\n if (!authority || !principalHeadMatchesReference(authority.state, expected))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Current group policy omits its exact Admins dependency\",\n );\n}\n"]}
1
+ {"version":3,"file":"currentOrganizationAuthority.js","sourceRoot":"","sources":["currentOrganizationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,uEAAuE,CAAC;AAC3H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CA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,CAC7B,KAAqC,EACrC,QAAiC;IAEjC,MAAM,SAAS,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACvC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,OAAO;QAChC,MAAM,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,SAAS,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC;QACzE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,wDAAwD,CACzD,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type {\n PrincipalPolicyCurrentResolver as CurrentPolicyResolver,\n ResolvedPrincipalPolicyCurrent,\n} from \"../principals/runtimePolicyRecovery\";\n\ninterface CurrentOrganizationAuthorityInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly organizationReference?: ReferencedPrincipalHead | null | undefined;\n readonly resolveCurrentPolicy: CurrentPolicyResolver;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/** One directory view with bounded, authenticated current artifacts for its groups. */\nexport async function loadCurrentOrganizationAuthority(\n input: CurrentOrganizationAuthorityInput,\n) {\n if (input.organizationReference)\n assertReferenceScope(\n input.organizationReference,\n \"organization\",\n input.organizationId,\n );\n const recoveryBatch = input.recoveryBatch ?? {};\n const resolve = (reference?: ReferencedPrincipalHead | null) =>\n input.resolveCurrentPolicy({\n organizationId: input.organizationId,\n reference: reference ?? undefined,\n preferLocalCurrent: true,\n recoveryBatch,\n stillCurrent: input.stillCurrent,\n });\n const directory = await resolve(input.organizationReference);\n await assertExactCurrent(\n directory,\n input.organizationReference ?? directory.policy.state,\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.current.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization current policy payload is outside its scope\",\n );\n const adminHead = requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n );\n const admins = await resolve(adminHead);\n await assertExactCurrent(admins, adminHead);\n assertDirectoryDependency(admins, directory);\n const stillCurrent = () =>\n input.stillCurrent() && directory.stillCurrent() && admins.stillCurrent();\n const validate = async (value: ResolvedPrincipalPolicyCurrent) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: [],\n policies: [...value.dependencies, value.policy],\n stillCurrent: () => stillCurrent() && value.stillCurrent(),\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && value.stillCurrent(),\n );\n };\n await validate(admins);\n return {\n admins,\n descriptor,\n directory,\n stillCurrent,\n async readGroup(groupId: string, reference?: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const head = requireOrganizationGroupHead(descriptor, groupId);\n const selected = reference ?? head;\n assertReferenceScope(selected, \"group\", groupId);\n const result =\n groupId === descriptor.adminGroupId &&\n principalHeadMatchesReference(admins.policy.state, selected)\n ? admins\n : await resolve(selected);\n await assertExactCurrent(result, head);\n assertDirectoryDependency(result, directory);\n if (groupId !== descriptor.adminGroupId)\n assertAdminsDependency(result, adminHead);\n await validate(result);\n return result;\n },\n };\n}\n\nfunction assertReferenceScope(\n reference: ReferencedPrincipalHead,\n principalType: ReferencedPrincipalHead[\"principalType\"],\n principalId: string,\n) {\n if (\n reference.principalType !== principalType ||\n reference.principalId !== principalId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n}\n\nasync function assertExactCurrent(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n assertProjectionVerificationCurrent(value.stillCurrent);\n await assertCurrentMatchesVerifiedPolicy(value);\n if (!principalHeadMatchesReference(value.policy.state, expected))\n throw new ProjectionDependencyUnavailableError(\n \"Current policy changed from the selected organization directory\",\n );\n assertProjectionVerificationCurrent(value.stillCurrent);\n}\n\nfunction assertDirectoryDependency(\n value: ResolvedPrincipalPolicyCurrent,\n directory: ResolvedPrincipalPolicyCurrent,\n) {\n const dependency = value.dependencies.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === directory.policy.principalId,\n );\n if (\n !dependency ||\n !principalHeadMatchesReference(dependency.state, directory.policy.state)\n )\n throw new ProjectionDependencyUnavailableError(\n \"Current policy belongs to a changed organization directory\",\n );\n}\n\nfunction assertAdminsDependency(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n const authority = value.dependencies.find(\n (policy) =>\n policy.principalType === \"group\" &&\n policy.principalId === expected.principalId,\n );\n if (!authority || !principalHeadMatchesReference(authority.state, expected))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Current group policy omits its exact Admins dependency\",\n );\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
- import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
3
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
4
3
  import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
4
+ import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
5
5
  import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
6
6
  import { assertMetadataRootBinding } from "./groupMetadataRootBinding.js";
7
7
  /** Authenticate metadata-root grants with current policies and only its cited predecessors. */
@@ -1 +1 @@
1
- {"version":3,"file":"currentGroupMetadataAuthority.js","sourceRoot":"","sources":["currentGroupMetadataAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAEvE,+FAA+F;AAC/F,MAAM,UAAU,2CAA2C,CACzD,KAGC;IAED,OAAO,KAAK,EACV,KAAmC,EACnC,qBAA+C,EAChC,EAAE;QACjB,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC;YACvD,GAAG,KAAK;YACR,qBAAqB;SACtB,CAAC,CAAC;QACH,MAAM,mDAAmD,CAAC;YACxD,SAAS;YACT,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC,KAAK,EAAE,qBAAqB,CAAC,CAAC;IACnC,CAAC,CAAC;AACJ,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,mDAAmD,CAAC,KAMnE;IACC,OAAO,KAAK,EACV,KAAmC,EACnC,qBAA+C,EAChC,EAAE;QACjB,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;QAC5B,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE,IA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,EAAE,CACxE,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { assertMetadataRootBinding } from \"./groupMetadataRootBinding\";\n\n/** Authenticate metadata-root grants with current policies and only its cited predecessors. */\nexport function createCurrentGroupMetadataContainerVerifier(\n input: Omit<\n Parameters<typeof loadCurrentOrganizationAuthority>[0],\n \"organizationReference\"\n >,\n) {\n return async (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const authority = await loadCurrentOrganizationAuthority({\n ...input,\n organizationReference,\n });\n await createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n })(state, organizationReference);\n };\n}\n\n/** Reuse one mutation's verified authority without broadening its lease or scope. */\nexport function createSelectedCurrentGroupMetadataContainerVerifier(input: {\n readonly authority: Awaited<\n ReturnType<typeof loadCurrentOrganizationAuthority>\n >;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n}) {\n return async (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead,\n ): Promise<void> => {\n const { authority } = input;\n const stillCurrent = () => input.stillCurrent() && authority.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n if (organizationReference) {\n if (\n organizationReference.principalType !== \"organization\" ||\n organizationReference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n if (\n !principalHeadMatchesReference(\n authority.directory.policy.state,\n organizationReference,\n )\n )\n throw new ProjectionDependencyUnavailableError(\n \"Metadata root belongs to a changed organization directory\",\n );\n }\n const { adminGroupId, memberGroupId } = authority.descriptor;\n const citation = (groupId: string) =>\n state.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === groupId,\n );\n const admins = await authority.readGroup(\n adminGroupId,\n citation(adminGroupId),\n );\n const members = await authority.readGroup(\n memberGroupId,\n citation(memberGroupId),\n );\n assertMetadataRootBinding({\n organizationId: input.organizationId,\n authority: {\n descriptor: authority.descriptor,\n adminGroupId,\n memberGroupId,\n adminPolicy: admins.policy,\n },\n members,\n state,\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && admins.stillCurrent() && members.stillCurrent(),\n );\n };\n}\n"]}
1
+ {"version":3,"file":"currentGroupMetadataAuthority.js","sourceRoot":"","sources":["currentGroupMetadataAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAClG,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAEvE,+FAA+F;AAC/F,MAAM,UAAU,2CAA2C,CACzD,KAGC;IAED,OAAO,KAAK,EACV,KAAmC,EACnC,qBAA+C,EAChC,EAAE;QACjB,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC;YACvD,GAAG,KAAK;YACR,qBAAqB;SACtB,CAAC,CAAC;QACH,MAAM,mDAAmD,CAAC;YACxD,SAAS;YACT,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,YA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C,CACxB,CAAC;QACF,yBAAyB,CAAC;YACxB,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,SAAS,EAAE;gBACT,UAAU,EAAE,SAAS,CAAC,UAAU;gBAChC,YAAY;gBACZ,aAAa;gBACb,WAAW,EAAE,MAAM,CAAC,MAAM;aAC3B;YACD,OAAO;YACP,KAAK;SACN,CAAC,CAAC;QACH,mCAAmC,CACjC,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,MAAM,CAAC,YAAY,EAAE,IAAI,OAAO,CAAC,YAAY,EAAE,CACxE,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { assertMetadataRootBinding } from \"./groupMetadataRootBinding\";\n\n/** Authenticate metadata-root grants with current policies and only its cited predecessors. */\nexport function createCurrentGroupMetadataContainerVerifier(\n input: Omit<\n Parameters<typeof loadCurrentOrganizationAuthority>[0],\n \"organizationReference\"\n >,\n) {\n return async (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const authority = await loadCurrentOrganizationAuthority({\n ...input,\n organizationReference,\n });\n await createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n })(state, organizationReference);\n };\n}\n\n/** Reuse one mutation's verified authority without broadening its lease or scope. */\nexport function createSelectedCurrentGroupMetadataContainerVerifier(input: {\n readonly authority: Awaited<\n ReturnType<typeof loadCurrentOrganizationAuthority>\n >;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n}) {\n return async (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead,\n ): Promise<void> => {\n const { authority } = input;\n const stillCurrent = () => input.stillCurrent() && authority.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n if (organizationReference) {\n if (\n organizationReference.principalType !== \"organization\" ||\n organizationReference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n if (\n !principalHeadMatchesReference(\n authority.directory.policy.state,\n organizationReference,\n )\n )\n throw new ProjectionDependencyUnavailableError(\n \"Metadata root belongs to a changed organization directory\",\n );\n }\n const { adminGroupId, memberGroupId } = authority.descriptor;\n const citation = (groupId: string) =>\n state.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === groupId,\n );\n const admins = await authority.readGroup(\n adminGroupId,\n citation(adminGroupId),\n );\n const members = await authority.readGroup(\n memberGroupId,\n citation(memberGroupId),\n );\n assertMetadataRootBinding({\n organizationId: input.organizationId,\n authority: {\n descriptor: authority.descriptor,\n adminGroupId,\n memberGroupId,\n adminPolicy: admins.policy,\n },\n members,\n state,\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && admins.stillCurrent() && members.stillCurrent(),\n );\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
1
  import { createProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/userKeyResolver.js";
2
+ import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
3
3
  import { createCurrentGroupMetadataContainerVerifier } from "./currentGroupMetadataAuthority.js";
4
4
  import { createGroupMetadataAccess, } from "./groupMetadataAccess.js";
5
5
  export function createRuntimeGroupMetadataAccess(runtime, organizationId, stillCurrent, verifyMetadataContainer, currentRecovery) {
@@ -1 +1 @@
1
- {"version":3,"file":"groupMetadataRuntime.js","sour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CAAC;QACJ,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,cAAc;QACd,wBAAwB,EAAE,+BAA+B,CAAC,OAAO,CAAC;QAClE,eAAe;QACf,YAAY;QACZ,+BAA+B,EAAE,MAAM;KACxC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,sBAAsB,CAC7B,OAAmD;IAEnD,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { EncapsulationKeyPair } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { PrincipalPolicyService } from \"../../principals/principalPolicyService\";\nimport type { PrincipalPolicyCurrentResolver } from \"../../principals/runtimePolicyRecovery\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\nimport {\n createGroupMetadataAccess,\n type GroupMetadataAccessInput,\n} from \"./groupMetadataAccess\";\n\ninterface GroupMetadataRuntime {\n readonly apiClient: GroupMetadataAccessInput[\"apiClient\"] &\n PrincipalPolicyReadApi;\n readonly crypto: {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n };\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: {\n readonly log: (message: string) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n };\n}\n\nexport function createRuntimeGroupMetadataAccess(\n runtime: GroupMetadataRuntime,\n organizationId: string,\n stillCurrent?: () => boolean,\n verifyMetadataContainer?: GroupMetadataAccessInput[\"verifyMetadataContainer\"],\n currentRecovery?: {\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver | undefined;\n readonly recoveryBatch: object;\n },\n) {\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!targetSecretKey) throw new Error(\"Group metadata identity is locked\");\n // The signed metadata projection selects exact citations. Reuse matching\n // private evidence with its dependencies and pins before bounded online reads.\n const warmer = runtime.principalPolicies.createWarmer({\n preferLocalCurrent: true,\n });\n const resolveCurrentPolicy =\n currentRecovery?.resolveCurrentPolicy ??\n runtime.principalPolicies.createCurrentPolicyResolver();\n const authorityInput = {\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: stillCurrent ?? (() => true),\n };\n return createGroupMetadataAccess({\n verifyMetadataContainer:\n verifyMetadataContainer ??\n createCurrentGroupMetadataContainerVerifier({\n ...authorityInput,\n resolveCurrentPolicy: requireCurrentResolver(resolveCurrentPolicy),\n recoveryBatch: currentRecovery?.recoveryBatch,\n }),\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: warmer,\n });\n}\n\nfunction requireCurrentResolver(\n resolve: PrincipalPolicyCurrentResolver | undefined,\n) {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n return resolve;\n}\n"]}
1
+ {"version":3,"file":"groupMetadataRuntime.js","sourceRoot":"","sources":["groupMetadataRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAC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cAAc;QACd,wBAAwB,EAAE,+BAA+B,CAAC,OAAO,CAAC;QAClE,eAAe;QACf,YAAY;QACZ,+BAA+B,EAAE,MAAM;KACxC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,sBAAsB,CAC7B,OAAmD;IAEnD,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { EncapsulationKeyPair } from \"@tearleads/crypto\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { PrincipalPolicyService } from \"../../principals/principalPolicyService\";\nimport type { PrincipalPolicyCurrentResolver } from \"../../principals/runtimePolicyRecovery\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\nimport {\n createGroupMetadataAccess,\n type GroupMetadataAccessInput,\n} from \"./groupMetadataAccess\";\n\ninterface GroupMetadataRuntime {\n readonly apiClient: GroupMetadataAccessInput[\"apiClient\"] &\n PrincipalPolicyReadApi;\n readonly crypto: {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n };\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: {\n readonly log: (message: string) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n };\n}\n\nexport function createRuntimeGroupMetadataAccess(\n runtime: GroupMetadataRuntime,\n organizationId: string,\n stillCurrent?: () => boolean,\n verifyMetadataContainer?: GroupMetadataAccessInput[\"verifyMetadataContainer\"],\n currentRecovery?: {\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver | undefined;\n readonly recoveryBatch: object;\n },\n) {\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!targetSecretKey) throw new Error(\"Group metadata identity is locked\");\n // The signed metadata projection selects exact citations. Reuse matching\n // private evidence with its dependencies and pins before bounded online reads.\n const warmer = runtime.principalPolicies.createWarmer({\n preferLocalCurrent: true,\n });\n const resolveCurrentPolicy =\n currentRecovery?.resolveCurrentPolicy ??\n runtime.principalPolicies.createCurrentPolicyResolver();\n const authorityInput = {\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: stillCurrent ?? (() => true),\n };\n return createGroupMetadataAccess({\n verifyMetadataContainer:\n verifyMetadataContainer ??\n createCurrentGroupMetadataContainerVerifier({\n ...authorityInput,\n resolveCurrentPolicy: requireCurrentResolver(resolveCurrentPolicy),\n recoveryBatch: currentRecovery?.recoveryBatch,\n }),\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: warmer,\n });\n}\n\nfunction requireCurrentResolver(\n resolve: PrincipalPolicyCurrentResolver | undefined,\n) {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n return resolve;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
1
+ import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
2
2
  import { createCurrentGroupMetadataContainerVerifier } from "./currentGroupMetadataAuthority.js";
3
3
  /** Remote metadata destinations require the same private authority as name reads. */
4
4
  export async function verifyRuntimeGroupMetadataAuthority(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeGroupMetadataAuthority.js","sourceRoot":"","sources":["runtimeGroupMetadataAuthority.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AAExH,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAE9F,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAMzD;IACC,MAAM,oBAAoB,GACxB,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IAChE,IAAI,CAAC,oBAAoB;QACvB,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,MAAM,2CAA2C,CAAC;QAChD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB;QACpB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\n\n/** Remote metadata destinations require the same private authority as name reads. */\nexport async function verifyRuntimeGroupMetadataAuthority(input: {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n readonly organizationReference?: ReferencedPrincipalHead | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const resolveCurrentPolicy =\n input.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n await createCurrentGroupMetadataContainerVerifier({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n })(input.state, input.organizationReference);\n}\n"]}
1
+ {"version":3,"file":"runtimeGroupMetadataAuthority.js","sourceRoot":"","sources":["runtimeGroupMetadataAuthority.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAE9F,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAMzD;IACC,MAAM,oBAAoB,GACxB,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IAChE,IAAI,CAAC,oBAAoB;QACvB,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,MAAM,2CAA2C,CAAC;QAChD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB;QACpB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\n\n/** Remote metadata destinations require the same private authority as name reads. */\nexport async function verifyRuntimeGroupMetadataAuthority(input: {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n readonly organizationReference?: ReferencedPrincipalHead | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const resolveCurrentPolicy =\n input.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n await createCurrentGroupMetadataContainerVerifier({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n })(input.state, input.organizationReference);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
1
+ import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
2
2
  import { hydrateCurrentOrganizationGroupNames } from "./currentOrganizationGroupNames.js";
3
3
  /** Verify names against the signed directory before projecting decrypted labels. */
4
4
  export async function hydrateOrganizationGroupNames(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"organizationGroupNames.js","sourceRoot":"","sources":["organizationGroupNames.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AAExH,OAAO,EAAE,oCAAoC,EAAE,MAAM,iCAAiC,CAAC;AAGvF,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,KAaC;IAED,IAAI,CAAC,KAAK,CAAC,oBAAoB;QAC7B,MAAM,IAAI,oCAAoC,CAC5C,4CAA4C,CAC7C,CAAC;IACJ,OAAO,oCAAoC,CAAC;QAC1C,GAAG,KAAK;QACR,qBAAqB,EAAE,KAAK,CAAC,2BAA2B;QACxD,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport type { OrganizationDirectoryAndGroups } from \"../readModel\";\nimport { hydrateCurrentOrganizationGroupNames } from \"./currentOrganizationGroupNames\";\nimport type { DirectoryGroupWalkInput } from \"./groupNameUniqueness\";\n\n/** Verify names against the signed directory before projecting decrypted labels. */\nexport async function hydrateOrganizationGroupNames(\n input: Omit<DirectoryGroupWalkInput, \"descriptor\" | \"externalAuthority\"> & {\n readonly directory: OrganizationDirectoryAndGroups;\n readonly organizationPolicyReference?: ReferencedPrincipalHead | null;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n readonly createCurrentNameReader?: Parameters<\n typeof hydrateCurrentOrganizationGroupNames\n >[0][\"createCurrentNameReader\"];\n readonly resolveCurrentPolicy?:\n | Parameters<\n typeof hydrateCurrentOrganizationGroupNames\n >[0][\"resolveCurrentPolicy\"]\n | undefined;\n },\n): Promise<OrganizationDirectoryAndGroups> {\n if (!input.resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group names require private paged recovery\",\n );\n return hydrateCurrentOrganizationGroupNames({\n ...input,\n organizationReference: input.organizationPolicyReference,\n resolveCurrentPolicy: input.resolveCurrentPolicy,\n });\n}\n"]}
1
+ {"version":3,"file":"organizationGroupNames.js","sourceRoot":"","sources":["organizationGroupNames.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,oCAAoC,EAAE,MAAM,iCAAiC,CAAC;AAGvF,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,KAaC;IAED,IAAI,CAAC,KAAK,CAAC,oBAAoB;QAC7B,MAAM,IAAI,oCAAoC,CAC5C,4CAA4C,CAC7C,CAAC;IACJ,OAAO,oCAAoC,CAAC;QAC1C,GAAG,KAAK;QACR,qBAAqB,EAAE,KAAK,CAAC,2BAA2B;QACxD,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { OrganizationDirectoryAndGroups } from \"../readModel\";\nimport { hydrateCurrentOrganizationGroupNames } from \"./currentOrganizationGroupNames\";\nimport type { DirectoryGroupWalkInput } from \"./groupNameUniqueness\";\n\n/** Verify names against the signed directory before projecting decrypted labels. */\nexport async function hydrateOrganizationGroupNames(\n input: Omit<DirectoryGroupWalkInput, \"descriptor\" | \"externalAuthority\"> & {\n readonly directory: OrganizationDirectoryAndGroups;\n readonly organizationPolicyReference?: ReferencedPrincipalHead | null;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n readonly createCurrentNameReader?: Parameters<\n typeof hydrateCurrentOrganizationGroupNames\n >[0][\"createCurrentNameReader\"];\n readonly resolveCurrentPolicy?:\n | Parameters<\n typeof hydrateCurrentOrganizationGroupNames\n >[0][\"resolveCurrentPolicy\"]\n | undefined;\n },\n): Promise<OrganizationDirectoryAndGroups> {\n if (!input.resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group names require private paged recovery\",\n );\n return hydrateCurrentOrganizationGroupNames({\n ...input,\n organizationReference: input.organizationPolicyReference,\n resolveCurrentPolicy: input.resolveCurrentPolicy,\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
- import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
+ import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
3
3
  /**
4
4
  * Client calls that leave the server unchanged. Every other call counts as a
5
5
  * write (the group policy commit in either form, the share, a recitation), so
@@ -1 +1 @@
1
- {"version":3,"file":"groupShareReplan.js","sourceRoot":"","sources":["groupShareReplan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE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AK,CAAC,SAAS,EAAE,GAAG,EAAE;gBAC5C,KAAK,GAAG,IAAI,CAAC;YACf,CAAC,CAAC;SACH,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,IAAI,CAAC,oBAAoB,CAAC,KAAK,CAAC;YAAE,MAAM,KAAK,CAAC;IACzD,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClD,KAAK,CAAC,SAAS,CAAC,8BAA8B,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAClE,OAAO,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,kBAAkB,EAAE,SAAS,EAAE,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\n\n/**\n * Client calls that leave the server unchanged. Every other call counts as a\n * write (the group policy commit in either form, the share, a recitation), so\n * a write method added later blocks the replan rather than slipping past it.\n * Recovery settles an earlier journaled mutation, never this share's.\n */\nfunction isReadOnlyCall(method: string): boolean {\n return (\n /^(evict|get|list)[A-Z]/u.test(method) ||\n method === \"recoverPendingPrincipalMutation\"\n );\n}\n\ninterface ReplannableGroupShareInput<Api extends object> {\n readonly apiClient: Api & {\n evictContainerWriterProjection(containerId: string): void;\n };\n readonly containerId: string;\n readonly previousProjection?: ContainerWriterProjectionResponse | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/**\n * A cached path can trail a pin this device advanced (a rollback), or its\n * history a checkpoint another workflow pinned meanwhile (a retryable missing\n * dependency). A fresh projection resolves both and is held to the same pins.\n */\nfunction isStaleShareEvidence(error: unknown): boolean {\n return (\n error instanceof ProjectionDependencyUnavailableError ||\n (error instanceof KeyingVerificationError && error.code === \"rollback\")\n );\n}\n\nfunction recordWrites<Api extends object>(api: Api, onWrite: () => void): Api {\n return new Proxy(api, {\n get(target, property) {\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const bound = (...args: unknown[]): unknown =>\n Reflect.apply(value, target, args);\n if (typeof property === \"string\" && isReadOnlyCall(property))\n return bound;\n return (...args: unknown[]): unknown => {\n onWrite();\n return bound(...args);\n };\n },\n });\n}\n\n/**\n * Plan a group share once more from a fresh projection when its evidence was\n * stale, as a user share and a create do, but only while no remote write (the\n * group grant policy or the share itself) has been submitted: a write may have\n * landed, and replaying it is not this retry's call. A second stale plan fails.\n */\nexport async function shareWithGroupReplanningOnce<\n Api extends object,\n Input extends ReplannableGroupShareInput<Api>,\n Result,\n>(\n input: Input,\n attempt: (input: Input) => Promise<Result | null>,\n): Promise<Result | null> {\n let wrote = false;\n try {\n return await attempt({\n ...input,\n apiClient: recordWrites(input.apiClient, () => {\n wrote = true;\n }),\n });\n } catch (error) {\n if (wrote || !isStaleShareEvidence(error)) throw error;\n }\n if (input.stillCurrent?.() === false) return null;\n input.apiClient.evictContainerWriterProjection(input.containerId);\n return attempt({ ...input, previousProjection: undefined });\n}\n"]}
1
+ {"version":3,"file":"groupShareReplan.js","sourceRoot":"","sources":["groupShareReplan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG;;;;;GAKG;AACH,SAAS,cAAc,CAAC,MAAc;IACpC,OAAO,CACL,yBAAyB,CAAC,IAAI,CAAC,MAAM,CAAC;QACtC,MAAM,KAAK,iCAAiC,CAC7C,CAAC;AACJ,CAAC;AAWD;;;;GAIG;AACH,SAAS,oBAAoB,CAAC,KAAc;IAC1C,OAAO,CACL,KAAK,YAAY,oCAAoC;QACrD,CAAC,KAAK,YAAY,uBAAuB,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,CAAC,CACx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AC,SAAS,CAAC,8BAA8B,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAClE,OAAO,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,kBAAkB,EAAE,SAAS,EAAE,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\n\n/**\n * Client calls that leave the server unchanged. Every other call counts as a\n * write (the group policy commit in either form, the share, a recitation), so\n * a write method added later blocks the replan rather than slipping past it.\n * Recovery settles an earlier journaled mutation, never this share's.\n */\nfunction isReadOnlyCall(method: string): boolean {\n return (\n /^(evict|get|list)[A-Z]/u.test(method) ||\n method === \"recoverPendingPrincipalMutation\"\n );\n}\n\ninterface ReplannableGroupShareInput<Api extends object> {\n readonly apiClient: Api & {\n evictContainerWriterProjection(containerId: string): void;\n };\n readonly containerId: string;\n readonly previousProjection?: ContainerWriterProjectionResponse | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/**\n * A cached path can trail a pin this device advanced (a rollback), or its\n * history a checkpoint another workflow pinned meanwhile (a retryable missing\n * dependency). A fresh projection resolves both and is held to the same pins.\n */\nfunction isStaleShareEvidence(error: unknown): boolean {\n return (\n error instanceof ProjectionDependencyUnavailableError ||\n (error instanceof KeyingVerificationError && error.code === \"rollback\")\n );\n}\n\nfunction recordWrites<Api extends object>(api: Api, onWrite: () => void): Api {\n return new Proxy(api, {\n get(target, property) {\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const bound = (...args: unknown[]): unknown =>\n Reflect.apply(value, target, args);\n if (typeof property === \"string\" && isReadOnlyCall(property))\n return bound;\n return (...args: unknown[]): unknown => {\n onWrite();\n return bound(...args);\n };\n },\n });\n}\n\n/**\n * Plan a group share once more from a fresh projection when its evidence was\n * stale, as a user share and a create do, but only while no remote write (the\n * group grant policy or the share itself) has been submitted: a write may have\n * landed, and replaying it is not this retry's call. A second stale plan fails.\n */\nexport async function shareWithGroupReplanningOnce<\n Api extends object,\n Input extends ReplannableGroupShareInput<Api>,\n Result,\n>(\n input: Input,\n attempt: (input: Input) => Promise<Result | null>,\n): Promise<Result | null> {\n let wrote = false;\n try {\n return await attempt({\n ...input,\n apiClient: recordWrites(input.apiClient, () => {\n wrote = true;\n }),\n });\n } catch (error) {\n if (wrote || !isStaleShareEvidence(error)) throw error;\n }\n if (input.stillCurrent?.() === false) return null;\n input.apiClient.evictContainerWriterProjection(input.containerId);\n return attempt({ ...input, previousProjection: undefined });\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
3
2
  import { requireOrganizationGroupHead } from "../../../data/principals/organizationAuthorityDescriptor.js";
3
+ import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
4
4
  import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
5
5
  import { loadLocalOrganizationPolicyReference } from "../readModel/localReadModelDetails.js";
6
6
  import { createLeaveRequestMembershipCheck, } from "./leaveRequestMembership.js";
@@ -1 +1 @@
1
- {"version":3,"file":"leaveRequestMembersEvidence.js","sourceRoot":"","sources":["leaveRequestMembersEvidence.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AAExG,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAC1F,OAAO,EACL,iCAAiC,GAElC,MAAM,0BAA0B,CAAC;AAQlC;;;GAGG;A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AAW,EAAE,KAAK,CAAC,cAAc;gBACjC,aAAa,EAAE,cAAc;aAC9B,CAAC,CAAC;YACH,IAAI,CAAC,qBAAqB;gBAAE,OAAO,IAAI,CAAC;YACxC,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC;gBACvD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;gBACpC,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,qBAAqB;gBACrB,oBAAoB,EAAE,OAAO;gBAC7B,YAAY,EAAE,KAAK,CAAC,YAAY;aACjC,CAAC,CAAC;YACH,mCAAmC,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;YAC5D,OAAO,4BAA4B,CACjC,SAAS,CAAC,UAAU,EACpB,SAAS,CAAC,UAAU,CAAC,aAAa,CACnC,CAAC;QACJ,CAAC;QACD,eAAe,EAAE,OAAO;YACtB,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,EAAE;gBAC5B,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC;oBAC7B,cAAc,EAAE,KAAK,CAAC,cAAc;oBACpC,SAAS,EAAE,IAAI;oBACf,kBAAkB,EAAE,IAAI;oBACxB,YAAY,EAAE,KAAK,CAAC,YAAY;oBAChC,WAAW,EAAE,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE;iBAClE,CAAC,CAAC;gBACH,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;gBAC3D,IAAI,CAAC,QAAQ,CAAC,WAAW;oBACvB,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;gBAC9D,OAAO,QAAQ,CAAC,WAAW,CAAC;YAC9B,CAAC;YACH,CAAC,CAAC,SAAS;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { OrganizationLeaveRequestMembersHead } from \"@tearleads/validators/util\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { requireOrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { loadLocalOrganizationPolicyReference } from \"../readModel/localReadModelDetails\";\nimport {\n createLeaveRequestMembershipCheck,\n type LeaveRequestMembershipCheck,\n} from \"./leaveRequestMembership\";\n\ninterface MembersEvidenceInput {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * The organization's current Members head as the member's own device\n * discovers and verifies it now, for a leave request to cite.\n */\nexport async function loadCurrentMembersHead(\n input: MembersEvidenceInput,\n): Promise<OrganizationLeaveRequestMembersHead> {\n const resolveCurrentPolicy =\n input.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Asking to leave requires private paged recovery\",\n );\n const authority = await loadCurrentOrganizationAuthority({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(authority.stillCurrent);\n const head = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.memberGroupId,\n );\n return {\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n };\n}\n\n/**\n * Checks leave requests against the Members head in the organization policy\n * this device's read model selected, verified exactly through the private\n * paged verifier (from local evidence when it has it), and walks verified\n * Members history the same way when a request cites an earlier key epoch.\n */\nexport function createRuntimeLeaveRequestMembershipCheck(\n input: MembersEvidenceInput & { readonly currentUserId: string },\n): LeaveRequestMembershipCheck {\n const resolve = input.runtime.principalPolicies.createCurrentPolicyResolver();\n return createLeaveRequestMembershipCheck({\n async loadMembersHead() {\n if (!resolve) return null;\n const organizationReference = await loadLocalOrganizationPolicyReference({\n currentUserId: input.currentUserId,\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n principalId: input.organizationId,\n principalType: \"organization\",\n });\n if (!organizationReference) return null;\n const authority = await loadCurrentOrganizationAuthority({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n organizationReference,\n resolveCurrentPolicy: resolve,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(authority.stillCurrent);\n return requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.memberGroupId,\n );\n },\n loadHistoryPage: resolve\n ? async (head, beforeVersion) => {\n const resolved = await resolve({\n organizationId: input.organizationId,\n reference: head,\n preferLocalCurrent: true,\n stillCurrent: input.stillCurrent,\n historyPage: beforeVersion === undefined ? {} : { beforeVersion },\n });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n if (!resolved.historyPage)\n throw new Error(\"Verified Members history page is missing\");\n return resolved.historyPage;\n }\n : undefined,\n });\n}\n"]}
1
+ {"version":3,"file":"leaveRequestMembersEvidence.js","sourceRoot":"","sources":["leaveRequestMembersEvidence.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AACxG,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAC1F,OAAO,EACL,iCAAiC,GAElC,MAAM,0BAA0B,CAAC;AAQlC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAA2B;IAE3B,MAAM,oBAAoB,GACxB,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IAChE,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AAG,MAAM,gCAAgC,CAAC;gBACvD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;gBACpC,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,qBAAqB;gBACrB,oBAAoB,EAAE,OAAO;gBAC7B,YAAY,EAAE,KAAK,CAAC,YAAY;aACjC,CAAC,CAAC;YACH,mCAAmC,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;YAC5D,OAAO,4BAA4B,CACjC,SAAS,CAAC,UAAU,EACpB,SAAS,CAAC,UAAU,CAAC,aAAa,CACnC,CAAC;QACJ,CAAC;QACD,eAAe,EAAE,OAAO;YACtB,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,EAAE;gBAC5B,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC;oBAC7B,cAAc,EAAE,KAAK,CAAC,cAAc;oBACpC,SAAS,EAAE,IAAI;oBACf,kBAAkB,EAAE,IAAI;oBACxB,YAAY,EAAE,KAAK,CAAC,YAAY;oBAChC,WAAW,EAAE,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE;iBAClE,CAAC,CAAC;gBACH,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;gBAC3D,IAAI,CAAC,QAAQ,CAAC,WAAW;oBACvB,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;gBAC9D,OAAO,QAAQ,CAAC,WAAW,CAAC;YAC9B,CAAC;YACH,CAAC,CAAC,SAAS;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { OrganizationLeaveRequestMembersHead } from \"@tearleads/validators/util\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { requireOrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { loadLocalOrganizationPolicyReference } from \"../readModel/localReadModelDetails\";\nimport {\n createLeaveRequestMembershipCheck,\n type LeaveRequestMembershipCheck,\n} from \"./leaveRequestMembership\";\n\ninterface MembersEvidenceInput {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * The organization's current Members head as the member's own device\n * discovers and verifies it now, for a leave request to cite.\n */\nexport async function loadCurrentMembersHead(\n input: MembersEvidenceInput,\n): Promise<OrganizationLeaveRequestMembersHead> {\n const resolveCurrentPolicy =\n input.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Asking to leave requires private paged recovery\",\n );\n const authority = await loadCurrentOrganizationAuthority({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(authority.stillCurrent);\n const head = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.memberGroupId,\n );\n return {\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n };\n}\n\n/**\n * Checks leave requests against the Members head in the organization policy\n * this device's read model selected, verified exactly through the private\n * paged verifier (from local evidence when it has it), and walks verified\n * Members history the same way when a request cites an earlier key epoch.\n */\nexport function createRuntimeLeaveRequestMembershipCheck(\n input: MembersEvidenceInput & { readonly currentUserId: string },\n): LeaveRequestMembershipCheck {\n const resolve = input.runtime.principalPolicies.createCurrentPolicyResolver();\n return createLeaveRequestMembershipCheck({\n async loadMembersHead() {\n if (!resolve) return null;\n const organizationReference = await loadLocalOrganizationPolicyReference({\n currentUserId: input.currentUserId,\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n principalId: input.organizationId,\n principalType: \"organization\",\n });\n if (!organizationReference) return null;\n const authority = await loadCurrentOrganizationAuthority({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n organizationReference,\n resolveCurrentPolicy: resolve,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(authority.stillCurrent);\n return requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.memberGroupId,\n );\n },\n loadHistoryPage: resolve\n ? async (head, beforeVersion) => {\n const resolved = await resolve({\n organizationId: input.organizationId,\n reference: head,\n preferLocalCurrent: true,\n stillCurrent: input.stillCurrent,\n historyPage: beforeVersion === undefined ? {} : { beforeVersion },\n });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n if (!resolved.historyPage)\n throw new Error(\"Verified Members history page is missing\");\n return resolved.historyPage;\n }\n : undefined,\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
1
  import { reportKeyingVerificationErrorInCauseChain } from "../../../data/keyingProjectionVerification/error.js";
2
+ import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
3
3
  import { loadLocalOrganizationPolicyReference } from "../readModel/localReadModelDetails.js";
4
4
  import { captureOrganizationPresentationAccessAttempt, isOrganizationPresentationAccessAttemptCurrent, isOrganizationPresentationAccessReadable, } from "../readModel/organizationPresentationAccessState.js";
5
5
  import { isOrganizationPresentationAccessDeniedFailure } from "../readModel/organizationPresentationFailures.js";
@@ -1 +1 @@
1
- {"version":3,"file":"loadPolicyHistoryDetails.js","sourceRoot":"","sources":["loadPolicyHistoryDetails.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,yCAAyC,EAAE,MAAM,kDAAkD,CAAC;AAM7G,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAC1F,OAAO,EACL,4CAA4C,EAC5C,8CAA8C,E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M,MAAM,CAAC,OAAO,CAAC,CAAC;QACvC,IAAI,QAAQ,KAAK,OAAO;YACtB,kBAAkB,CAAC,EAAE,GAAG,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;QACrD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IACE,CAAC,KAAK,CAAC,SAAS;YAChB,KAAK,YAAY,oCAAoC;YAErD,OAAO,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC/B,MAAM,yCAAyC,CAC7C,KAAK,EACL,KAAK,CAAC,sBAAsB,EAC5B;YACE,QAAQ,EAAE,KAAK,CAAC,cAAc;YAC9B,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,kCAAkC;YAC7C,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CACF,CAAC;QACF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/keyingProjectionVerification/error\";\nimport type { ReferencedPrincipalPolicyWarmer } from \"../../../data/keyingProjectionVerification/types\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { RecoveredPrincipalHistoryPage } from \"../../principals/historyRecovery/loadRecoveredPrincipalHistoryPage\";\nimport { loadLocalOrganizationPolicyReference } from \"../readModel/localReadModelDetails\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n} from \"../readModel/organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"../readModel/organizationPresentationFailures\";\nimport { buildDetailedOrganizationPolicyHistory } from \"./organizationPolicyHistoryDetails\";\nimport { denyPolicyHistoryAccess } from \"./policyHistoryAccessDenial\";\nimport {\n cachePolicyHistory,\n loadCachedPolicyHistory,\n} from \"./policyHistoryCache\";\nimport type { OrganizationPolicyHistory } from \"./policyHistoryTypes\";\n\nexport async function loadPolicyHistoryDetails(input: {\n apiClient: Pick<ApiClient, \"getOrganizationPolicyHistoryResult\">;\n currentUserId: string;\n domainScope: DomainScope;\n execSql: ExecSql;\n organizationId: string;\n head: ReferencedPrincipalHead;\n page: RecoveredPrincipalHistoryPage;\n history: OrganizationPolicyHistory;\n resolveHistory: NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"]\n >;\n stillCurrent: () => boolean;\n online: boolean;\n olderPage: boolean;\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n // Forwarded to denyPolicyHistoryAccess to report failed durable cleanup.\n logError: (message: string | Error, cause?: unknown) => void;\n}): Promise<OrganizationPolicyHistory | null> {\n const access = { ...input, requesterUserId: input.currentUserId };\n const attempt = captureOrganizationPresentationAccessAttempt(\n access,\n \"readModel\",\n );\n const current = () =>\n input.stillCurrent() &&\n isOrganizationPresentationAccessAttemptCurrent(access, attempt) &&\n isOrganizationPresentationAccessReadable(access, \"readModel\");\n if (!current()) return null;\n const beforeVersion = (input.page.entries.at(-1)?.state.version ?? 0) + 1;\n const cache = {\n domainScope: input.domainScope,\n access,\n stateHash: input.head.stateHash,\n beforeVersion,\n };\n const retain = async (history: OrganizationPolicyHistory) => {\n const latest = await loadLocalOrganizationPolicyReference({\n ...input,\n principalType: \"organization\",\n principalId: input.organizationId,\n });\n return current() && latest?.stateHash === input.head.stateHash\n ? history\n : null;\n };\n const cached = loadCachedPolicyHistory(cache);\n if (cached) return retain(cached);\n if (!input.online) return retain(input.history);\n try {\n const response = await input.apiClient.getOrganizationPolicyHistoryResult(\n input.organizationId,\n input.head.stateHash,\n { beforeVersion, reportErrors: false },\n );\n if (!input.stillCurrent()) return null;\n if (!response.ok) {\n if (isOrganizationPresentationAccessDeniedFailure(response)) {\n await denyPolicyHistoryAccess(access);\n return null;\n }\n response.report();\n if (input.olderPage) throw new Error(response.message);\n return retain(input.history);\n }\n const history = await buildDetailedOrganizationPolicyHistory({\n head: input.head,\n page: input.page,\n evidence: response.data,\n resolveHistory: input.resolveHistory,\n stillCurrent: current,\n });\n const retained = await retain(history);\n if (retained === history)\n cachePolicyHistory({ ...cache, attempt, history });\n return retained;\n } catch (error) {\n if (\n !input.olderPage &&\n error instanceof ProjectionDependencyUnavailableError\n )\n return retain(input.history);\n await reportKeyingVerificationErrorInCauseChain(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.organizationId,\n objectKind: \"principal\",\n operation: \"organization.policy_history.load\",\n organizationId: input.organizationId,\n },\n );\n throw error;\n }\n}\n"]}
1
+ {"version":3,"file":"loadPolicyHistoryDetails.js","sourceRoot":"","sources":["loadPolicyHistoryDetails.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yCAAyC,EAAE,MAAM,kDAAkD,CAAC;AAE7G,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAKlG,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAC1F,OAAO,EACL,4CAA4C,EAC5C,8CAA8C,EAC9C,wCAAwC,GACzC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,6CAA6C,EAAE,MAAM,+CAA+C,CAAC;AAC9G,OAAO,EAAE,sCAAsC,EAAE,MAAM,oCAAoC,CAAC;AAC5F,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAG9B,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,KAkB9C;IACC,MAAM,MAAM,GAAG,EAAE,GAAG,KAAK,EAAE,eAAe,EAAE,KAAK,CAAC,aAAa,EAAE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EAAE,KAAK,CAAC,cAAc;YAC9B,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,kCAAkC;YAC7C,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CACF,CAAC;QACF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/keyingProjectionVerification/error\";\nimport type { ReferencedPrincipalPolicyWarmer } from \"../../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { RecoveredPrincipalHistoryPage } from \"../../principals/historyRecovery/loadRecoveredPrincipalHistoryPage\";\nimport { loadLocalOrganizationPolicyReference } from \"../readModel/localReadModelDetails\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n} from \"../readModel/organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"../readModel/organizationPresentationFailures\";\nimport { buildDetailedOrganizationPolicyHistory } from \"./organizationPolicyHistoryDetails\";\nimport { denyPolicyHistoryAccess } from \"./policyHistoryAccessDenial\";\nimport {\n cachePolicyHistory,\n loadCachedPolicyHistory,\n} from \"./policyHistoryCache\";\nimport type { OrganizationPolicyHistory } from \"./policyHistoryTypes\";\n\nexport async function loadPolicyHistoryDetails(input: {\n apiClient: Pick<ApiClient, \"getOrganizationPolicyHistoryResult\">;\n currentUserId: string;\n domainScope: DomainScope;\n execSql: ExecSql;\n organizationId: string;\n head: ReferencedPrincipalHead;\n page: RecoveredPrincipalHistoryPage;\n history: OrganizationPolicyHistory;\n resolveHistory: NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"]\n >;\n stillCurrent: () => boolean;\n online: boolean;\n olderPage: boolean;\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n // Forwarded to denyPolicyHistoryAccess to report failed durable cleanup.\n logError: (message: string | Error, cause?: unknown) => void;\n}): Promise<OrganizationPolicyHistory | null> {\n const access = { ...input, requesterUserId: input.currentUserId };\n const attempt = captureOrganizationPresentationAccessAttempt(\n access,\n \"readModel\",\n );\n const current = () =>\n input.stillCurrent() &&\n isOrganizationPresentationAccessAttemptCurrent(access, attempt) &&\n isOrganizationPresentationAccessReadable(access, \"readModel\");\n if (!current()) return null;\n const beforeVersion = (input.page.entries.at(-1)?.state.version ?? 0) + 1;\n const cache = {\n domainScope: input.domainScope,\n access,\n stateHash: input.head.stateHash,\n beforeVersion,\n };\n const retain = async (history: OrganizationPolicyHistory) => {\n const latest = await loadLocalOrganizationPolicyReference({\n ...input,\n principalType: \"organization\",\n principalId: input.organizationId,\n });\n return current() && latest?.stateHash === input.head.stateHash\n ? history\n : null;\n };\n const cached = loadCachedPolicyHistory(cache);\n if (cached) return retain(cached);\n if (!input.online) return retain(input.history);\n try {\n const response = await input.apiClient.getOrganizationPolicyHistoryResult(\n input.organizationId,\n input.head.stateHash,\n { beforeVersion, reportErrors: false },\n );\n if (!input.stillCurrent()) return null;\n if (!response.ok) {\n if (isOrganizationPresentationAccessDeniedFailure(response)) {\n await denyPolicyHistoryAccess(access);\n return null;\n }\n response.report();\n if (input.olderPage) throw new Error(response.message);\n return retain(input.history);\n }\n const history = await buildDetailedOrganizationPolicyHistory({\n head: input.head,\n page: input.page,\n evidence: response.data,\n resolveHistory: input.resolveHistory,\n stillCurrent: current,\n });\n const retained = await retain(history);\n if (retained === history)\n cachePolicyHistory({ ...cache, attempt, history });\n return retained;\n } catch (error) {\n if (\n !input.olderPage &&\n error instanceof ProjectionDependencyUnavailableError\n )\n return retain(input.history);\n await reportKeyingVerificationErrorInCauseChain(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.organizationId,\n objectKind: \"principal\",\n operation: \"organization.policy_history.load\",\n organizationId: input.organizationId,\n },\n );\n throw error;\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
- import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
3
2
  import { externalAuthorityCouldAuthorize, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../../data/principals/principalPolicyAdminSigners.js";
3
+ import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
4
4
  import { collectPrincipalPolicySignerPublicKeys, principalPolicyStates, } from "../policyVerification.js";
5
5
  function getBundleReferenceFailure(reference, bundle) {
6
6
  const states = principalPolicyStates(bundle);
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,GAC1D,MAAM,sDAAsD,CAAC;AAG9D,OAAO,EACL,sCAAsC,EAEtC,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAO/B,SAAS,yBAAyB,CAChC,SAA2C,EAC3C,MAAqC;IAErC,MAAM,MAAM,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC7C,MAAM,sBAAsB,GAAG,MAAM,CAAC,IAAI,CACxC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC5B,OAAO;YACL,IAAI,EAAE,iBAAiB;YACvB,OAA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AAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../policyVerification\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,GAC1D,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAGlG,OAAO,EACL,sCAAsC,EAEtC,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAO/B,SAAS,yBAAyB,CAChC,SAA2C,EAC3C,MAAqC;IAErC,MAAM,MAAM,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC7C,MAAM,sBAAsB,GAAG,MAAM,CAAC,IAAI,CACxC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC5B,OAAO;YACL,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,sDAAsD;SAChE,CAAC;IACJ,CAAC;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KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../policyVerification\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
@@ -1,8 +1,8 @@
1
- import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
1
  import { rethrowKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
3
2
  import { assertProjectionVerificationCurrent, isProjectionVerificationCancelledError, } from "../../data/keyingProjectionVerification/types.js";
4
3
  import { directoryHistoryProtection } from "../../data/principals/principalHistoryScopeProtection.js";
5
4
  import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
5
+ import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
6
6
  import { errorMessage } from "../../data/shared/errorMessage.js";
7
7
  import { apiPrincipalPolicyPageReader, } from "./principalPolicyHistoryReader.js";
8
8
  import { createPrincipalPolicyCurrentResolver, } from "./runtimePolicyRecovery.js";