@tearleads/client-sdk 0.1.15 → 0.1.16

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 (166) hide show
  1. package/client/Tearleads.d.ts +2 -0
  2. package/client/Tearleads.js +1 -0
  3. package/client/Tearleads.js.map +1 -1
  4. package/client/index.d.ts +1 -1
  5. package/client/index.js.map +1 -1
  6. package/client/organizations/index.d.ts +4 -42
  7. package/client/organizations/index.js +13 -0
  8. package/client/organizations/index.js.map +1 -1
  9. package/client/organizations/organizationGroupNameHydration.js +8 -1
  10. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  11. package/client/organizations/organizationsTypes.d.ts +47 -0
  12. package/client/organizations/organizationsTypes.js +2 -0
  13. package/client/organizations/organizationsTypes.js.map +1 -0
  14. package/client/organizations/principalMutationRecovery.d.ts +16 -0
  15. package/client/organizations/principalMutationRecovery.js +23 -0
  16. package/client/organizations/principalMutationRecovery.js.map +1 -0
  17. package/client/organizations/principalMutationScope.js +7 -2
  18. package/client/organizations/principalMutationScope.js.map +1 -1
  19. package/client/principalMutationApi.d.ts +24 -0
  20. package/client/principalMutationApi.js +108 -0
  21. package/client/principalMutationApi.js.map +1 -0
  22. package/client/principalMutationDeadline.js +23 -0
  23. package/client/principalMutationDeadline.js.map +1 -0
  24. package/client/workflowRuntime.d.ts +3 -1
  25. package/client/workflowRuntime.js +44 -5
  26. package/client/workflowRuntime.js.map +1 -1
  27. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +27 -0
  28. package/data/persistence/principalCurrentAcknowledgementPersistence.js +109 -0
  29. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -0
  30. package/data/persistence/principalGrantRetirementPersistence.d.ts +3 -3
  31. package/data/persistence/principalGrantRetirementPersistence.js +4 -1
  32. package/data/persistence/principalGrantRetirementPersistence.js.map +1 -1
  33. package/data/persistence/principalKeyEnvelopeCandidates.js +12 -1
  34. package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -1
  35. package/data/persistence/principalMutationJournalPersistence.d.ts +19 -0
  36. package/data/persistence/principalMutationJournalPersistence.js +53 -0
  37. package/data/persistence/principalMutationJournalPersistence.js.map +1 -0
  38. package/data/persistence/verifiedPrincipalPolicyBundle.js +7 -51
  39. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
  40. package/data/persistence/verifiedPrincipalPolicyCurrent.js +56 -0
  41. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -0
  42. package/data/principals/principalMutationJournal.d.ts +26 -0
  43. package/data/principals/principalMutationJournal.js +90 -0
  44. package/data/principals/principalMutationJournal.js.map +1 -0
  45. package/data/principals/principalMutationJournalRecord.d.ts +8 -0
  46. package/data/principals/principalMutationJournalRecord.js +25 -0
  47. package/data/principals/principalMutationJournalRecord.js.map +1 -0
  48. package/data/sqlite/principalHistoryStageSchema.js +3 -0
  49. package/data/sqlite/principalHistoryStageSchema.js.map +1 -1
  50. package/data/sqlite/principalMutationJournalSchema.d.ts +85 -0
  51. package/data/sqlite/principalMutationJournalSchema.js +13 -0
  52. package/data/sqlite/principalMutationJournalSchema.js.map +1 -0
  53. package/data/sqlite/schema.d.ts +83 -0
  54. package/data/sqlite/schema.js +3 -0
  55. package/data/sqlite/schema.js.map +1 -1
  56. package/index.d.ts +3 -3
  57. package/index.js +1 -1
  58. package/index.js.map +1 -1
  59. package/internal/crypto/index.d.ts +1 -1
  60. package/internal/crypto/index.js +1 -1
  61. package/internal/crypto/index.js.map +1 -1
  62. package/internal/crypto/keying/index.d.ts +2 -0
  63. package/internal/crypto/keying/index.js +2 -0
  64. package/internal/crypto/keying/index.js.map +1 -1
  65. package/internal/crypto/keying/principalPolicyCurrent.d.ts +1 -1
  66. package/internal/crypto/keying/principalPolicyCurrent.js +3 -3
  67. package/internal/crypto/keying/principalPolicyCurrent.js.map +1 -1
  68. package/internal/crypto/keying/principalPolicyCurrentEvidence.js +16 -0
  69. package/internal/crypto/keying/principalPolicyCurrentEvidence.js.map +1 -0
  70. package/internal/crypto/keying/principalPolicyCurrentMutation.d.ts +10 -0
  71. package/internal/crypto/keying/principalPolicyCurrentMutation.js +51 -0
  72. package/internal/crypto/keying/principalPolicyCurrentMutation.js.map +1 -0
  73. package/internal/crypto/keying/principalPolicyCurrentSuccessor.d.ts +10 -0
  74. package/internal/crypto/keying/principalPolicyCurrentSuccessor.js +60 -0
  75. package/internal/crypto/keying/principalPolicyCurrentSuccessor.js.map +1 -0
  76. package/internal/crypto/keying/principalPolicyHistory.js +4 -1
  77. package/internal/crypto/keying/principalPolicyHistory.js.map +1 -1
  78. package/internal/crypto/keying/principalPolicyHistoryReferences.js +1 -1
  79. package/internal/crypto/keying/principalPolicyHistoryReferences.js.map +1 -1
  80. package/internal/crypto/keying/principalPolicyHistoryTypes.d.ts +5 -2
  81. package/internal/crypto/keying/principalPolicyHistoryTypes.js +6 -3
  82. package/internal/crypto/keying/principalPolicyHistoryTypes.js.map +1 -1
  83. package/package.json +1 -1
  84. package/workflows/containers/child/share.js +4 -0
  85. package/workflows/containers/child/share.js.map +1 -1
  86. package/workflows/containers/child/sharePrincipalPolicy.d.ts +1 -0
  87. package/workflows/containers/child/sharePrincipalPolicy.js.map +1 -1
  88. package/workflows/organizations/acknowledgedDirectoryBindings.js +18 -0
  89. package/workflows/organizations/acknowledgedDirectoryBindings.js.map +1 -0
  90. package/workflows/organizations/currentGroupMetadataAuthority.js +32 -0
  91. package/workflows/organizations/currentGroupMetadataAuthority.js.map +1 -0
  92. package/workflows/organizations/currentOrganizationAuthority.js +88 -0
  93. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -0
  94. package/workflows/organizations/currentOrganizationGroupNames.js +68 -0
  95. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -0
  96. package/workflows/organizations/currentPolicyMutationAcknowledgement.js +65 -0
  97. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -0
  98. package/workflows/organizations/deleteOrganizationGroup.js +1 -0
  99. package/workflows/organizations/deleteOrganizationGroup.js.map +1 -1
  100. package/workflows/organizations/groupCreation.js +1 -0
  101. package/workflows/organizations/groupCreation.js.map +1 -1
  102. package/workflows/organizations/groupMetadataAccess.d.ts +2 -2
  103. package/workflows/organizations/groupMetadataAccess.js +1 -1
  104. package/workflows/organizations/groupMetadataAccess.js.map +1 -1
  105. package/workflows/organizations/groupMetadataBinding.js.map +1 -1
  106. package/workflows/organizations/groupMetadataContainerAuthority.js +2 -47
  107. package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
  108. package/workflows/organizations/groupMetadataRootBinding.js +51 -0
  109. package/workflows/organizations/groupMetadataRootBinding.js.map +1 -0
  110. package/workflows/organizations/groupMetadataRuntime.js +20 -9
  111. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  112. package/workflows/organizations/groupMutationAuthorization.js.map +1 -1
  113. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +9 -75
  114. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  115. package/workflows/organizations/groupPolicyMutationContext.d.ts +5 -13
  116. package/workflows/organizations/groupPolicyMutationContext.js +1 -0
  117. package/workflows/organizations/groupPolicyMutationContext.js.map +1 -1
  118. package/workflows/organizations/groupPolicyMutationEvidence.d.ts +26 -0
  119. package/workflows/organizations/groupPolicyMutationEvidence.js +64 -0
  120. package/workflows/organizations/groupPolicyMutationEvidence.js.map +1 -0
  121. package/workflows/organizations/groupPolicyMutationHead.js.map +1 -1
  122. package/workflows/organizations/groupPolicyRequests.js +69 -63
  123. package/workflows/organizations/groupPolicyRequests.js.map +1 -1
  124. package/workflows/organizations/index.d.ts +6 -0
  125. package/workflows/organizations/index.js +5 -0
  126. package/workflows/organizations/index.js.map +1 -1
  127. package/workflows/organizations/organizationGroupNames.js +7 -0
  128. package/workflows/organizations/organizationGroupNames.js.map +1 -1
  129. package/workflows/organizations/principalCurrentPublicationSeal.js +51 -0
  130. package/workflows/organizations/principalCurrentPublicationSeal.js.map +1 -0
  131. package/workflows/organizations/principalMutationJournalLane.js +26 -0
  132. package/workflows/organizations/principalMutationJournalLane.js.map +1 -0
  133. package/workflows/organizations/principalMutationJournalManagement.d.ts +26 -0
  134. package/workflows/organizations/principalMutationJournalManagement.js +104 -0
  135. package/workflows/organizations/principalMutationJournalManagement.js.map +1 -0
  136. package/workflows/organizations/principalMutationJournalSession.d.ts +26 -0
  137. package/workflows/organizations/principalMutationJournalSession.js +85 -0
  138. package/workflows/organizations/principalMutationJournalSession.js.map +1 -0
  139. package/workflows/organizations/principalMutationReceipt.js +21 -0
  140. package/workflows/organizations/principalMutationReceipt.js.map +1 -0
  141. package/workflows/organizations/principalPolicyReceiptArtifacts.js +74 -0
  142. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -0
  143. package/workflows/organizations/principalPolicyRequest.d.ts +5 -4
  144. package/workflows/organizations/principalPolicyRequest.js.map +1 -1
  145. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +21 -0
  146. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +155 -0
  147. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -0
  148. package/workflows/principals/principalCurrentRecoveryBatch.js +14 -0
  149. package/workflows/principals/principalCurrentRecoveryBatch.js.map +1 -0
  150. package/workflows/principals/principalRecoveryDirectory.d.ts +1 -1
  151. package/workflows/principals/principalRecoveryDirectory.js +29 -4
  152. package/workflows/principals/principalRecoveryDirectory.js.map +1 -1
  153. package/workflows/principals/principalRecoveryDiscoveryPage.js +36 -0
  154. package/workflows/principals/principalRecoveryDiscoveryPage.js.map +1 -0
  155. package/workflows/principals/principalRecoveryLocalPreference.js +28 -0
  156. package/workflows/principals/principalRecoveryLocalPreference.js.map +1 -0
  157. package/workflows/principals/principalRecoveryMemo.d.ts +16 -0
  158. package/workflows/principals/principalRecoveryMemo.js +88 -16
  159. package/workflows/principals/principalRecoveryMemo.js.map +1 -1
  160. package/workflows/principals/recoverCurrentOrganizationPolicy.js +33 -0
  161. package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +1 -0
  162. package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +2 -1
  163. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +13 -15
  164. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  165. package/workflows/principals/runtimePolicyRecovery.js +14 -8
  166. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyHistory.js","sourceRoot":"","sources":["principalPolicyHistory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gCAAgC,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,8BAA8B,EAC9B,gCAAgC,GACjC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EACL,8CAA8C,GAE/C,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,4BAA4B,EAC5B,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,kCAAkC,GAMnC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,oCAAoC,EAAE,MAAM,4BAA4B,CAAC;AAClF,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAOhF,MAAM,kCAAkC;IAG7B,MAAM,CAAoD;IACnE,SAAS,CAAuD;IAChE,gBAAgB,GAA2C,IAAI,CAAC;IAChE,eAAe,CAAqB;IACpC,cAAc,GAA+B,EAAE,CAAC;IAChD,cAAc,GAAkB,IAAI,CAAC;IAC5B,SAAS,GAAG,IAAI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"../principalState\";\nimport { normalizeReferencedPrincipalHead } from \"./accessEvent\";\nimport {\n normalizeCanonicalJsonValue,\n serializeKeyingCanonicalJson,\n} from \"./canonical\";\nimport {\n normalizePrincipalHistoryInput,\n verifyPrincipalHistoryCheckpoint,\n} from \"./principalPolicyHistoryChecks\";\nimport { appendPrincipalHistoryIndex } from \"./principalPolicyHistoryIndex\";\nimport { verifyPrincipalHistoryPage } from \"./principalPolicyHistoryPage\";\nimport {\n normalizeAuthenticatedPrincipalHistoryProgress,\n type PrincipalHistoryProgress,\n} from \"./principalPolicyHistoryProgress\";\nimport {\n capturePrincipalHistoryAuthority,\n capturePrincipalHistoryProgressEntry,\n} from \"./principalPolicyHistoryProgressEntry\";\nimport {\n openPrincipalHistoryProgress,\n ownPrincipalHistoryProgressProtection,\n sealPrincipalHistoryProgress,\n} from \"./principalPolicyHistoryProgressProtection\";\nimport {\n makeVerifiedPrincipalPolicyHistory,\n type PrincipalPolicyHistoryInput,\n type PrincipalPolicyHistoryPage,\n type PrincipalPolicyHistoryProgressOptions,\n type PrincipalPolicyHistoryVerifier,\n type VerifiedPrincipalPolicyHistory,\n} from \"./principalPolicyHistoryTypes\";\nimport { principalPolicyStateMatchesReference } from \"./principalPolicyReference\";\nimport { runVerifier, throwVerification, toVerificationResult } from \"./shared\";\nimport type {\n KeyingVerificationResult,\n NormalizedPrincipalPolicyStateChainEntry,\n ReferencedPrincipalHead,\n} from \"./types\";\n\nclass PrincipalPolicyHistoryVerifierImpl\n implements PrincipalPolicyHistoryVerifier\n{\n readonly #input: ReturnType<typeof normalizePrincipalHistoryInput>;\n #previous: NormalizedPrincipalPolicyStateChainEntry | undefined;\n #latestAuthority: PrincipalStateExternalAuthority | null = null;\n #checkpointHash: string | undefined;\n #indexFrontier: readonly (string | null)[] = [];\n #indexRootHash: string | null = null;\n readonly #retained = new Map<\n number,\n NormalizedPrincipalPolicyStateChainEntry\n >();\n #appending = false;\n\n constructor(\n input: PrincipalPolicyHistoryInput,\n progress?: PrincipalHistoryProgress,\n ) {\n this.#input = normalizePrincipalHistoryInput(input);\n if (progress) {\n this.#previous = progress.previous ?? undefined;\n this.#latestAuthority = progress.latestAuthority;\n this.#checkpointHash = progress.checkpointHash ?? undefined;\n this.#indexFrontier = progress.indexFrontier;\n this.#indexRootHash = progress.indexRootHash;\n for (const entry of progress.retained)\n this.#retained.set(entry.state.version, entry);\n }\n }\n\n getExternalAuthorityReference(): ReferencedPrincipalHead | null {\n return this.#latestAuthority ? { ...this.#latestAuthority } : null;\n }\n\n append(page: PrincipalPolicyHistoryPage) {\n return runVerifier(async () => {\n this.#assertIdle();\n this.#appending = true;\n try {\n const verified = await verifyPrincipalHistoryPage({\n page,\n principalId: this.#input.principalId,\n principalType: this.#input.principalType,\n previous: this.#previous,\n latestAuthority: this.#latestAuthority,\n references: this.#input.references,\n checkpoint: this.#input.checkpoint,\n });\n const index = await appendPrincipalHistoryIndex(\n this.#indexFrontier,\n verified.entries.map((entry) => entry.state),\n );\n // Publish only after every check, including the final signature, passes.\n for (const entry of verified.entries) {\n if (entry.state.version === this.#input.checkpoint?.version)\n this.#checkpointHash = entry.state.stateHash;\n if (\n entry.state.version === this.#input.checkpoint?.version ||\n this.#input.references.some(\n (reference) => reference.version === entry.state.version,\n )\n )\n this.#retained.set(entry.state.version, entry);\n }\n this.#previous = verified.last;\n this.#latestAuthority = verified.latestAuthority;\n this.#indexFrontier = index.frontier;\n this.#indexRootHash = index.rootHash;\n return {\n throughVersion: verified.last.state.version,\n indexNodes: index.nodes,\n };\n } finally {\n this.#appending = false;\n }\n });\n }\n\n #assertIdle(): void {\n if (this.#appending)\n throwVerification(\n \"invalid_shape\",\n \"principal history append in progress\",\n );\n }\n\n exportProgress(options: PrincipalPolicyHistoryProgressOptions) {\n return runVerifier(async () => {\n this.#assertIdle();\n // Capture a complete accepted prefix before the first yield. A later\n // append cannot change this snapshot or publish a partial page into it.\n const plaintext = serializeKeyingCanonicalJson(\n normalizeCanonicalJsonValue(\n {\n previous: this.#previous\n ? capturePrincipalHistoryProgressEntry(this.#previous)\n : null,\n latestAuthority: this.#latestAuthority\n ? capturePrincipalHistoryAuthority(this.#latestAuthority)\n : null,\n checkpointHash: this.#checkpointHash ?? null,\n indexFrontier: this.#indexFrontier,\n retained: [...this.#retained.values()].map(\n capturePrincipalHistoryProgressEntry,\n ),\n },\n \"principal history progress\",\n ),\n );\n return sealPrincipalHistoryProgress(\n plaintext,\n ownPrincipalHistoryProgressProtection(this.#input, options),\n );\n });\n }\n\n finish(\n expectedHead: ReferencedPrincipalHead,\n ): KeyingVerificationResult<VerifiedPrincipalPolicyHistory> {\n try {\n this.#assertIdle();\n const reference = normalizeReferencedPrincipalHead(expectedHead);\n const previous = this.#previous;\n if (\n !previous ||\n !this.#indexRootHash ||\n !principalPolicyStateMatchesReference(previous.state, reference)\n )\n throwVerification(\n \"missing_dependency\",\n \"principal history has not reached the requested head\",\n );\n verifyPrincipalHistoryCheckpoint(\n previous.state,\n this.#input.checkpoint,\n this.#checkpointHash,\n );\n const history = new Map(this.#retained);\n history.set(previous.state.version, previous);\n const { state, projection, grants } = previous;\n const { principalId, principalType } = this.#input;\n const owned = structuredClone({\n indexRootHash: this.#indexRootHash,\n currentEntry: { state, projection, grants },\n retainedEntries: [...history.values()].sort(\n (left, right) => left.state.version - right.state.version,\n ),\n checkpoint: {\n principalId,\n principalType,\n version: state.version,\n stateHash: state.stateHash,\n },\n });\n return { ok: true, value: makeVerifiedPrincipalPolicyHistory(owned) };\n } catch (error) {\n return toVerificationResult(error);\n }\n }\n}\n\n/**\n * Verify from genesis with bounded retained state. A rejected page cannot\n * advance authorization or continuity. Progress is local to this verifier;\n * a remote cursor/checkpoint is never accepted as verified history.\n * Callers bound serialized page bytes and authenticate external authority.\n * Throws KeyingVerificationError for invalid local scope, checkpoint or references.\n */\nexport function createPrincipalPolicyHistoryVerifier(\n input: PrincipalPolicyHistoryInput,\n): PrincipalPolicyHistoryVerifier {\n const verifier = new PrincipalPolicyHistoryVerifierImpl(input);\n return publicVerifier(verifier);\n}\n\nfunction publicVerifier(\n verifier: PrincipalPolicyHistoryVerifierImpl,\n): PrincipalPolicyHistoryVerifier {\n return {\n getExternalAuthorityReference: () =>\n verifier.getExternalAuthorityReference(),\n append: (page: PrincipalPolicyHistoryPage) => verifier.append(page),\n finish: (expectedHead: ReferencedPrincipalHead) =>\n verifier.finish(expectedHead),\n exportProgress: (options: PrincipalPolicyHistoryProgressOptions) =>\n verifier.exportProgress(options),\n };\n}\n\n/** Restore only progress authenticated by this verifier's own local key. */\nexport function restorePrincipalPolicyHistoryVerifier(\n input: PrincipalPolicyHistoryInput,\n progress: string,\n protection: PrincipalPolicyHistoryProgressOptions,\n): Promise<KeyingVerificationResult<PrincipalPolicyHistoryVerifier>> {\n return runVerifier(async () => {\n const normalized = normalizePrincipalHistoryInput(input);\n const ownedInput: PrincipalPolicyHistoryInput = {\n principalId: normalized.principalId,\n principalType: normalized.principalType,\n localCheckpoint: normalized.checkpoint,\n retainedReferences: normalized.references,\n };\n const decoded = await openPrincipalHistoryProgress(\n progress,\n ownPrincipalHistoryProgressProtection(normalized, protection),\n );\n const authenticated = await normalizeAuthenticatedPrincipalHistoryProgress(\n decoded,\n normalized,\n );\n return publicVerifier(\n new PrincipalPolicyHistoryVerifierImpl(ownedInput, authenticated),\n );\n });\n}\n"]}
1
+ {"version":3,"file":"principalPolicyHistory.js","sourceRoot":"","sources":["principalPolicyHistory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gCAAgC,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,8BAA8B,EAC9B,gCAAgC,GACjC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EACL,8CAA8C,GAE/C,MAA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I,EAAE;QAC5B,MAAM,UAAU,GAAG,8BAA8B,CAAC,KAAK,CAAC,CAAC;QACzD,MAAM,UAAU,GAAgC;YAC9C,WAAW,EAAE,UAAU,CAAC,WAAW;YACnC,aAAa,EAAE,UAAU,CAAC,aAAa;YACvC,eAAe,EAAE,UAAU,CAAC,UAAU;YACtC,kBAAkB,EAAE,UAAU,CAAC,UAAU;SAC1C,CAAC;QACF,MAAM,OAAO,GAAG,MAAM,4BAA4B,CAChD,QAAQ,EACR,qCAAqC,CAAC,UAAU,EAAE,UAAU,CAAC,CAC9D,CAAC;QACF,MAAM,aAAa,GAAG,MAAM,8CAA8C,CACxE,OAAO,EACP,UAAU,CACX,CAAC;QACF,OAAO,cAAc,CACnB,IAAI,kCAAkC,CAAC,UAAU,EAAE,aAAa,CAAC,CAClE,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalStateExternalAuthority } from \"../principalState\";\nimport { normalizeReferencedPrincipalHead } from \"./accessEvent\";\nimport {\n normalizeCanonicalJsonValue,\n serializeKeyingCanonicalJson,\n} from \"./canonical\";\nimport {\n normalizePrincipalHistoryInput,\n verifyPrincipalHistoryCheckpoint,\n} from \"./principalPolicyHistoryChecks\";\nimport { appendPrincipalHistoryIndex } from \"./principalPolicyHistoryIndex\";\nimport { verifyPrincipalHistoryPage } from \"./principalPolicyHistoryPage\";\nimport {\n normalizeAuthenticatedPrincipalHistoryProgress,\n type PrincipalHistoryProgress,\n} from \"./principalPolicyHistoryProgress\";\nimport {\n capturePrincipalHistoryAuthority,\n capturePrincipalHistoryProgressEntry,\n} from \"./principalPolicyHistoryProgressEntry\";\nimport {\n openPrincipalHistoryProgress,\n ownPrincipalHistoryProgressProtection,\n sealPrincipalHistoryProgress,\n} from \"./principalPolicyHistoryProgressProtection\";\nimport {\n makeVerifiedPrincipalPolicyHistory,\n type PrincipalPolicyHistoryInput,\n type PrincipalPolicyHistoryPage,\n type PrincipalPolicyHistoryProgressOptions,\n type PrincipalPolicyHistoryVerifier,\n type VerifiedPrincipalPolicyHistory,\n} from \"./principalPolicyHistoryTypes\";\nimport { principalPolicyStateMatchesReference } from \"./principalPolicyReference\";\nimport { runVerifier, throwVerification, toVerificationResult } from \"./shared\";\nimport type {\n KeyingVerificationResult,\n NormalizedPrincipalPolicyStateChainEntry,\n ReferencedPrincipalHead,\n} from \"./types\";\n\nclass PrincipalPolicyHistoryVerifierImpl\n implements PrincipalPolicyHistoryVerifier\n{\n readonly #input: ReturnType<typeof normalizePrincipalHistoryInput>;\n #previous: NormalizedPrincipalPolicyStateChainEntry | undefined;\n #latestAuthority: PrincipalStateExternalAuthority | null = null;\n #checkpointHash: string | undefined;\n #indexFrontier: readonly (string | null)[] = [];\n #indexRootHash: string | null = null;\n readonly #retained = new Map<\n number,\n NormalizedPrincipalPolicyStateChainEntry\n >();\n #appending = false;\n\n constructor(\n input: PrincipalPolicyHistoryInput,\n progress?: PrincipalHistoryProgress,\n ) {\n this.#input = normalizePrincipalHistoryInput(input);\n if (progress) {\n this.#previous = progress.previous ?? undefined;\n this.#latestAuthority = progress.latestAuthority;\n this.#checkpointHash = progress.checkpointHash ?? undefined;\n this.#indexFrontier = progress.indexFrontier;\n this.#indexRootHash = progress.indexRootHash;\n for (const entry of progress.retained)\n this.#retained.set(entry.state.version, entry);\n }\n }\n\n getExternalAuthorityReference(): ReferencedPrincipalHead | null {\n return this.#latestAuthority ? { ...this.#latestAuthority } : null;\n }\n\n append(page: PrincipalPolicyHistoryPage) {\n return runVerifier(async () => {\n this.#assertIdle();\n this.#appending = true;\n try {\n const verified = await verifyPrincipalHistoryPage({\n page,\n principalId: this.#input.principalId,\n principalType: this.#input.principalType,\n previous: this.#previous,\n latestAuthority: this.#latestAuthority,\n references: this.#input.references,\n checkpoint: this.#input.checkpoint,\n });\n const index = await appendPrincipalHistoryIndex(\n this.#indexFrontier,\n verified.entries.map((entry) => entry.state),\n );\n // Publish only after every check, including the final signature, passes.\n for (const entry of verified.entries) {\n if (entry.state.version === this.#input.checkpoint?.version)\n this.#checkpointHash = entry.state.stateHash;\n if (\n entry.state.version === this.#input.checkpoint?.version ||\n this.#input.references.some(\n (reference) => reference.version === entry.state.version,\n )\n )\n this.#retained.set(entry.state.version, entry);\n }\n this.#previous = verified.last;\n this.#latestAuthority = verified.latestAuthority;\n this.#indexFrontier = index.frontier;\n this.#indexRootHash = index.rootHash;\n return {\n throughVersion: verified.last.state.version,\n indexNodes: index.nodes,\n };\n } finally {\n this.#appending = false;\n }\n });\n }\n\n #assertIdle(): void {\n if (this.#appending)\n throwVerification(\n \"invalid_shape\",\n \"principal history append in progress\",\n );\n }\n\n exportProgress(options: PrincipalPolicyHistoryProgressOptions) {\n return runVerifier(async () => {\n this.#assertIdle();\n // Capture a complete accepted prefix before the first yield. A later\n // append cannot change this snapshot or publish a partial page into it.\n const plaintext = serializeKeyingCanonicalJson(\n normalizeCanonicalJsonValue(\n {\n previous: this.#previous\n ? capturePrincipalHistoryProgressEntry(this.#previous)\n : null,\n latestAuthority: this.#latestAuthority\n ? capturePrincipalHistoryAuthority(this.#latestAuthority)\n : null,\n checkpointHash: this.#checkpointHash ?? null,\n indexFrontier: this.#indexFrontier,\n retained: [...this.#retained.values()].map(\n capturePrincipalHistoryProgressEntry,\n ),\n },\n \"principal history progress\",\n ),\n );\n return sealPrincipalHistoryProgress(\n plaintext,\n ownPrincipalHistoryProgressProtection(this.#input, options),\n );\n });\n }\n\n finish(\n expectedHead: ReferencedPrincipalHead,\n ): KeyingVerificationResult<VerifiedPrincipalPolicyHistory> {\n try {\n this.#assertIdle();\n const reference = normalizeReferencedPrincipalHead(expectedHead);\n const previous = this.#previous;\n if (\n !previous ||\n !this.#indexRootHash ||\n !principalPolicyStateMatchesReference(previous.state, reference)\n )\n throwVerification(\n \"missing_dependency\",\n \"principal history has not reached the requested head\",\n );\n verifyPrincipalHistoryCheckpoint(\n previous.state,\n this.#input.checkpoint,\n this.#checkpointHash,\n );\n const history = new Map(this.#retained);\n history.set(previous.state.version, previous);\n const { state, projection, grants } = previous;\n const { principalId, principalType } = this.#input;\n const owned = structuredClone({\n indexRootHash: this.#indexRootHash,\n currentEntry: { state, projection, grants },\n retainedEntries: [...history.values()].sort(\n (left, right) => left.state.version - right.state.version,\n ),\n checkpoint: {\n principalId,\n principalType,\n version: state.version,\n stateHash: state.stateHash,\n },\n });\n return {\n ok: true,\n value: makeVerifiedPrincipalPolicyHistory(owned, this.#latestAuthority),\n };\n } catch (error) {\n return toVerificationResult(error);\n }\n }\n}\n\n/**\n * Verify from genesis with bounded retained state. A rejected page cannot\n * advance authorization or continuity. Progress is local to this verifier;\n * a remote cursor/checkpoint is never accepted as verified history.\n * Callers bound serialized page bytes and authenticate external authority.\n * Throws KeyingVerificationError for invalid local scope, checkpoint or references.\n */\nexport function createPrincipalPolicyHistoryVerifier(\n input: PrincipalPolicyHistoryInput,\n): PrincipalPolicyHistoryVerifier {\n const verifier = new PrincipalPolicyHistoryVerifierImpl(input);\n return publicVerifier(verifier);\n}\n\nfunction publicVerifier(\n verifier: PrincipalPolicyHistoryVerifierImpl,\n): PrincipalPolicyHistoryVerifier {\n return {\n getExternalAuthorityReference: () =>\n verifier.getExternalAuthorityReference(),\n append: (page: PrincipalPolicyHistoryPage) => verifier.append(page),\n finish: (expectedHead: ReferencedPrincipalHead) =>\n verifier.finish(expectedHead),\n exportProgress: (options: PrincipalPolicyHistoryProgressOptions) =>\n verifier.exportProgress(options),\n };\n}\n\n/** Restore only progress authenticated by this verifier's own local key. */\nexport function restorePrincipalPolicyHistoryVerifier(\n input: PrincipalPolicyHistoryInput,\n progress: string,\n protection: PrincipalPolicyHistoryProgressOptions,\n): Promise<KeyingVerificationResult<PrincipalPolicyHistoryVerifier>> {\n return runVerifier(async () => {\n const normalized = normalizePrincipalHistoryInput(input);\n const ownedInput: PrincipalPolicyHistoryInput = {\n principalId: normalized.principalId,\n principalType: normalized.principalType,\n localCheckpoint: normalized.checkpoint,\n retainedReferences: normalized.references,\n };\n const decoded = await openPrincipalHistoryProgress(\n progress,\n ownPrincipalHistoryProgressProtection(normalized, protection),\n );\n const authenticated = await normalizeAuthenticatedPrincipalHistoryProgress(\n decoded,\n normalized,\n );\n return publicVerifier(\n new PrincipalPolicyHistoryVerifierImpl(ownedInput, authenticated),\n );\n });\n}\n"]}
@@ -75,7 +75,7 @@ export function verifyPrincipalPolicyHistoryReferences(input) {
75
75
  return makeVerifiedPrincipalPolicyHistory({
76
76
  ...history,
77
77
  retainedEntries: [...entries.values()].sort((left, right) => left.state.version - right.state.version),
78
- });
78
+ }, history.latestAuthority);
79
79
  });
80
80
  }
81
81
  //# sourceMappingURL=principalPolicyHistoryReferences.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyHistoryReferences.js","sourceRoot":"","sources":["principalPolicyHistoryReferences.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uCAAuC,EAAE,MAAM,6BAA6B,CAAC;AACtF,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAAC;AAChF,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EACL,kCAAkC,EAClC,iCAAiC,EACjC,kCAAkC,GAEnC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,oCAAoC,EAAE,MAAM,4BAA4B,CAAC;AAClF,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC1D,OAAO,EACL,2BAA2B,EAC3B,mCAAmC,GACpC,MAAM,sBAAsB,CAAC;AAe9B,SAAS,iBAAiB,CACxB,UAA2D;IAE3D,IACE,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC;QAC1B,UAAU,CAAC,MAAM,GAAG,kCAAkC;QAEtD,iBAAiB,CAAC,eAAe,EAAE,mCAAmC,CAAC,CAAC;IAC1E,MAAM,KAAK,GAAG,UAAU,CAAC,MAAM,CAAC;IAChC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG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CAAC;YACxC,GAAG,OAAO;YACV,eAAe,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CACzC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAC1D;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { normalizePrincipalPolicyStateChainEntry } from \"./principalPolicyChainEntry\";\nimport { normalizePrincipalHistoryInput } from \"./principalPolicyHistoryChecks\";\nimport { principalHistoryIndexLeaf } from \"./principalPolicyHistoryIndex\";\nimport {\n makeVerifiedPrincipalPolicyHistory,\n ownVerifiedPrincipalPolicyHistory,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type VerifiedPrincipalPolicyHistory,\n} from \"./principalPolicyHistoryTypes\";\nimport { principalPolicyStateMatchesReference } from \"./principalPolicyReference\";\nimport { runVerifier, throwVerification } from \"./shared\";\nimport {\n assertTransparencyInclusion,\n normalizeTransparencyInclusionProof,\n} from \"./transparencyProofs\";\nimport type {\n KeyingVerificationResult,\n PrincipalPolicyStateChainEntry,\n ReferencedPrincipalHead,\n TransparencyInclusionProof,\n} from \"./types\";\n\n/** Untrusted material to select an entry from a locally verified prefix. */\nexport interface PrincipalPolicyHistoryReferenceProof {\n readonly reference: ReferencedPrincipalHead;\n readonly entry: PrincipalPolicyStateChainEntry;\n readonly proof: TransparencyInclusionProof;\n}\n\nfunction assertProofBudget(\n references: readonly PrincipalPolicyHistoryReferenceProof[],\n): void {\n if (\n !Array.isArray(references) ||\n references.length > PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT\n )\n throwVerification(\"invalid_shape\", \"too many principal history proofs\");\n const count = references.length;\n for (let index = 0; index < count; index += 1) {\n const path = references[index]?.proof.auditPath;\n if (!Array.isArray(path) || path.length > 53)\n throwVerification(\n \"invalid_shape\",\n \"principal history proof exceeds its budget\",\n );\n }\n}\n\n/**\n * Select new retained references without replaying signatures. Inclusion is\n * checked against the private root owned by a local verifier, never a peer's\n * claimed root. Each leaf commits to the exact signed entry already accepted.\n * Replaces the retained selection; the current entry is always included.\n * A separate checkpoint proof preserves the full 128-citation selection budget.\n */\nexport function verifyPrincipalPolicyHistoryReferences(input: {\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly references: readonly PrincipalPolicyHistoryReferenceProof[];\n readonly checkpointReference?:\n | PrincipalPolicyHistoryReferenceProof\n | undefined;\n}): Promise<KeyingVerificationResult<VerifiedPrincipalPolicyHistory>> {\n return runVerifier(async () => {\n const history = ownVerifiedPrincipalPolicyHistory(input.history);\n const supplied = input.references;\n const suppliedCheckpoint = input.checkpointReference;\n assertProofBudget(supplied);\n if (suppliedCheckpoint !== undefined)\n assertProofBudget([suppliedCheckpoint]);\n const references = structuredClone(supplied);\n const checkpoint = structuredClone(suppliedCheckpoint);\n assertProofBudget(references);\n const scope = {\n principalId: history.currentEntry.state.principalId,\n principalType: history.currentEntry.state.principalType,\n };\n normalizePrincipalHistoryInput({\n ...scope,\n retainedReferences: references.map((item) => item.reference),\n });\n const selected = [...references];\n if (checkpoint !== undefined) {\n assertProofBudget([checkpoint]);\n normalizePrincipalHistoryInput({\n ...scope,\n retainedReferences: [checkpoint.reference],\n });\n selected.push(checkpoint);\n }\n const entries = new Map<number, PrincipalPolicyStateChainEntry>();\n const treeSize = history.currentEntry.state.version;\n for (const item of selected) {\n const entry = await normalizePrincipalPolicyStateChainEntry(item.entry);\n const proof = normalizeTransparencyInclusionProof(item.proof);\n if (\n !principalPolicyStateMatchesReference(entry.state, item.reference) ||\n entry.state.version > treeSize ||\n proof.leafIndex !== entry.state.version - 1\n )\n throwVerification(\n \"object_mismatch\",\n \"principal history proof reference mismatch\",\n );\n await assertTransparencyInclusion({\n leafHash: await principalHistoryIndexLeaf(entry.state),\n checkpoint: {\n logId: \"principal-history\",\n rootHash: history.indexRootHash,\n treeSize,\n },\n proof,\n });\n entries.set(entry.state.version, entry);\n }\n entries.set(treeSize, history.currentEntry);\n return makeVerifiedPrincipalPolicyHistory({\n ...history,\n retainedEntries: [...entries.values()].sort(\n (left, right) => left.state.version - right.state.version,\n ),\n });\n });\n}\n"]}
1
+ {"version":3,"file":"principalPolicyHistoryReferences.js","sourceRoot":"","sources":["principalPolicyHistoryReferences.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uCAAuC,EAAE,MAAM,6BAA6B,CAAC;AACtF,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAAC;AAChF,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EACL,kCAAkC,EAClC,iCAAiC,EACjC,kCAAkC,GAEnC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,oCAAoC,EAAE,MAAM,4BAA4B,CAAC;AAClF,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC1D,OAAO,EACL,2BAA2B,EAC3B,mCAAmC,GACpC,MAAM,sBAAsB,CAAC;AAe9B,SAAS,iBAAiB,CACxB,UAA2D;IAE3D,IACE,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC;QAC1B,UAAU,CAAC,MAAM,GAAG,kCAAkC;QAEtD,iBAAiB,CAAC,eAAe,EAAE,mCAAmC,CAAC,CAAC;IAC1E,MAAM,KAAK,GAAG,UAAU,CAAC,MAAM,CAAC;IAChC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;QAC9C,MAAM,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;QAChD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,GAAG,EAAE;YAC1C,iBAAiB,CACf,eAAe,EACf,4CAA4C,CAC7C,CAAC;IACN,CAA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AAC;AACL,CAAC","sourcesContent":["import { normalizePrincipalPolicyStateChainEntry } from \"./principalPolicyChainEntry\";\nimport { normalizePrincipalHistoryInput } from \"./principalPolicyHistoryChecks\";\nimport { principalHistoryIndexLeaf } from \"./principalPolicyHistoryIndex\";\nimport {\n makeVerifiedPrincipalPolicyHistory,\n ownVerifiedPrincipalPolicyHistory,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type VerifiedPrincipalPolicyHistory,\n} from \"./principalPolicyHistoryTypes\";\nimport { principalPolicyStateMatchesReference } from \"./principalPolicyReference\";\nimport { runVerifier, throwVerification } from \"./shared\";\nimport {\n assertTransparencyInclusion,\n normalizeTransparencyInclusionProof,\n} from \"./transparencyProofs\";\nimport type {\n KeyingVerificationResult,\n PrincipalPolicyStateChainEntry,\n ReferencedPrincipalHead,\n TransparencyInclusionProof,\n} from \"./types\";\n\n/** Untrusted material to select an entry from a locally verified prefix. */\nexport interface PrincipalPolicyHistoryReferenceProof {\n readonly reference: ReferencedPrincipalHead;\n readonly entry: PrincipalPolicyStateChainEntry;\n readonly proof: TransparencyInclusionProof;\n}\n\nfunction assertProofBudget(\n references: readonly PrincipalPolicyHistoryReferenceProof[],\n): void {\n if (\n !Array.isArray(references) ||\n references.length > PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT\n )\n throwVerification(\"invalid_shape\", \"too many principal history proofs\");\n const count = references.length;\n for (let index = 0; index < count; index += 1) {\n const path = references[index]?.proof.auditPath;\n if (!Array.isArray(path) || path.length > 53)\n throwVerification(\n \"invalid_shape\",\n \"principal history proof exceeds its budget\",\n );\n }\n}\n\n/**\n * Select new retained references without replaying signatures. Inclusion is\n * checked against the private root owned by a local verifier, never a peer's\n * claimed root. Each leaf commits to the exact signed entry already accepted.\n * Replaces the retained selection; the current entry is always included.\n * A separate checkpoint proof preserves the full 128-citation selection budget.\n */\nexport function verifyPrincipalPolicyHistoryReferences(input: {\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly references: readonly PrincipalPolicyHistoryReferenceProof[];\n readonly checkpointReference?:\n | PrincipalPolicyHistoryReferenceProof\n | undefined;\n}): Promise<KeyingVerificationResult<VerifiedPrincipalPolicyHistory>> {\n return runVerifier(async () => {\n const history = ownVerifiedPrincipalPolicyHistory(input.history);\n const supplied = input.references;\n const suppliedCheckpoint = input.checkpointReference;\n assertProofBudget(supplied);\n if (suppliedCheckpoint !== undefined)\n assertProofBudget([suppliedCheckpoint]);\n const references = structuredClone(supplied);\n const checkpoint = structuredClone(suppliedCheckpoint);\n assertProofBudget(references);\n const scope = {\n principalId: history.currentEntry.state.principalId,\n principalType: history.currentEntry.state.principalType,\n };\n normalizePrincipalHistoryInput({\n ...scope,\n retainedReferences: references.map((item) => item.reference),\n });\n const selected = [...references];\n if (checkpoint !== undefined) {\n assertProofBudget([checkpoint]);\n normalizePrincipalHistoryInput({\n ...scope,\n retainedReferences: [checkpoint.reference],\n });\n selected.push(checkpoint);\n }\n const entries = new Map<number, PrincipalPolicyStateChainEntry>();\n const treeSize = history.currentEntry.state.version;\n for (const item of selected) {\n const entry = await normalizePrincipalPolicyStateChainEntry(item.entry);\n const proof = normalizeTransparencyInclusionProof(item.proof);\n if (\n !principalPolicyStateMatchesReference(entry.state, item.reference) ||\n entry.state.version > treeSize ||\n proof.leafIndex !== entry.state.version - 1\n )\n throwVerification(\n \"object_mismatch\",\n \"principal history proof reference mismatch\",\n );\n await assertTransparencyInclusion({\n leafHash: await principalHistoryIndexLeaf(entry.state),\n checkpoint: {\n logId: \"principal-history\",\n rootHash: history.indexRootHash,\n treeSize,\n },\n proof,\n });\n entries.set(entry.state.version, entry);\n }\n entries.set(treeSize, history.currentEntry);\n return makeVerifiedPrincipalPolicyHistory(\n {\n ...history,\n retainedEntries: [...entries.values()].sort(\n (left, right) => left.state.version - right.state.version,\n ),\n },\n history.latestAuthority,\n );\n });\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import type { PrincipalStateExternalAuthority } from "../principalState.js";
1
2
  import type { PrincipalPolicyExternalAuthority } from "./principalPolicyExternalAuthorityTypes.js";
2
3
  import type { PrincipalHistoryIndexNode } from "./principalPolicyHistoryIndex.js";
3
4
  import type { KeyingVerificationResult, PrincipalPolicyCheckpoint, PrincipalPolicySignerPublicKey, PrincipalPolicyStateChainEntry, ReferencedPrincipalHead } from "./types.js";
@@ -32,8 +33,10 @@ export interface VerifiedPrincipalPolicyHistory {
32
33
  /** Computed only from locally accepted entries; never supplied by a peer. */
33
34
  readonly indexRootHash: string;
34
35
  }
35
- type HistorySnapshot = Omit<VerifiedPrincipalPolicyHistory, typeof verifiedHistoryBrand>;
36
- export declare function makeVerifiedPrincipalPolicyHistory(value: Omit<VerifiedPrincipalPolicyHistory, typeof verifiedHistoryBrand>): VerifiedPrincipalPolicyHistory;
36
+ type HistorySnapshot = Omit<VerifiedPrincipalPolicyHistory, typeof verifiedHistoryBrand> & {
37
+ readonly latestAuthority: PrincipalStateExternalAuthority | null;
38
+ };
39
+ export declare function makeVerifiedPrincipalPolicyHistory(value: Omit<VerifiedPrincipalPolicyHistory, typeof verifiedHistoryBrand>, latestAuthority: PrincipalStateExternalAuthority | null): VerifiedPrincipalPolicyHistory;
37
40
  export declare function ownVerifiedPrincipalPolicyHistory(history: VerifiedPrincipalPolicyHistory): HistorySnapshot;
38
41
  export interface PrincipalPolicyHistoryVerifier {
39
42
  /** Owned copy of the latest accepted citation, including across uncited pages. */
@@ -4,12 +4,15 @@ const verifiedHistoryBrand = Symbol("verifiedPrincipalPolicyHistory");
4
4
  // Public copies are useful for inspection, but their fields are not authority.
5
5
  // A later verifier consumes the privately held snapshot issued by finish().
6
6
  const issuedHistories = new WeakMap();
7
- export function makeVerifiedPrincipalPolicyHistory(value) {
7
+ export function makeVerifiedPrincipalPolicyHistory(value, latestAuthority) {
8
8
  const result = {
9
- ...value,
9
+ currentEntry: value.currentEntry,
10
+ retainedEntries: value.retainedEntries,
11
+ checkpoint: value.checkpoint,
12
+ indexRootHash: value.indexRootHash,
10
13
  [verifiedHistoryBrand]: true,
11
14
  };
12
- issuedHistories.set(result, structuredClone(value));
15
+ issuedHistories.set(result, structuredClone({ ...value, latestAuthority }));
13
16
  return result;
14
17
  }
15
18
  export function ownVerifiedPrincipalPolicyHistory(history) {
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyHistoryTypes.js","sourceRoot":"","sources":["principalPolicyHistoryTypes.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAS7C,MAAM,CAAC,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAyBtD,MAAM,oBAAoB,GAAkB,MAAM,CAChD,gCAAgC,CACjC,CAAC;AAiBF,+EAA+E;AAC/E,4EAA4E;AAC5E,MAAM,eAAe,GAAG,IAAI,OAAO,EAGhC,CAAC;AAEJ,MAAM,UAAU,kCAAkC,CAChD,KAAwE;IAExE,MAAM,MAAM,GAAmC;QAC7C,GAAG,KAAK;QACR,CAAC,oBAAoB,CAAC,EAAE,IAAI;KAC7B,CAAC;IACF,eAAe,CAAC,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;IACpD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,OAAuC;IAEvC,MAAM,QAAQ,GAAG,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC9C,IAAI,CAAC,QAAQ;QACX,iBAAiB,CACf,eAAe,EACf,mDAAmD,CACpD,CAAC;IACJ,OAAO,eAAe,CAAC,QAAQ,CAAC,CAAC;AACnC,CAAC","sourcesContent":["import type { PrincipalPolicyExternalAuthority } from \"./principalPolicyExternalAuthorityTypes\";\nimport type { PrincipalHistoryIndexNode } from \"./principalPolicyHistoryIndex\";\nimport { throwVerification } from \"./shared\";\nimport type {\n KeyingVerificationResult,\n PrincipalPolicyCheckpoint,\n PrincipalPolicySignerPublicKey,\n PrincipalPolicyStateChainEntry,\n ReferencedPrincipalHead,\n} from \"./types\";\n\nexport const PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT = 128;\n\n/** A crypto verification batch, not a wire-response DTO. */\nexport interface PrincipalPolicyHistoryPage {\n readonly entries: readonly PrincipalPolicyStateChainEntry[];\n /** Keys resolved through the caller's trusted user-identity mechanism. */\n readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];\n /** Already authenticated authority; never trust a server page directly. */\n readonly externalAuthority?: PrincipalPolicyExternalAuthority;\n}\n\nexport interface PrincipalPolicyHistoryInput {\n readonly principalId: string;\n readonly principalType: ReferencedPrincipalHead[\"principalType\"];\n readonly localCheckpoint?: PrincipalPolicyCheckpoint | null;\n readonly retainedReferences?: readonly ReferencedPrincipalHead[];\n}\n\n/** Local verifier protection; never obtain this key from a remote API. */\nexport interface PrincipalPolicyHistoryProgressOptions {\n readonly localKey: Uint8Array;\n /** Stable local operation identity, bound into authenticated progress. */\n readonly context: string;\n}\n\nconst verifiedHistoryBrand: unique symbol = Symbol(\n \"verifiedPrincipalPolicyHistory\",\n);\n\n/** A verified prefix with explicitly retained references, not a full snapshot. */\nexport interface VerifiedPrincipalPolicyHistory {\n readonly [verifiedHistoryBrand]: true;\n readonly currentEntry: PrincipalPolicyStateChainEntry;\n readonly retainedEntries: readonly PrincipalPolicyStateChainEntry[];\n readonly checkpoint: PrincipalPolicyCheckpoint;\n /** Computed only from locally accepted entries; never supplied by a peer. */\n readonly indexRootHash: string;\n}\n\ntype HistorySnapshot = Omit<\n VerifiedPrincipalPolicyHistory,\n typeof verifiedHistoryBrand\n>;\n\n// Public copies are useful for inspection, but their fields are not authority.\n// A later verifier consumes the privately held snapshot issued by finish().\nconst issuedHistories = new WeakMap<\n VerifiedPrincipalPolicyHistory,\n HistorySnapshot\n>();\n\nexport function makeVerifiedPrincipalPolicyHistory(\n value: Omit<VerifiedPrincipalPolicyHistory, typeof verifiedHistoryBrand>,\n): VerifiedPrincipalPolicyHistory {\n const result: VerifiedPrincipalPolicyHistory = {\n ...value,\n [verifiedHistoryBrand]: true,\n };\n issuedHistories.set(result, structuredClone(value));\n return result;\n}\n\nexport function ownVerifiedPrincipalPolicyHistory(\n history: VerifiedPrincipalPolicyHistory,\n): HistorySnapshot {\n const snapshot = issuedHistories.get(history);\n if (!snapshot)\n throwVerification(\n \"invalid_shape\",\n \"principal history must come from a local verifier\",\n );\n return structuredClone(snapshot);\n}\n\nexport interface PrincipalPolicyHistoryVerifier {\n /** Owned copy of the latest accepted citation, including across uncited pages. */\n getExternalAuthorityReference(): ReferencedPrincipalHead | null;\n append(page: PrincipalPolicyHistoryPage): Promise<\n KeyingVerificationResult<{\n readonly throughVersion: number;\n readonly indexNodes: readonly PrincipalHistoryIndexNode[];\n }>\n >;\n finish(\n expectedHead: ReferencedPrincipalHead,\n ): KeyingVerificationResult<VerifiedPrincipalPolicyHistory>;\n exportProgress(\n options: PrincipalPolicyHistoryProgressOptions,\n ): Promise<KeyingVerificationResult<string>>;\n}\n"]}
1
+ {"version":3,"file":"principalPolicyHistoryTypes.js","sourceRoot":"","sources":["principalPolicyHistoryTypes.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAS7C,MAAM,CAAC,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAyBtD,MAAM,oBAAoB,GAAkB,MAAM,CAChD,gCAAgC,CACjC,CAAC;AAiBF,+EAA+E;AAC/E,4EAA4E;AAC5E,MAAM,eAAe,GAAG,IAAI,OAAO,EAGhC,CAAC;AAEJ,MAAM,UAAU,kCAAkC,CAChD,KAAwE,EACxE,eAAuD;IAEvD,MAAM,MAAM,GAAmC;QAC7C,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,CAAC,oBAAoB,CAAC,EAAE,IAAI;KAC7B,CAAC;IACF,eAAe,CAAC,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,EAAE,GAAG,KAAK,EAAE,eAAe,EAAE,CAAC,CAAC,CAAC;IAC5E,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,OAAuC;IAEvC,MAAM,QAAQ,GAAG,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC9C,IAAI,CAAC,QAAQ;QACX,iBAAiB,CACf,eAAe,EACf,mDAAmD,CACpD,CAAC;IACJ,OAAO,eAAe,CAAC,QAAQ,CAAC,CAAC;AACnC,CAAC","sourcesContent":["import type { PrincipalStateExternalAuthority } from \"../principalState\";\nimport type { PrincipalPolicyExternalAuthority } from \"./principalPolicyExternalAuthorityTypes\";\nimport type { PrincipalHistoryIndexNode } from \"./principalPolicyHistoryIndex\";\nimport { throwVerification } from \"./shared\";\nimport type {\n KeyingVerificationResult,\n PrincipalPolicyCheckpoint,\n PrincipalPolicySignerPublicKey,\n PrincipalPolicyStateChainEntry,\n ReferencedPrincipalHead,\n} from \"./types\";\n\nexport const PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT = 128;\n\n/** A crypto verification batch, not a wire-response DTO. */\nexport interface PrincipalPolicyHistoryPage {\n readonly entries: readonly PrincipalPolicyStateChainEntry[];\n /** Keys resolved through the caller's trusted user-identity mechanism. */\n readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];\n /** Already authenticated authority; never trust a server page directly. */\n readonly externalAuthority?: PrincipalPolicyExternalAuthority;\n}\n\nexport interface PrincipalPolicyHistoryInput {\n readonly principalId: string;\n readonly principalType: ReferencedPrincipalHead[\"principalType\"];\n readonly localCheckpoint?: PrincipalPolicyCheckpoint | null;\n readonly retainedReferences?: readonly ReferencedPrincipalHead[];\n}\n\n/** Local verifier protection; never obtain this key from a remote API. */\nexport interface PrincipalPolicyHistoryProgressOptions {\n readonly localKey: Uint8Array;\n /** Stable local operation identity, bound into authenticated progress. */\n readonly context: string;\n}\n\nconst verifiedHistoryBrand: unique symbol = Symbol(\n \"verifiedPrincipalPolicyHistory\",\n);\n\n/** A verified prefix with explicitly retained references, not a full snapshot. */\nexport interface VerifiedPrincipalPolicyHistory {\n readonly [verifiedHistoryBrand]: true;\n readonly currentEntry: PrincipalPolicyStateChainEntry;\n readonly retainedEntries: readonly PrincipalPolicyStateChainEntry[];\n readonly checkpoint: PrincipalPolicyCheckpoint;\n /** Computed only from locally accepted entries; never supplied by a peer. */\n readonly indexRootHash: string;\n}\n\ntype HistorySnapshot = Omit<\n VerifiedPrincipalPolicyHistory,\n typeof verifiedHistoryBrand\n> & { readonly latestAuthority: PrincipalStateExternalAuthority | null };\n\n// Public copies are useful for inspection, but their fields are not authority.\n// A later verifier consumes the privately held snapshot issued by finish().\nconst issuedHistories = new WeakMap<\n VerifiedPrincipalPolicyHistory,\n HistorySnapshot\n>();\n\nexport function makeVerifiedPrincipalPolicyHistory(\n value: Omit<VerifiedPrincipalPolicyHistory, typeof verifiedHistoryBrand>,\n latestAuthority: PrincipalStateExternalAuthority | null,\n): VerifiedPrincipalPolicyHistory {\n const result: VerifiedPrincipalPolicyHistory = {\n currentEntry: value.currentEntry,\n retainedEntries: value.retainedEntries,\n checkpoint: value.checkpoint,\n indexRootHash: value.indexRootHash,\n [verifiedHistoryBrand]: true,\n };\n issuedHistories.set(result, structuredClone({ ...value, latestAuthority }));\n return result;\n}\n\nexport function ownVerifiedPrincipalPolicyHistory(\n history: VerifiedPrincipalPolicyHistory,\n): HistorySnapshot {\n const snapshot = issuedHistories.get(history);\n if (!snapshot)\n throwVerification(\n \"invalid_shape\",\n \"principal history must come from a local verifier\",\n );\n return structuredClone(snapshot);\n}\n\nexport interface PrincipalPolicyHistoryVerifier {\n /** Owned copy of the latest accepted citation, including across uncited pages. */\n getExternalAuthorityReference(): ReferencedPrincipalHead | null;\n append(page: PrincipalPolicyHistoryPage): Promise<\n KeyingVerificationResult<{\n readonly throughVersion: number;\n readonly indexNodes: readonly PrincipalHistoryIndexNode[];\n }>\n >;\n finish(\n expectedHead: ReferencedPrincipalHead,\n ): KeyingVerificationResult<VerifiedPrincipalPolicyHistory>;\n exportProgress(\n options: PrincipalPolicyHistoryProgressOptions,\n ): Promise<KeyingVerificationResult<string>>;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.15",
3
+ "version": "0.1.16",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -98,6 +98,7 @@ async function commitMissingGroupGrantPolicy(input) {
98
98
  throw new Error("Container group share requires principal policy signing context");
99
99
  }
100
100
  const policyApi = {
101
+ recoverPendingPrincipalMutation: input.apiClient.recoverPendingPrincipalMutation?.bind(input.apiClient),
101
102
  commitOrganizationGroupPolicy: input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),
102
103
  getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(input.apiClient),
103
104
  };
@@ -198,6 +199,9 @@ function loadShareGroupPolicy(input) {
198
199
  });
199
200
  }
200
201
  export async function shareRemoteContainerWithGroup(input) {
202
+ if (input.stillCurrent?.() === false)
203
+ return null;
204
+ await input.apiClient.recoverPendingPrincipalMutation?.(input.author.organizationId);
201
205
  if (input.stillCurrent?.() === false)
202
206
  return null;
203
207
  const resolveProjectionUserKey = requireProjectionUserKeyResolver(input.resolveProjectionUserKey, "Remote container share");
@@ -1 +1 @@
1
- {"version":3,"file":"share.js","sourceRoot":"","sources":["share.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,sCAAsC,EACtC,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,uCAAuC,EAAE,MAAM,iEAAiE,CAAC;AAC1H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AAGjG,OAAO,EACL,kCAAkC,GAEnC,MA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CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QACrC,MAAM,yBAAyB,CAC7B,KAAK,CAAC,OAAO,EACb,uBAAuB,CAAC,MAAM,EAC9B,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACxB,KAAK,CAAC,MAAM,CAAC,cAAc,EAC3B,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,CACrC,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAElD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n ContainerMutationAuthor,\n ContainerShareApi,\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport { createGroupMetadataAccess } from \"../../organizations/groupMetadataAccess\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport { preparePrincipalContainerRematerializationBatch } from \"../../organizations/principalContainerRematerialization\";\nimport { setOrganizationGroupContainerGrant } from \"../../organizations/principalPolicy\";\nimport type { GroupPolicyNameReader } from \"../../organizations/principalPolicyRequest\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"./mutationSubmit\";\nimport { projectionWithCurrentAncestors } from \"./shareAncestorRepair\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport {\n advanceVerifiedSharePolicies,\n type ContainerManagedPrincipalShareApi,\n loadVerifiedGroupSharePrincipalPolicy,\n} from \"./sharePrincipalPolicy\";\n\nclass ContainerShareGenerationExpiredError extends Error {}\n\nasync function buildCurrentContainerSharePlan(\n input: Parameters<typeof buildMaterializedContainerSharePlan>[0],\n): Promise<MaterializedContainerSharePlan | null> {\n return nullOnProjectionVerificationCancellation(() =>\n buildMaterializedContainerSharePlan(input),\n );\n}\n\n/** The container's projection, with any lazily stale chain above it repaired. */\nasync function resolveShareProjection(\n input: Omit<\n Parameters<typeof projectionWithCurrentAncestors>[0],\n \"previousProjection\" | \"resolveProjectionUserKey\"\n > & { previousProjection?: ContainerWriterProjectionResponse | undefined },\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<ContainerWriterProjectionResponse | null> {\n const servedProjection =\n input.previousProjection ??\n (await input.apiClient.getContainerWriterProjection(input.containerId));\n if (!servedProjection || input.stillCurrent?.() === false) return null;\n const previousProjection = await projectionWithCurrentAncestors({\n ...input,\n previousProjection: servedProjection,\n resolveProjectionUserKey,\n });\n return input.stillCurrent?.() === false ? null : previousProjection;\n}\n\nexport async function shareRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n} | null> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n const recipientIdentity = await resolveTrustedUserIdentity(\n input.recipientUserId,\n );\n if (!recipientIdentity || input.stillCurrent?.() === false) {\n return null;\n }\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n recipient: {\n recipientEncapsulationPublicKey: recipientIdentity.encapsulationPublicKey,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n}\n\ninterface RemoteContainerGroupShareInput {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerManagedPrincipalShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n /**\n * The display name the user chose the group by, checked against the name\n * committed in the verified group policy so a relabeled read-model row\n * cannot redirect the share onto another group. `null` is reserved for the\n * grant-preserving re-wrap: a share that would mint a new grant without a\n * name is refused.\n */\n expectedGroupName: string | null;\n readEncryptedName?: GroupPolicyNameReader | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n signingKeyPair?: SigningKeyPair | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RemoteContainerGroupShareResult {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n}\n\nfunction isMaterializedContainerSharePlan(\n value: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >[\"plans\"][number],\n): value is MaterializedContainerSharePlan {\n return value.plan.body.eventType === \"container.grant\";\n}\n\nasync function prepareMissingGroupGrantMutations(input: {\n currentPolicy: PrincipalPolicyBundleResponse;\n nextPolicy: VerifiedPrincipalPolicy;\n shareInput: RemoteContainerGroupShareInput;\n}) {\n const { currentPolicy, nextPolicy, shareInput } = input;\n return preparePrincipalContainerRematerializationBatch({\n reportSecurityIncident: shareInput.reportSecurityIncident,\n apiClient: shareInput.apiClient,\n author: shareInput.author,\n execSql: shareInput.execSql,\n grants: [\n ...new Map(\n [...currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: shareInput.recipientGroupId,\n nextPolicy,\n resolveTrustedUserIdentity: shareInput.resolveTrustedUserIdentity,\n stillCurrent: shareInput.stillCurrent,\n targetSecretKey: shareInput.targetSecretKey,\n warmReferencedPrincipalPolicies: shareInput.warmReferencedPrincipalPolicies,\n });\n}\n\nasync function commitMissingGroupGrantPolicy(\n input: RemoteContainerGroupShareInput,\n): Promise<{\n preparedTarget: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >;\n storedPolicy: Awaited<ReturnType<typeof setOrganizationGroupContainerGrant>>;\n} | null> {\n const signingKeyPair = input.signingKeyPair;\n if (!signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n const policyApi = {\n commitOrganizationGroupPolicy:\n input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),\n getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(\n input.apiClient,\n ),\n };\n let preparedTarget:\n | Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >\n | undefined;\n try {\n const storedPolicy = await setOrganizationGroupContainerGrant({\n accessLevel: input.accessLevel,\n apiClient: policyApi,\n assertCanCommit: () => {\n if (input.stillCurrent?.() === false) {\n throw new ContainerShareGenerationExpiredError();\n }\n },\n containerId: input.containerId,\n execSql: input.execSql,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n prepareContainerMutations: async ({ currentPolicy, nextPolicy }) => {\n preparedTarget = await prepareMissingGroupGrantMutations({\n currentPolicy,\n nextPolicy,\n shareInput: input,\n });\n return preparedTarget;\n },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.author.signerUserId,\n signingFingerprint: input.author.signerKeyFingerprint,\n signingKeyPair,\n });\n if (!preparedTarget) {\n throw new Error(\"Container group share preparation is incomplete\");\n }\n return { preparedTarget, storedPolicy };\n } catch (error) {\n if (\n error instanceof ContainerShareGenerationExpiredError ||\n isProjectionVerificationCancelledError(error)\n ) {\n return null;\n }\n throw error;\n }\n}\n\nasync function commitMissingGroupGrant(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (!input.signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n if (input.stillCurrent?.() === false) return null;\n const committed = await commitMissingGroupGrantPolicy(input);\n if (!committed) return null;\n const { preparedTarget, storedPolicy } = committed;\n const targetIndex = preparedTarget?.plans.findIndex(\n (planned) => planned.plan.containerId === input.containerId,\n );\n const response =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : storedPolicy.containerMutations[targetIndex];\n const targetPlan =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : preparedTarget?.plans[targetIndex];\n if (\n !targetPlan ||\n !response ||\n !isMaterializedContainerSharePlan(targetPlan)\n ) {\n throw new Error(\"Container group share acknowledgement is incomplete\");\n }\n return {\n containerKey: targetPlan.containerKey,\n plan: targetPlan.plan,\n response,\n };\n}\n\n// Only a re-wrap of an existing signed grant may run without the chosen name;\n// minting a grant is exactly the operation the name binding protects.\nfunction assertGrantMintNamed(expectedGroupName: string | null): void {\n if (expectedGroupName === null) {\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n }\n}\n\nfunction loadShareGroupPolicy(input: RemoteContainerGroupShareInput) {\n return loadVerifiedGroupSharePrincipalPolicy({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedGroupName: input.expectedGroupName ?? undefined,\n readEncryptedName:\n input.readEncryptedName ??\n createGroupMetadataAccess({\n ...input,\n organizationId: input.author.organizationId,\n verifyMetadataContainer: createGroupMetadataContainerVerifier({\n ...input,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n }),\n }).readName,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n}\n\nexport async function shareRemoteContainerWithGroup(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const verifiedPrincipalPolicy = await loadShareGroupPolicy(input);\n if (input.stillCurrent?.() === false) return null;\n await advanceVerifiedSharePolicies(\n input.execSql,\n verifiedPrincipalPolicy,\n input.stillCurrent,\n );\n if (input.stillCurrent?.() === false) return null;\n\n const signedGrant = verifiedPrincipalPolicy.policy.grants.find(\n (grant) => grant.containerId === input.containerId,\n );\n if (!signedGrant || signedGrant.accessLevel !== input.accessLevel) {\n assertGrantMintNamed(input.expectedGroupName);\n return commitMissingGroupGrant(input);\n }\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n principalPolicyCache: principalPolicyCacheForVerifiedPolicies(\n verifiedPrincipalPolicy.checkpointPolicies,\n ),\n previousProjection,\n recipient: {\n principalPolicy: verifiedPrincipalPolicy.policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n const result = await submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: verifiedPrincipalPolicy.checkpointPolicies,\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n if (!result) return null;\n\n // Keep the previously cached group epoch available until the old container\n // wrap has been unwrapped and the replacement has committed. Root has no\n // parent fallback, so caching the rotated policy any earlier destroys the\n // only local path to the KEK that must be re-wrapped.\n if (input.stillCurrent?.() !== false) {\n await savePrincipalPolicyBundle(\n input.execSql,\n verifiedPrincipalPolicy.bundle,\n new Date().toISOString(),\n input.author.organizationId,\n { stillCurrent: input.stillCurrent },\n );\n }\n if (input.stillCurrent?.() === false) return null;\n\n return result;\n}\n"]}
1
+ {"version":3,"file":"share.js","sourceRoot":"","sources":["share.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,sCAAsC,EACtC,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,uCAAuC,EAAE,MAAM,iEAAiE,CAAC;AAC1H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AAGjG,OAAO,EACL,kCAAkC,GAEnC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,oCAAoC,EAAE,MAAM,qDAAqD,CAAC;AAC3G,OAAO,EAAE,+CAA+C,EAAE,MAAM,yDAAyD,CAAC;AAC1H,OAAO,EAAE,kCAAkC,EAAE,MAAM,qCAAqC,CAAC;AAEzF,OAAO,EACL,mCAAmC,EACnC,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,mCAAmC,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EACL,4BAA4B,EAE5B,qCAAqC,GACtC,MAAM,wBAAwB,CAAC;AAEhC,MAAM,oCAAqC,SAAQ,KAAK;CAAG;AAE3D,KAAK,UAAU,8BAA8B,CAC3C,KAAgE;IAEhE,OAAO,wCAAwC,CAAC,GAAG,EAAE,CACnD,mCAAmC,CAAC,KAAK,CAAC,CAC3C,CAAC;AACJ,CAAC;AAED,iFAAiF;AACjF,KAAK,UAAU,sBAAsB,CACnC,KAG0E,EAC1E,w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,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n ContainerMutationAuthor,\n ContainerShareApi,\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport { createGroupMetadataAccess } from \"../../organizations/groupMetadataAccess\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport { preparePrincipalContainerRematerializationBatch } from \"../../organizations/principalContainerRematerialization\";\nimport { setOrganizationGroupContainerGrant } from \"../../organizations/principalPolicy\";\nimport type { GroupPolicyNameReader } from \"../../organizations/principalPolicyRequest\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"./mutationSubmit\";\nimport { projectionWithCurrentAncestors } from \"./shareAncestorRepair\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport {\n advanceVerifiedSharePolicies,\n type ContainerManagedPrincipalShareApi,\n loadVerifiedGroupSharePrincipalPolicy,\n} from \"./sharePrincipalPolicy\";\n\nclass ContainerShareGenerationExpiredError extends Error {}\n\nasync function buildCurrentContainerSharePlan(\n input: Parameters<typeof buildMaterializedContainerSharePlan>[0],\n): Promise<MaterializedContainerSharePlan | null> {\n return nullOnProjectionVerificationCancellation(() =>\n buildMaterializedContainerSharePlan(input),\n );\n}\n\n/** The container's projection, with any lazily stale chain above it repaired. */\nasync function resolveShareProjection(\n input: Omit<\n Parameters<typeof projectionWithCurrentAncestors>[0],\n \"previousProjection\" | \"resolveProjectionUserKey\"\n > & { previousProjection?: ContainerWriterProjectionResponse | undefined },\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<ContainerWriterProjectionResponse | null> {\n const servedProjection =\n input.previousProjection ??\n (await input.apiClient.getContainerWriterProjection(input.containerId));\n if (!servedProjection || input.stillCurrent?.() === false) return null;\n const previousProjection = await projectionWithCurrentAncestors({\n ...input,\n previousProjection: servedProjection,\n resolveProjectionUserKey,\n });\n return input.stillCurrent?.() === false ? null : previousProjection;\n}\n\nexport async function shareRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n} | null> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n const recipientIdentity = await resolveTrustedUserIdentity(\n input.recipientUserId,\n );\n if (!recipientIdentity || input.stillCurrent?.() === false) {\n return null;\n }\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n recipient: {\n recipientEncapsulationPublicKey: recipientIdentity.encapsulationPublicKey,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n}\n\ninterface RemoteContainerGroupShareInput {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerManagedPrincipalShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n /**\n * The display name the user chose the group by, checked against the name\n * committed in the verified group policy so a relabeled read-model row\n * cannot redirect the share onto another group. `null` is reserved for the\n * grant-preserving re-wrap: a share that would mint a new grant without a\n * name is refused.\n */\n expectedGroupName: string | null;\n readEncryptedName?: GroupPolicyNameReader | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n signingKeyPair?: SigningKeyPair | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RemoteContainerGroupShareResult {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n}\n\nfunction isMaterializedContainerSharePlan(\n value: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >[\"plans\"][number],\n): value is MaterializedContainerSharePlan {\n return value.plan.body.eventType === \"container.grant\";\n}\n\nasync function prepareMissingGroupGrantMutations(input: {\n currentPolicy: PrincipalPolicyBundleResponse;\n nextPolicy: VerifiedPrincipalPolicy;\n shareInput: RemoteContainerGroupShareInput;\n}) {\n const { currentPolicy, nextPolicy, shareInput } = input;\n return preparePrincipalContainerRematerializationBatch({\n reportSecurityIncident: shareInput.reportSecurityIncident,\n apiClient: shareInput.apiClient,\n author: shareInput.author,\n execSql: shareInput.execSql,\n grants: [\n ...new Map(\n [...currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: shareInput.recipientGroupId,\n nextPolicy,\n resolveTrustedUserIdentity: shareInput.resolveTrustedUserIdentity,\n stillCurrent: shareInput.stillCurrent,\n targetSecretKey: shareInput.targetSecretKey,\n warmReferencedPrincipalPolicies: shareInput.warmReferencedPrincipalPolicies,\n });\n}\n\nasync function commitMissingGroupGrantPolicy(\n input: RemoteContainerGroupShareInput,\n): Promise<{\n preparedTarget: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >;\n storedPolicy: Awaited<ReturnType<typeof setOrganizationGroupContainerGrant>>;\n} | null> {\n const signingKeyPair = input.signingKeyPair;\n if (!signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n const policyApi = {\n recoverPendingPrincipalMutation:\n input.apiClient.recoverPendingPrincipalMutation?.bind(input.apiClient),\n commitOrganizationGroupPolicy:\n input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),\n getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(\n input.apiClient,\n ),\n };\n let preparedTarget:\n | Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >\n | undefined;\n try {\n const storedPolicy = await setOrganizationGroupContainerGrant({\n accessLevel: input.accessLevel,\n apiClient: policyApi,\n assertCanCommit: () => {\n if (input.stillCurrent?.() === false) {\n throw new ContainerShareGenerationExpiredError();\n }\n },\n containerId: input.containerId,\n execSql: input.execSql,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n prepareContainerMutations: async ({ currentPolicy, nextPolicy }) => {\n preparedTarget = await prepareMissingGroupGrantMutations({\n currentPolicy,\n nextPolicy,\n shareInput: input,\n });\n return preparedTarget;\n },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.author.signerUserId,\n signingFingerprint: input.author.signerKeyFingerprint,\n signingKeyPair,\n });\n if (!preparedTarget) {\n throw new Error(\"Container group share preparation is incomplete\");\n }\n return { preparedTarget, storedPolicy };\n } catch (error) {\n if (\n error instanceof ContainerShareGenerationExpiredError ||\n isProjectionVerificationCancelledError(error)\n ) {\n return null;\n }\n throw error;\n }\n}\n\nasync function commitMissingGroupGrant(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (!input.signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n if (input.stillCurrent?.() === false) return null;\n const committed = await commitMissingGroupGrantPolicy(input);\n if (!committed) return null;\n const { preparedTarget, storedPolicy } = committed;\n const targetIndex = preparedTarget?.plans.findIndex(\n (planned) => planned.plan.containerId === input.containerId,\n );\n const response =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : storedPolicy.containerMutations[targetIndex];\n const targetPlan =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : preparedTarget?.plans[targetIndex];\n if (\n !targetPlan ||\n !response ||\n !isMaterializedContainerSharePlan(targetPlan)\n ) {\n throw new Error(\"Container group share acknowledgement is incomplete\");\n }\n return {\n containerKey: targetPlan.containerKey,\n plan: targetPlan.plan,\n response,\n };\n}\n\n// Only a re-wrap of an existing signed grant may run without the chosen name;\n// minting a grant is exactly the operation the name binding protects.\nfunction assertGrantMintNamed(expectedGroupName: string | null): void {\n if (expectedGroupName === null) {\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n }\n}\n\nfunction loadShareGroupPolicy(input: RemoteContainerGroupShareInput) {\n return loadVerifiedGroupSharePrincipalPolicy({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedGroupName: input.expectedGroupName ?? undefined,\n readEncryptedName:\n input.readEncryptedName ??\n createGroupMetadataAccess({\n ...input,\n organizationId: input.author.organizationId,\n verifyMetadataContainer: createGroupMetadataContainerVerifier({\n ...input,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n }),\n }).readName,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n}\n\nexport async function shareRemoteContainerWithGroup(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (input.stillCurrent?.() === false) return null;\n await input.apiClient.recoverPendingPrincipalMutation?.(\n input.author.organizationId,\n );\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const verifiedPrincipalPolicy = await loadShareGroupPolicy(input);\n if (input.stillCurrent?.() === false) return null;\n await advanceVerifiedSharePolicies(\n input.execSql,\n verifiedPrincipalPolicy,\n input.stillCurrent,\n );\n if (input.stillCurrent?.() === false) return null;\n\n const signedGrant = verifiedPrincipalPolicy.policy.grants.find(\n (grant) => grant.containerId === input.containerId,\n );\n if (!signedGrant || signedGrant.accessLevel !== input.accessLevel) {\n assertGrantMintNamed(input.expectedGroupName);\n return commitMissingGroupGrant(input);\n }\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n principalPolicyCache: principalPolicyCacheForVerifiedPolicies(\n verifiedPrincipalPolicy.checkpointPolicies,\n ),\n previousProjection,\n recipient: {\n principalPolicy: verifiedPrincipalPolicy.policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n const result = await submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: verifiedPrincipalPolicy.checkpointPolicies,\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n if (!result) return null;\n\n // Keep the previously cached group epoch available until the old container\n // wrap has been unwrapped and the replacement has committed. Root has no\n // parent fallback, so caching the rotated policy any earlier destroys the\n // only local path to the KEK that must be re-wrapped.\n if (input.stillCurrent?.() !== false) {\n await savePrincipalPolicyBundle(\n input.execSql,\n verifiedPrincipalPolicy.bundle,\n new Date().toISOString(),\n input.author.organizationId,\n { stillCurrent: input.stillCurrent },\n );\n }\n if (input.stillCurrent?.() === false) return null;\n\n return result;\n}\n"]}
@@ -7,6 +7,7 @@ import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
7
7
  import type { TrustedUserIdentityResolver } from "../../../data/trustedUserIdentity/index.js";
8
8
  import { type GroupPolicyNameReader } from "../../organizations/principalPolicyRequest.js";
9
9
  export interface ContainerManagedPrincipalShareApi extends ContainerShareApi, Pick<ApiClient, "evictContainerWriterProjection" | "getContainerWriterProjectionResult"> {
10
+ readonly recoverPendingPrincipalMutation?: ((organizationId: string) => Promise<void>) | undefined;
10
11
  commitOrganizationGroupPolicy: (organizationId: string, groupId: string, input: CommitOrganizationGroupPolicyRequest) => Promise<CommitOrganizationGroupPolicyResponse | null>;
11
12
  getCurrentPrincipalPolicy: (principalType: ManagedPrincipalKind, principalId: string) => Promise<PrincipalPolicyBundleResponse | null>;
12
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"sharePrincipalPolicy.js","sourceRoot":"","sources":["sharePrincipalPolicy.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,GAKxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AACjG,OAAO,EAAE,qCAAqC,EAAE,MAAM,+DAA+D,CAAC;AACtH,OAAO,EAAE,mCAAmC,EAAE,MAAM,uEAAuE,CAAC;AAC5H,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EACL,kCAAkC,EAClC,yDAAyD,GAC1D,MAAM,sDAAsD,CAAC;AAG9D,OAAO,EAAE,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AACtF,OAAO,EAEL,uBAAuB,GACxB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,qCAAqC,EACrC,mCAAmC,GAEpC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,sCAAsC,GAEvC,MAA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BAAkB;QACrC,qBAAqB,EAAE,KAAK,IAAI,EAAE,CAChC,uBAAuB,CAAC,iBAAiB;QAC3C,eAAe;QACf,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,uCAAuC,CACrC,QAAQ,CAAC,KAAK,EACd,sDAAsD,CACvD,CAAC;IACJ,CAAC;IACD,0BAA0B,CAAC,MAAM,EAAE,uBAAuB,CAAC,UAAU,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,iBAAiB,KAAK,SAAS,EAAE,CAAC;QAC1C,MAAM,oBAAoB,CAAC;YACzB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,MAAM;YACN,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;SAC3C,CAAC,CAAC;IACL,CAAC;IAED,MAAM,kBAAkB,GAAG,MAAM,2BAA2B,CAAC;QAC3D,MAAM;QACN,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,kBAAkB,EAAE,uBAAuB;QAC3C,MAAM,EAAE,QAAQ,CAAC,KAAK;QACtB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,OAAO;QACL,MAAM;QACN,kBAAkB;QAClB,iBAAiB,EAAE,qCAAqC,CACtD,uBAAuB,CACxB,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC;QAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type ManagedPrincipalKind,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { CommitOrganizationGroupPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n CommitOrganizationGroupPolicyResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { ContainerShareApi } from \"../../../data/containers/shared/types\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../../data/keyingProjectionVerification/error\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../../data/persistence/keyingCheckpointPersistence\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../../data/persistence/principalPolicyReferencePersistence\";\nimport { retainVerifiedPrincipalPolicyBundle } from \"../../../data/persistence/verifiedPrincipalPolicyRetentionPersistence\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalPolicyReferenceFromBundle,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { assertGroupMetadataBinding } from \"../../organizations/groupMetadataBinding\";\nimport {\n type GroupPolicyNameReader,\n groupPolicyNameMismatch,\n} from \"../../organizations/principalPolicyRequest\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../../principals/externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n} from \"../../principals/policyVerification\";\n\nexport interface ContainerManagedPrincipalShareApi\n extends ContainerShareApi,\n Pick<\n ApiClient,\n \"evictContainerWriterProjection\" | \"getContainerWriterProjectionResult\"\n > {\n commitOrganizationGroupPolicy: (\n organizationId: string,\n groupId: string,\n input: CommitOrganizationGroupPolicyRequest,\n ) => Promise<CommitOrganizationGroupPolicyResponse | null>;\n getCurrentPrincipalPolicy: (\n principalType: ManagedPrincipalKind,\n principalId: string,\n ) => Promise<PrincipalPolicyBundleResponse | null>;\n}\n\nexport interface VerifiedSharePrincipalPolicy {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly checkpointPolicies: readonly VerifiedPrincipalPolicy[];\n readonly dependencyBundles: readonly PrincipalPolicyBundleResponse[];\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\nasync function retainVerifiedSharePolicies(input: {\n bundle: PrincipalPolicyBundleResponse;\n execSql: ExecSql;\n organizationId: string;\n organizationPolicy: VerifiedExternalAdminPolicy | null;\n policy: VerifiedPrincipalPolicy;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const retainedAt = new Date().toISOString();\n if (input.organizationPolicy) {\n for (const entry of externalAdminPolicyPersistenceEntries(\n input.organizationPolicy,\n )) {\n await retainVerifiedPrincipalPolicyBundle({\n ...entry,\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n }\n }\n await retainVerifiedPrincipalPolicyBundle({\n bundle: input.bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n policy: input.policy,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n return [\n ...(input.organizationPolicy\n ? externalAdminPolicyPersistenceEntries(input.organizationPolicy).map(\n (entry) => entry.policy,\n )\n : []),\n input.policy,\n ];\n}\n\n/**\n * Commits the verification a loadVerifiedGroupSharePrincipalPolicy call\n * deferred: advances the keying checkpoints for the verified policies and\n * caches the dependency bundles they were verified against.\n */\nexport async function advanceVerifiedSharePolicies(\n execSql: ExecSql,\n verified: Pick<\n VerifiedSharePrincipalPolicy,\n \"checkpointPolicies\" | \"dependencyBundles\" | \"organizationId\"\n >,\n stillCurrent?: (() => boolean) | undefined,\n): Promise<void> {\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql,\n organizationId: verified.organizationId,\n policies: verified.checkpointPolicies,\n stillCurrent,\n });\n if (stillCurrent?.() === false) return;\n for (const bundle of verified.dependencyBundles) {\n await savePrincipalPolicyBundle(\n execSql,\n bundle,\n new Date().toISOString(),\n verified.organizationId,\n { stillCurrent },\n );\n if (stillCurrent?.() === false) return;\n }\n}\n\nfunction assertGroupPolicyTarget(\n bundle: PrincipalPolicyBundleResponse,\n groupId: string,\n): void {\n if (\n bundle.currentState.principalType !== \"group\" ||\n bundle.currentState.principalId !== groupId\n ) {\n throw new Error(\"Container share principal policy target mismatch\");\n }\n}\n\nfunction signerPublicKeyLoadErrorMessage(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): string {\n switch (code) {\n case \"fingerprint-mismatch\":\n return \"principal policy signer key fingerprint mismatch\";\n case \"not-found\":\n return \"principal policy signer key could not be loaded\";\n }\n}\n\nasync function loadGroupSharePolicyBundle(input: {\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n groupId: string;\n localCheckpoint: PrincipalPolicyCheckpoint | null;\n}): Promise<PrincipalPolicyBundleResponse> {\n if (\n input.expectedGroupHead &&\n (input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId)\n ) {\n throw new Error(\"Container share expected group policy target mismatch\");\n }\n const bundleFromCache = input.expectedGroupHead\n ? await loadPrincipalPolicyBundleForReference(\n input.execSql,\n input.expectedGroupHead,\n input.localCheckpoint,\n )\n : null;\n let bundle = bundleFromCache;\n bundle ??= await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n input.groupId,\n );\n if (!bundle) {\n throw new Error(\"Container share principal policy could not be loaded\");\n }\n assertGroupPolicyTarget(bundle, input.groupId);\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n input.expectedGroupHead,\n )\n ) {\n throw new Error(\n \"Container share group policy does not match the signed organization directory\",\n );\n }\n return bundle;\n}\n\n/**\n * The chosen group label does not match the name in the group's verified\n * policy. A KeyingVerificationError (so it is reported as an incident), with\n * its own class so a caller can tell this refusal from every other\n * `object_mismatch` and say what happened.\n */\nexport class GroupShareNameMismatchError extends KeyingVerificationError {\n constructor(message: string) {\n super(\"object_mismatch\", message);\n this.name = \"GroupShareNameMismatchError\";\n }\n}\n\n/**\n * The share picker labels groups from the organization read model, which a\n * compromised server can relabel, so the name the user chose must equal the\n * name committed in the target's verified policy. Names compare by their\n * canonical key so look-alike spellings count as the same name. Uniqueness of\n * signed names within an organization is enforced where names enter — group\n * creation verifies every group in the signed directory — so a single\n * verified match identifies the group.\n */\nasync function assertShareGroupName(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n bundle: PrincipalPolicyBundleResponse;\n expectedGroupName: string;\n}): Promise<void> {\n // The label comes from the untrusted read model. Signed names never carry\n // an invisible code point, so a label that does is a look-alike that would\n // only match after canonicalization strips it; refuse it outright.\n const mismatch = await groupPolicyNameMismatch(\n input.bundle,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n if (mismatch === \"forbidden_characters\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name contains control or format characters\",\n );\n }\n if (mismatch === \"name_mismatch\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name does not match the signed group policy\",\n );\n }\n}\n\nexport async function loadVerifiedGroupSharePrincipalPolicy(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n /**\n * The display name the user chose the group by. The read model that labels\n * groups is a server projection; only the name committed in the signed\n * group payload can confirm the share lands on the group the user saw.\n */\n expectedGroupName?: string | undefined;\n groupId: string;\n organizationId: string;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedSharePrincipalPolicy> {\n const organizationAdminPolicy = await loadOrganizationExternalAdminPolicy({\n execSql: input.execSql,\n getCurrentPrincipalPolicy: (principalType, principalId) =>\n input.apiClient.getCurrentPrincipalPolicy(principalType, principalId),\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!organizationAdminPolicy) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const committedGroupHead = requireOrganizationGroupHead(\n organizationAdminPolicy.descriptor,\n input.groupId,\n );\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(input.expectedGroupHead, committedGroupHead)\n ) {\n throw new Error(\n \"Container share expected group head conflicts with the signed organization directory\",\n );\n }\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.groupId,\n );\n const bundle = await loadGroupSharePolicyBundle({\n ...input,\n expectedGroupHead: committedGroupHead,\n localCheckpoint,\n });\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n throw new Error(signerPublicKeyLoadErrorMessage(signerPublicKeys.error));\n }\n\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: committedGroupHead,\n loadExternalAuthority: async () =>\n organizationAdminPolicy.externalAuthority,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throwKeyingVerificationErrorWithContext(\n verified.error,\n \"Container share principal policy verification failed\",\n );\n }\n assertGroupMetadataBinding(bundle, organizationAdminPolicy.descriptor);\n if (input.expectedGroupName !== undefined) {\n await assertShareGroupName({\n readEncryptedName: input.readEncryptedName,\n bundle,\n expectedGroupName: input.expectedGroupName,\n });\n }\n\n const checkpointPolicies = await retainVerifiedSharePolicies({\n bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n organizationPolicy: organizationAdminPolicy,\n policy: verified.value,\n stillCurrent: input.stillCurrent,\n });\n return {\n bundle,\n checkpointPolicies,\n dependencyBundles: externalAdminPolicyPersistenceEntries(\n organizationAdminPolicy,\n ).map((entry) => entry.bundle),\n organizationId: input.organizationId,\n policy: verified.value,\n };\n}\n"]}
1
+ {"version":3,"file":"sharePrincipalPolicy.js","sourceRoot":"","sources":["sharePrincipalPolicy.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,GAKxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AACjG,OAAO,EAAE,qCAAqC,EAAE,MAAM,+DAA+D,CAAC;AACtH,OAAO,EAAE,mCAAmC,EAAE,MAAM,uEAAuE,CAAC;AAC5H,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EACL,kCAAkC,EAClC,yDAAyD,GAC1D,MAAM,sDAAsD,CAAC;AAG9D,OAAO,EAAE,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AACtF,OAAO,EAEL,uBAAuB,GACxB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,qCAAqC,EACrC,mCAAmC,GAEpC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,sCAAsC,GAEvC,MAAM,qCAAqC,CAAC;AA8B7C,KAAK,UAAU,2BAA2B,CAAC,KAO1C;IACC,MAAM,UAAU,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC5C,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC;QAC7B,KAAK,MAAM,KAAK,IAAI,qCAAqC,CACvD,KAAK,CAAC,kBAAkB,CACzB,EAAE,CAAC;YACF,MAA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ACJ,CAAC;IACD,0BAA0B,CAAC,MAAM,EAAE,uBAAuB,CAAC,UAAU,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,iBAAiB,KAAK,SAAS,EAAE,CAAC;QAC1C,MAAM,oBAAoB,CAAC;YACzB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,MAAM;YACN,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;SAC3C,CAAC,CAAC;IACL,CAAC;IAED,MAAM,kBAAkB,GAAG,MAAM,2BAA2B,CAAC;QAC3D,MAAM;QACN,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,kBAAkB,EAAE,uBAAuB;QAC3C,MAAM,EAAE,QAAQ,CAAC,KAAK;QACtB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,OAAO;QACL,MAAM;QACN,kBAAkB;QAClB,iBAAiB,EAAE,qCAAqC,CACtD,uBAAuB,CACxB,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC;QAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type ManagedPrincipalKind,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { CommitOrganizationGroupPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n CommitOrganizationGroupPolicyResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { ContainerShareApi } from \"../../../data/containers/shared/types\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../../data/keyingProjectionVerification/error\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../../data/persistence/keyingCheckpointPersistence\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../../data/persistence/principalPolicyReferencePersistence\";\nimport { retainVerifiedPrincipalPolicyBundle } from \"../../../data/persistence/verifiedPrincipalPolicyRetentionPersistence\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalPolicyReferenceFromBundle,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { assertGroupMetadataBinding } from \"../../organizations/groupMetadataBinding\";\nimport {\n type GroupPolicyNameReader,\n groupPolicyNameMismatch,\n} from \"../../organizations/principalPolicyRequest\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../../principals/externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n} from \"../../principals/policyVerification\";\n\nexport interface ContainerManagedPrincipalShareApi\n extends ContainerShareApi,\n Pick<\n ApiClient,\n \"evictContainerWriterProjection\" | \"getContainerWriterProjectionResult\"\n > {\n readonly recoverPendingPrincipalMutation?:\n | ((organizationId: string) => Promise<void>)\n | undefined;\n commitOrganizationGroupPolicy: (\n organizationId: string,\n groupId: string,\n input: CommitOrganizationGroupPolicyRequest,\n ) => Promise<CommitOrganizationGroupPolicyResponse | null>;\n getCurrentPrincipalPolicy: (\n principalType: ManagedPrincipalKind,\n principalId: string,\n ) => Promise<PrincipalPolicyBundleResponse | null>;\n}\n\nexport interface VerifiedSharePrincipalPolicy {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly checkpointPolicies: readonly VerifiedPrincipalPolicy[];\n readonly dependencyBundles: readonly PrincipalPolicyBundleResponse[];\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\nasync function retainVerifiedSharePolicies(input: {\n bundle: PrincipalPolicyBundleResponse;\n execSql: ExecSql;\n organizationId: string;\n organizationPolicy: VerifiedExternalAdminPolicy | null;\n policy: VerifiedPrincipalPolicy;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const retainedAt = new Date().toISOString();\n if (input.organizationPolicy) {\n for (const entry of externalAdminPolicyPersistenceEntries(\n input.organizationPolicy,\n )) {\n await retainVerifiedPrincipalPolicyBundle({\n ...entry,\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n }\n }\n await retainVerifiedPrincipalPolicyBundle({\n bundle: input.bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n policy: input.policy,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n return [\n ...(input.organizationPolicy\n ? externalAdminPolicyPersistenceEntries(input.organizationPolicy).map(\n (entry) => entry.policy,\n )\n : []),\n input.policy,\n ];\n}\n\n/**\n * Commits the verification a loadVerifiedGroupSharePrincipalPolicy call\n * deferred: advances the keying checkpoints for the verified policies and\n * caches the dependency bundles they were verified against.\n */\nexport async function advanceVerifiedSharePolicies(\n execSql: ExecSql,\n verified: Pick<\n VerifiedSharePrincipalPolicy,\n \"checkpointPolicies\" | \"dependencyBundles\" | \"organizationId\"\n >,\n stillCurrent?: (() => boolean) | undefined,\n): Promise<void> {\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql,\n organizationId: verified.organizationId,\n policies: verified.checkpointPolicies,\n stillCurrent,\n });\n if (stillCurrent?.() === false) return;\n for (const bundle of verified.dependencyBundles) {\n await savePrincipalPolicyBundle(\n execSql,\n bundle,\n new Date().toISOString(),\n verified.organizationId,\n { stillCurrent },\n );\n if (stillCurrent?.() === false) return;\n }\n}\n\nfunction assertGroupPolicyTarget(\n bundle: PrincipalPolicyBundleResponse,\n groupId: string,\n): void {\n if (\n bundle.currentState.principalType !== \"group\" ||\n bundle.currentState.principalId !== groupId\n ) {\n throw new Error(\"Container share principal policy target mismatch\");\n }\n}\n\nfunction signerPublicKeyLoadErrorMessage(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): string {\n switch (code) {\n case \"fingerprint-mismatch\":\n return \"principal policy signer key fingerprint mismatch\";\n case \"not-found\":\n return \"principal policy signer key could not be loaded\";\n }\n}\n\nasync function loadGroupSharePolicyBundle(input: {\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n groupId: string;\n localCheckpoint: PrincipalPolicyCheckpoint | null;\n}): Promise<PrincipalPolicyBundleResponse> {\n if (\n input.expectedGroupHead &&\n (input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId)\n ) {\n throw new Error(\"Container share expected group policy target mismatch\");\n }\n const bundleFromCache = input.expectedGroupHead\n ? await loadPrincipalPolicyBundleForReference(\n input.execSql,\n input.expectedGroupHead,\n input.localCheckpoint,\n )\n : null;\n let bundle = bundleFromCache;\n bundle ??= await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n input.groupId,\n );\n if (!bundle) {\n throw new Error(\"Container share principal policy could not be loaded\");\n }\n assertGroupPolicyTarget(bundle, input.groupId);\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n input.expectedGroupHead,\n )\n ) {\n throw new Error(\n \"Container share group policy does not match the signed organization directory\",\n );\n }\n return bundle;\n}\n\n/**\n * The chosen group label does not match the name in the group's verified\n * policy. A KeyingVerificationError (so it is reported as an incident), with\n * its own class so a caller can tell this refusal from every other\n * `object_mismatch` and say what happened.\n */\nexport class GroupShareNameMismatchError extends KeyingVerificationError {\n constructor(message: string) {\n super(\"object_mismatch\", message);\n this.name = \"GroupShareNameMismatchError\";\n }\n}\n\n/**\n * The share picker labels groups from the organization read model, which a\n * compromised server can relabel, so the name the user chose must equal the\n * name committed in the target's verified policy. Names compare by their\n * canonical key so look-alike spellings count as the same name. Uniqueness of\n * signed names within an organization is enforced where names enter — group\n * creation verifies every group in the signed directory — so a single\n * verified match identifies the group.\n */\nasync function assertShareGroupName(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n bundle: PrincipalPolicyBundleResponse;\n expectedGroupName: string;\n}): Promise<void> {\n // The label comes from the untrusted read model. Signed names never carry\n // an invisible code point, so a label that does is a look-alike that would\n // only match after canonicalization strips it; refuse it outright.\n const mismatch = await groupPolicyNameMismatch(\n input.bundle,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n if (mismatch === \"forbidden_characters\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name contains control or format characters\",\n );\n }\n if (mismatch === \"name_mismatch\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name does not match the signed group policy\",\n );\n }\n}\n\nexport async function loadVerifiedGroupSharePrincipalPolicy(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n /**\n * The display name the user chose the group by. The read model that labels\n * groups is a server projection; only the name committed in the signed\n * group payload can confirm the share lands on the group the user saw.\n */\n expectedGroupName?: string | undefined;\n groupId: string;\n organizationId: string;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedSharePrincipalPolicy> {\n const organizationAdminPolicy = await loadOrganizationExternalAdminPolicy({\n execSql: input.execSql,\n getCurrentPrincipalPolicy: (principalType, principalId) =>\n input.apiClient.getCurrentPrincipalPolicy(principalType, principalId),\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!organizationAdminPolicy) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const committedGroupHead = requireOrganizationGroupHead(\n organizationAdminPolicy.descriptor,\n input.groupId,\n );\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(input.expectedGroupHead, committedGroupHead)\n ) {\n throw new Error(\n \"Container share expected group head conflicts with the signed organization directory\",\n );\n }\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.groupId,\n );\n const bundle = await loadGroupSharePolicyBundle({\n ...input,\n expectedGroupHead: committedGroupHead,\n localCheckpoint,\n });\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n throw new Error(signerPublicKeyLoadErrorMessage(signerPublicKeys.error));\n }\n\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: committedGroupHead,\n loadExternalAuthority: async () =>\n organizationAdminPolicy.externalAuthority,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throwKeyingVerificationErrorWithContext(\n verified.error,\n \"Container share principal policy verification failed\",\n );\n }\n assertGroupMetadataBinding(bundle, organizationAdminPolicy.descriptor);\n if (input.expectedGroupName !== undefined) {\n await assertShareGroupName({\n readEncryptedName: input.readEncryptedName,\n bundle,\n expectedGroupName: input.expectedGroupName,\n });\n }\n\n const checkpointPolicies = await retainVerifiedSharePolicies({\n bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n organizationPolicy: organizationAdminPolicy,\n policy: verified.value,\n stillCurrent: input.stillCurrent,\n });\n return {\n bundle,\n checkpointPolicies,\n dependencyBundles: externalAdminPolicyPersistenceEntries(\n organizationAdminPolicy,\n ).map((entry) => entry.bundle),\n organizationId: input.organizationId,\n policy: verified.value,\n };\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
+ import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../data/principals/organizationAuthorityDescriptor.js";
3
+ /** Couple supplied group receipts to the directory acknowledged in the same batch. */
4
+ export function assertAcknowledgedDirectoryBindings(organizationId, receipts) {
5
+ const directories = receipts.filter((receipt) => receipt.currentState.principalType === "organization");
6
+ if (directories.length === 0 &&
7
+ receipts.some((receipt) => receipt.currentState.principalType === "group"))
8
+ throw new KeyingVerificationError("missing_dependency", "Acknowledged groups require their organization directory");
9
+ for (const directory of directories) {
10
+ const descriptor = parseOrganizationAuthorityDescriptor(directory.currentPayload.ciphertext);
11
+ if (directory.currentState.principalId !== organizationId ||
12
+ descriptor.organizationId !== organizationId ||
13
+ receipts.some(({ currentState }) => currentState.principalType === "group" &&
14
+ !descriptor.groupHeads.some((head) => principalHeadMatchesReference(head, currentState))))
15
+ throw new KeyingVerificationError("object_mismatch", "Acknowledged organization does not bind its group receipt");
16
+ }
17
+ }
18
+ //# sourceMappingURL=acknowledgedDirectoryBindings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"acknowledgedDirectoryBindings.js","sourceRoot":"","sources":["acknowledgedDirectoryBindings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,uDAAuD,CAAC;AAE/D,sFAAsF;AACtF,MAAM,UAAU,mCAAmC,CACjD,cAAsB,EACtB,QAAoD;IAEpD,MAAM,WAAW,GAAG,QAAQ,CAAC,MAAM,CACjC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,YAAY,CAAC,aAAa,KAAK,cAAc,CACnE,CAAC;IACF,IACE,WAAW,CAAC,MAAM,KAAK,CAAC;QACxB,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,YAAY,CAAC,aAAa,KAAK,OAAO,CAAC;QAE1E,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,0DAA0D,CAC3D,CAAC;IACJ,KAAK,MAAM,SAAS,IAAI,WAAW,EAAE,CAAC;QACpC,MAAM,UAAU,GAAG,oCAAoC,CACrD,SAAS,CAAC,cAAc,CAAC,UAAU,CACpC,CAAC;QACF,IACE,SAAS,CAAC,YAAY,CAAC,WAAW,KAAK,cAAc;YACrD,UAAU,CAAC,cAAc,KAAK,cAAc;YAC5C,QAAQ,CAAC,IAAI,CACX,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,CACnB,YAAY,CAAC,aAAa,KAAK,OAAO;gBACtC,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CACnC,6BAA6B,CAAC,IAAI,EAAE,YAAY,CAAC,CAClD,CACJ;YAED,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,2DAA2D,CAC5D,CAAC;IACN,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\n\n/** Couple supplied group receipts to the directory acknowledged in the same batch. */\nexport function assertAcknowledgedDirectoryBindings(\n organizationId: string,\n receipts: readonly PrincipalPolicyMutationResponse[],\n) {\n const directories = receipts.filter(\n (receipt) => receipt.currentState.principalType === \"organization\",\n );\n if (\n directories.length === 0 &&\n receipts.some((receipt) => receipt.currentState.principalType === \"group\")\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledged groups require their organization directory\",\n );\n for (const directory of directories) {\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.currentPayload.ciphertext,\n );\n if (\n directory.currentState.principalId !== organizationId ||\n descriptor.organizationId !== organizationId ||\n receipts.some(\n ({ currentState }) =>\n currentState.principalType === \"group\" &&\n !descriptor.groupHeads.some((head) =>\n principalHeadMatchesReference(head, currentState),\n ),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged organization does not bind its group receipt\",\n );\n }\n}\n"]}
@@ -0,0 +1,32 @@
1
+ import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
2
+ import { loadCurrentOrganizationAuthority } from "./currentOrganizationAuthority.js";
3
+ import { assertMetadataRootBinding } from "./groupMetadataRootBinding.js";
4
+ /** Authenticate metadata-root grants with current policies and only its cited predecessors. */
5
+ export function createCurrentGroupMetadataContainerVerifier(input) {
6
+ return async (state, organizationReference) => {
7
+ assertProjectionVerificationCurrent(input.stillCurrent);
8
+ const authority = await loadCurrentOrganizationAuthority({
9
+ ...input,
10
+ organizationReference,
11
+ });
12
+ const { adminGroupId, memberGroupId } = authority.descriptor;
13
+ const citation = (groupId) => state.referencedPrincipalHeads.find((head) => head.principalType === "group" && head.principalId === groupId);
14
+ const admins = await authority.readGroup(adminGroupId, citation(adminGroupId));
15
+ const members = await authority.readGroup(memberGroupId, citation(memberGroupId));
16
+ assertMetadataRootBinding({
17
+ organizationId: input.organizationId,
18
+ authority: {
19
+ descriptor: authority.descriptor,
20
+ adminGroupId,
21
+ memberGroupId,
22
+ adminPolicy: admins.policy,
23
+ },
24
+ members,
25
+ state,
26
+ });
27
+ assertProjectionVerificationCurrent(() => authority.stillCurrent() &&
28
+ admins.stillCurrent() &&
29
+ members.stillCurrent());
30
+ };
31
+ }
32
+ //# sourceMappingURL=currentGroupMetadataAuthority.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"currentGroupMetadataAuthority.js","sourceRoot":"","sources":["currentGroupMetadataAuthority.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,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,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,SAAS,CAAC,UAAU,CAAC;QAC7D,MAAM,QAAQ,GAAG,CAAC,OAAe,EAAE,EAAE,CACnC,KAAK,CAAC,wBAAwB,CAAC,IAAI,CACjC,CAAC,IAAI,EAAE,EAAE,CACP,IAAI,CAAC,aAAa,KAAK,OAAO,IAAI,IAAI,CAAC,WAAW,KAAK,OAAO,CACjE,CAAC;QACJ,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,SAAS,CACtC,YAAY,EACZ,QAAQ,CAAC,YAAY,CAAC,CACvB,CAAC;QACF,MAAM,OAAO,GAAG,MAAM,SAAS,CAAC,SAAS,CACvC,aAAa,EACb,QAAQ,CAAC,aAAa,CAAC,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,CACH,SAAS,CAAC,YAAY,EAAE;YACxB,MAAM,CAAC,YAAY,EAAE;YACrB,OAAO,CAAC,YAAY,EAAE,CACzB,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\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 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 () =>\n authority.stillCurrent() &&\n admins.stillCurrent() &&\n members.stillCurrent(),\n );\n };\n}\n"]}