@tearleads/client-sdk 0.1.11 → 0.1.13
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.
- package/README.md +18 -2
- package/client/Tearleads.d.ts +4 -0
- package/client/Tearleads.js +5 -0
- package/client/Tearleads.js.map +1 -1
- package/client/index.d.ts +1 -0
- package/client/index.js.map +1 -1
- package/client/principalHistoryProtection.d.ts +19 -0
- package/client/principalHistoryProtection.js +76 -0
- package/client/principalHistoryProtection.js.map +1 -0
- package/client/workflowRuntime.d.ts +5 -0
- package/client/workflowRuntime.js +34 -5
- package/client/workflowRuntime.js.map +1 -1
- package/data/containers/shared/authorAccess.d.ts +2 -2
- package/data/containers/shared/authorAccess.js.map +1 -1
- package/data/containers/shared/heldContainerHeads.js.map +1 -1
- package/data/containers/shared/principalPolicies.js.map +1 -1
- package/data/containers/shared/types.d.ts +3 -2
- package/data/containers/shared/types.js.map +1 -1
- package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
- package/data/keyingProjectionVerification/checkpointContext.d.ts +4 -3
- package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/containerPathVerification.js.map +1 -1
- package/data/keyingProjectionVerification/containerProjectionVerification.d.ts +4 -3
- package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentManifestPolicies.js.map +1 -1
- package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentProjectionVerification.d.ts +3 -2
- package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/organizationFounderBinding.js +9 -4
- package/data/keyingProjectionVerification/organizationFounderBinding.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicyCache.js +3 -4
- package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicyVerification.js +12 -2
- package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
- package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js +70 -0
- package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js.map +1 -0
- package/data/keyingProjectionVerification/types.d.ts +17 -2
- package/data/keyingProjectionVerification/types.js +12 -0
- package/data/keyingProjectionVerification/types.js.map +1 -1
- package/data/persistence/organizationFounderPersistence.js +3 -2
- package/data/persistence/organizationFounderPersistence.js.map +1 -1
- package/data/persistence/principalHistoryEvidencePersistence.js +91 -0
- package/data/persistence/principalHistoryEvidencePersistence.js.map +1 -0
- package/data/persistence/principalHistoryPrefixPersistence.js +52 -0
- package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -0
- package/data/persistence/principalHistoryStagePersistence.js +9 -2
- package/data/persistence/principalHistoryStagePersistence.js.map +1 -1
- package/data/persistence/principalKeyEnvelopeCandidates.js +67 -0
- package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -0
- package/data/principals/principalHistoryPrefixProtection.js +29 -0
- package/data/principals/principalHistoryPrefixProtection.js.map +1 -0
- package/data/principals/principalHistoryProtection.d.ts +10 -0
- package/data/principals/principalHistoryProtection.js +14 -0
- package/data/principals/principalHistoryProtection.js.map +1 -0
- package/data/principals/principalHistoryStageProtection.js.map +1 -1
- package/data/principals/principalPolicyCrypto.js +11 -21
- package/data/principals/principalPolicyCrypto.js.map +1 -1
- package/data/principals/principalPolicyEvidence.d.ts +4 -0
- package/data/principals/principalPolicyEvidence.js +12 -0
- package/data/principals/principalPolicyEvidence.js.map +1 -0
- package/data/sqlite/principalHistoryEvidenceSchema.js +46 -0
- package/data/sqlite/principalHistoryEvidenceSchema.js.map +1 -0
- package/data/sqlite/principalKeyFingerprintJson.js +9 -0
- package/data/sqlite/principalKeyFingerprintJson.js.map +1 -0
- package/data/sqlite/principalPolicySchema.js +4 -0
- package/data/sqlite/principalPolicySchema.js.map +1 -1
- package/data/sqlite/schema.d.ts +304 -0
- package/data/sqlite/schema.js +5 -0
- package/data/sqlite/schema.js.map +1 -1
- package/data/sqlite/sqlTableSchema.js +1 -1
- package/data/sqlite/sqlTableSchema.js.map +1 -1
- package/index.d.ts +3 -3
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/internal/api-client/principalPolicyPages.d.ts +2 -0
- package/internal/api-client/principalPolicyPages.js +11 -2
- package/internal/api-client/principalPolicyPages.js.map +1 -1
- package/internal/crypto/index.d.ts +1 -1
- package/internal/crypto/index.js +1 -1
- package/internal/crypto/index.js.map +1 -1
- package/internal/crypto/keying/index.d.ts +1 -1
- package/internal/crypto/keying/index.js +1 -1
- package/internal/crypto/keying/index.js.map +1 -1
- package/internal/crypto/keying/principalPolicyHistoryIndex.d.ts +6 -2
- package/internal/crypto/keying/principalPolicyHistoryIndex.js +11 -5
- package/internal/crypto/keying/principalPolicyHistoryIndex.js.map +1 -1
- package/internal/crypto/keying/principalPolicyHistoryReferences.d.ts +2 -0
- package/internal/crypto/keying/principalPolicyHistoryReferences.js +19 -2
- package/internal/crypto/keying/principalPolicyHistoryReferences.js.map +1 -1
- package/package.json +1 -1
- package/workflows/containers/child/create.js.map +1 -1
- package/workflows/containers/child/move.js.map +1 -1
- package/workflows/containers/child/moveWraps.js.map +1 -1
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/child/rekey.d.ts +3 -2
- package/workflows/containers/child/rekey.js.map +1 -1
- package/workflows/containers/child/revoke.d.ts +2 -2
- package/workflows/containers/child/revoke.js.map +1 -1
- package/workflows/containers/child/rotationPrincipalPolicies.js.map +1 -1
- package/workflows/containers/child/rotationWraps.js.map +1 -1
- package/workflows/containers/child/sharePlanCore.d.ts +11 -10
- package/workflows/containers/child/sharePlanCore.js.map +1 -1
- package/workflows/documents/linkSetAuthority.js.map +1 -1
- package/workflows/principals/index.d.ts +1 -0
- package/workflows/principals/index.js +1 -0
- package/workflows/principals/index.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryPrefix.js +65 -0
- package/workflows/principals/principalHistoryRecoveryPrefix.js.map +1 -0
- package/workflows/principals/principalHistoryRecoveryReferences.js +60 -0
- package/workflows/principals/principalHistoryRecoveryReferences.js.map +1 -0
- package/workflows/principals/principalHistoryRecoveryStage.js +38 -2
- package/workflows/principals/principalHistoryRecoveryStage.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryTypes.d.ts +9 -1
- package/workflows/principals/principalHistoryRecoveryTypes.js +7 -0
- package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryVerification.js +24 -0
- package/workflows/principals/principalHistoryRecoveryVerification.js.map +1 -0
- package/workflows/principals/principalRecoveryDirectory.d.ts +10 -0
- package/workflows/principals/principalRecoveryDirectory.js +107 -0
- package/workflows/principals/principalRecoveryDirectory.js.map +1 -0
- package/workflows/principals/principalRecoveryMemo.js +46 -0
- package/workflows/principals/principalRecoveryMemo.js.map +1 -0
- package/workflows/principals/principalRecoveryOutage.js +40 -0
- package/workflows/principals/principalRecoveryOutage.js.map +1 -0
- package/workflows/principals/principalRecoveryQueue.js +22 -0
- package/workflows/principals/principalRecoveryQueue.js.map +1 -0
- package/workflows/principals/recoverPrincipalPolicyHistory.d.ts +1 -0
- package/workflows/principals/recoverPrincipalPolicyHistory.js +108 -36
- package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +13 -0
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +150 -0
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -0
- package/workflows/principals/runtimePolicyRecovery.js +65 -0
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -0
- package/workflows/principals/runtimePolicyWarmer.js +5 -1
- package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
- package/workflows/sync/remoteResetPrincipalScope.js +10 -0
- package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentManifestPolicies.js","sourceRoot":"","sources":["documentManifestPolicies.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"documentManifestPolicies.js","sourceRoot":"","sources":["documentManifestPolicies.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,+BAA+B,GAEhC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AAYnF,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAAC,KAgB9D;IACC,MAAM,qBAAqB,GAAG,KAAK,CAAC,qBAAqB,IAAI,EAAE,CAAC;IAChE,MAAM,UAAU,GAAG,KAAK,CAAC,KAAK;SAC3B,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAChB,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,CAClB,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,wBAAwB,CACtD,CACF;SACA,MAAM,CACL,CAAC,SAAS,EAAE,EAAE,CACZ,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CACrC,+BAA+B,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CACvD,CACJ,CAAC;IACJ,IAAI,KAAK,CAAC,4BAA4B,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,qDAAqD,CACtD,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,4BAA4B;QAAE,OAAO,CAAC,GAAG,qBAAqB,CAAC,CAAC;IAC1E,OAAO;QACL,GAAG,qBAAqB;QACxB,GAAG,CAAC,MAAM,kCAAkC,CAAC;YAC3C,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;YAChD,UAAU;YACV,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;SACvE,CAAC,CAAC;KACJ,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oCAAoC,CAAC,KAMpD;IACC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;QAC/B,KAAK,MAAM,QAAQ,IAAI,IAAI,IAAI,EAAE,EAAE,CAAC;YAClC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;QACnD,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n principalPolicyMatchesReference,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ProjectionCheckpointContext } from \"./checkpointContext\";\nimport { collectReferencedPrincipalPolicies } from \"./principalPolicyVerification\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\n\nexport type UsedDocumentContainerManifests = Map<\n string,\n VerifiedContainerAccessManifest\n>;\n\nexport async function collectDocumentManifestPrincipalPolicies(input: {\n readonly authorizationEvidence?:\n | readonly PrincipalPolicyCheckpointEvidence[]\n | undefined;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly organizationId: string;\n readonly paths: readonly (\n | readonly VerifiedContainerAccessManifest[]\n | undefined\n )[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly requireAuthorizationEvidence?: boolean | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<PrincipalPolicyCheckpointEvidence[]> {\n const authorizationEvidence = input.authorizationEvidence ?? [];\n const references = input.paths\n .flatMap((path) =>\n (path ?? []).flatMap(\n (manifest) => manifest.state.referencedPrincipalHeads,\n ),\n )\n .filter(\n (reference) =>\n !authorizationEvidence.some((policy) =>\n principalPolicyMatchesReference({ policy, reference }),\n ),\n );\n if (input.requireAuthorizationEvidence && references.length > 0) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection omits required principal policy evidence\",\n );\n }\n if (input.requireAuthorizationEvidence) return [...authorizationEvidence];\n return [\n ...authorizationEvidence,\n ...(await collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n })),\n ];\n}\n\nexport function recordUsedDocumentContainerManifests(input: {\n readonly paths: readonly (\n | readonly VerifiedContainerAccessManifest[]\n | undefined\n )[];\n readonly used?: UsedDocumentContainerManifests | undefined;\n}): void {\n for (const path of input.paths) {\n for (const manifest of path ?? []) {\n input.used?.set(manifest.manifestHash, manifest);\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentManifestVerification.js","sourceRoot":"","sources":["documentManifestVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,EAIvB,6BAA6B,GAC9B,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,EACL,wCAAwC,EACxC,oCAAoC,GAErC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,EACL,kCAA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KAAK,CAAC,iBAAiB;QAC1C,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;QAC9D,sBAAsB,EAAE,IAAI;QAC5B,KAAK,EAAE,4BAA4B;QACnC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,cAAc;QACd,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["import {\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n type VerifiedDocumentLinkSetManifest,\n type VerifiedDocumentLinkSetSnapshot,\n verifyDocumentLinkSetManifest,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { readCanonicalJson } from \"../keyingCanonicalJson\";\nimport {\n addBundleByHash,\n assertCanonicalEqual,\n verifyAccessEventBundle,\n} from \"./bundleVerification\";\nimport type { ProjectionCheckpointContext } from \"./checkpointContext\";\nimport { resolveEventContainerPaths } from \"./documentDependencyPaths\";\nimport {\n collectDocumentManifestPrincipalPolicies,\n recordUsedDocumentContainerManifests,\n type UsedDocumentContainerManifests,\n} from \"./documentManifestPolicies\";\nimport { requireVerifiedDocumentPredecessor } from \"./documentManifestPredecessor\";\nimport {\n loadManifestCheckpointVerification,\n verifyCachedManifestCheckpoint,\n} from \"./manifestCheckpointVerification\";\nimport { readAccessManifest, readDocumentAccessEventBody } from \"./readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\n\ntype PolicyWarmer = ReferencedPrincipalPolicyWarmer | undefined;\n\nexport async function verifyDocumentManifestBundle(input: {\n readonly authorizationMembership?: \"current\" | \"referenced\" | undefined;\n readonly authorizationEvidence?:\n | readonly AnyVerifiedPrincipalPolicy[]\n | undefined;\n readonly bundle: AccessManifestBundleWireResponse;\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly enforceLocalCheckpoint: boolean;\n readonly label: string;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly requireAuthorizationEvidence?: boolean | undefined;\n readonly trustedPredecessorByHash?:\n | ReadonlyMap<string, VerifiedDocumentLinkSetSnapshot>\n | undefined;\n readonly usedContainerManifests?: UsedDocumentContainerManifests | undefined;\n readonly verifiedByHash: Map<string, VerifiedDocumentLinkSetManifest>;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}): Promise<VerifiedDocumentLinkSetManifest> {\n const cached = input.verifiedByHash.get(input.bundle.manifestHash);\n if (cached) {\n if (input.enforceLocalCheckpoint) {\n await verifyCachedManifestCheckpoint({\n current: cached,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: input.verifiedByHash,\n });\n }\n return cached;\n }\n\n const event = await verifyAccessEventBundle(input);\n const manifest = readAccessManifest(\n input.bundle.manifest,\n `${input.label} manifest`,\n );\n const previousManifest = requireVerifiedDocumentPredecessor({\n label: input.label,\n previousManifestHash: event.event.previousManifestHash,\n trustedPredecessorByHash: input.trustedPredecessorByHash,\n verifiedByHash: input.verifiedByHash,\n });\n const body = readDocumentAccessEventBody(\n event.body,\n `${input.label} event body`,\n );\n const { dependencyContainerPaths, targetContainerPath } =\n resolveEventContainerPaths({\n containerPathByManifestHash: input.containerPathByManifestHash,\n dependencyManifestHashes: event.event.dependencyManifestHashes,\n targetManifestHash: body.containerManifestHash,\n });\n const principalPolicies = await collectDocumentManifestPrincipalPolicies({\n authorizationEvidence: input.authorizationEvidence,\n checkpointContext: input.checkpointContext,\n organizationId: event.event.organizationId,\n paths: [...dependencyContainerPaths, targetContainerPath],\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n requireAuthorizationEvidence: input.requireAuthorizationEvidence,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const checkpointVerification = input.enforceLocalCheckpoint\n ? await loadManifestCheckpointVerification({\n current: manifest,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: input.verifiedByHash,\n })\n : null;\n const verified = await verifyDocumentLinkSetManifest({\n // Served heads and history were committed under the group membership their\n // cited container heads referenced; a signer removed since must still\n // verify on a cold device. The API verifier gates new writes at current.\n authorizationMembership: input.authorizationMembership ?? \"referenced\",\n authorizingContainerPaths: dependencyContainerPaths,\n event,\n expectedManifestHash: input.bundle.manifestHash,\n manifest,\n previousManifest,\n principalPolicies,\n ...(checkpointVerification ?? {}),\n ...(targetContainerPath ? { targetContainerPath } : {}),\n });\n if (!verified.ok) {\n throw new KeyingVerificationError(\n verified.error.code,\n `${input.label} manifest verification failed: ${verified.error.message}`,\n );\n }\n\n recordUsedDocumentContainerManifests({\n paths: [...dependencyContainerPaths, targetContainerPath],\n used: input.usedContainerManifests,\n });\n assertCanonicalEqual({\n actual: input.bundle.state,\n expected: readCanonicalJson(verified.value.state, `${input.label} state`),\n label: `${input.label} state`,\n });\n input.verifiedByHash.set(input.bundle.manifestHash, verified.value);\n\n return verified.value;\n}\n\nexport async function verifyDocumentProjectionManifests(\n input: Omit<\n Parameters<typeof verifyDocumentManifestBundle>[0],\n | \"bundle\"\n | \"bundlesByHash\"\n | \"enforceLocalCheckpoint\"\n | \"label\"\n | \"verifiedByHash\"\n > & { readonly projection: DocumentWriterProjectionResponse },\n) {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addBundleByHash(\n bundlesByHash,\n input.projection.documentManifest,\n \"Document writer projection manifest\",\n );\n const history = input.projection.documentManifestHistory;\n for (const [index, bundle] of history.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection manifest history[${index}]`,\n );\n }\n // An honest API never lists the head in its own history (it seeds the walk\n // with the head), so a repeat is a malformed or tampered projection and is\n // refused as such, rather than letting the head reach its verification\n // through the history cache and relying on the cached branch to re-run\n // every check the fresh path would.\n if (\n history.some(\n (bundle) =>\n bundle.manifestHash === input.projection.documentManifest.manifestHash,\n )\n ) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n \"Document writer projection history repeats the current head\",\n );\n }\n\n const verifiedByHash = new Map<string, VerifiedDocumentLinkSetManifest>();\n for (let index = history.length - 1; index >= 0; index -= 1) {\n const bundle = history[index];\n if (!bundle) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `Document writer projection manifest history[${index}] is missing`,\n );\n }\n await verifyDocumentManifestBundle({\n authorizationEvidence: input.authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle,\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n containerPathByManifestHash: input.containerPathByManifestHash,\n enforceLocalCheckpoint: false,\n label: `Document writer projection manifest history[${index}]`,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n }\n\n const headManifest = await verifyDocumentManifestBundle({\n authorizationEvidence: input.authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle: input.projection.documentManifest,\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n containerPathByManifestHash: input.containerPathByManifestHash,\n enforceLocalCheckpoint: true,\n label: \"Document writer projection\",\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n return { headManifest, verifiedByHash };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentManifestVerification.js","sourceRoot":"","sources":["documentManifestVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EAC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AK,EAAE,+CAA+C,KAAK,GAAG;YAC9D,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;YAChD,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,cAAc;YACd,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;SACvE,CAAC,CAAC;IACL,CAAC;IAED,MAAM,YAAY,GAAG,MAAM,4BAA4B,CAAC;QACtD,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,4BAA4B,EAAE,IAAI;QAClC,MAAM,EAAE,KAAK,CAAC,UAAU,CAAC,gBAAgB;QACzC,aAAa;QACb,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;QAC9D,sBAAsB,EAAE,IAAI;QAC5B,KAAK,EAAE,4BAA4B;QACnC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,cAAc;QACd,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n type VerifiedDocumentLinkSetManifest,\n type VerifiedDocumentLinkSetSnapshot,\n verifyDocumentLinkSetManifest,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { readCanonicalJson } from \"../keyingCanonicalJson\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport {\n addBundleByHash,\n assertCanonicalEqual,\n verifyAccessEventBundle,\n} from \"./bundleVerification\";\nimport type { ProjectionCheckpointContext } from \"./checkpointContext\";\nimport { resolveEventContainerPaths } from \"./documentDependencyPaths\";\nimport {\n collectDocumentManifestPrincipalPolicies,\n recordUsedDocumentContainerManifests,\n type UsedDocumentContainerManifests,\n} from \"./documentManifestPolicies\";\nimport { requireVerifiedDocumentPredecessor } from \"./documentManifestPredecessor\";\nimport {\n loadManifestCheckpointVerification,\n verifyCachedManifestCheckpoint,\n} from \"./manifestCheckpointVerification\";\nimport { readAccessManifest, readDocumentAccessEventBody } from \"./readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\n\ntype PolicyWarmer = ReferencedPrincipalPolicyWarmer | undefined;\n\nexport async function verifyDocumentManifestBundle(input: {\n readonly authorizationMembership?: \"current\" | \"referenced\" | undefined;\n readonly authorizationEvidence?:\n | readonly PrincipalPolicyCheckpointEvidence[]\n | undefined;\n readonly bundle: AccessManifestBundleWireResponse;\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly enforceLocalCheckpoint: boolean;\n readonly label: string;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly requireAuthorizationEvidence?: boolean | undefined;\n readonly trustedPredecessorByHash?:\n | ReadonlyMap<string, VerifiedDocumentLinkSetSnapshot>\n | undefined;\n readonly usedContainerManifests?: UsedDocumentContainerManifests | undefined;\n readonly verifiedByHash: Map<string, VerifiedDocumentLinkSetManifest>;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}): Promise<VerifiedDocumentLinkSetManifest> {\n const cached = input.verifiedByHash.get(input.bundle.manifestHash);\n if (cached) {\n if (input.enforceLocalCheckpoint) {\n await verifyCachedManifestCheckpoint({\n current: cached,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: input.verifiedByHash,\n });\n }\n return cached;\n }\n\n const event = await verifyAccessEventBundle(input);\n const manifest = readAccessManifest(\n input.bundle.manifest,\n `${input.label} manifest`,\n );\n const previousManifest = requireVerifiedDocumentPredecessor({\n label: input.label,\n previousManifestHash: event.event.previousManifestHash,\n trustedPredecessorByHash: input.trustedPredecessorByHash,\n verifiedByHash: input.verifiedByHash,\n });\n const body = readDocumentAccessEventBody(\n event.body,\n `${input.label} event body`,\n );\n const { dependencyContainerPaths, targetContainerPath } =\n resolveEventContainerPaths({\n containerPathByManifestHash: input.containerPathByManifestHash,\n dependencyManifestHashes: event.event.dependencyManifestHashes,\n targetManifestHash: body.containerManifestHash,\n });\n const principalPolicies = await collectDocumentManifestPrincipalPolicies({\n authorizationEvidence: input.authorizationEvidence,\n checkpointContext: input.checkpointContext,\n organizationId: event.event.organizationId,\n paths: [...dependencyContainerPaths, targetContainerPath],\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n requireAuthorizationEvidence: input.requireAuthorizationEvidence,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const checkpointVerification = input.enforceLocalCheckpoint\n ? await loadManifestCheckpointVerification({\n current: manifest,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: input.verifiedByHash,\n })\n : null;\n const verified = await verifyDocumentLinkSetManifest({\n // Served heads and history were committed under the group membership their\n // cited container heads referenced; a signer removed since must still\n // verify on a cold device. The API verifier gates new writes at current.\n authorizationMembership: input.authorizationMembership ?? \"referenced\",\n authorizingContainerPaths: dependencyContainerPaths,\n event,\n expectedManifestHash: input.bundle.manifestHash,\n manifest,\n previousManifest,\n principalPolicies,\n ...(checkpointVerification ?? {}),\n ...(targetContainerPath ? { targetContainerPath } : {}),\n });\n if (!verified.ok) {\n throw new KeyingVerificationError(\n verified.error.code,\n `${input.label} manifest verification failed: ${verified.error.message}`,\n );\n }\n\n recordUsedDocumentContainerManifests({\n paths: [...dependencyContainerPaths, targetContainerPath],\n used: input.usedContainerManifests,\n });\n assertCanonicalEqual({\n actual: input.bundle.state,\n expected: readCanonicalJson(verified.value.state, `${input.label} state`),\n label: `${input.label} state`,\n });\n input.verifiedByHash.set(input.bundle.manifestHash, verified.value);\n\n return verified.value;\n}\n\nexport async function verifyDocumentProjectionManifests(\n input: Omit<\n Parameters<typeof verifyDocumentManifestBundle>[0],\n | \"bundle\"\n | \"bundlesByHash\"\n | \"enforceLocalCheckpoint\"\n | \"label\"\n | \"verifiedByHash\"\n > & { readonly projection: DocumentWriterProjectionResponse },\n) {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addBundleByHash(\n bundlesByHash,\n input.projection.documentManifest,\n \"Document writer projection manifest\",\n );\n const history = input.projection.documentManifestHistory;\n for (const [index, bundle] of history.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection manifest history[${index}]`,\n );\n }\n // An honest API never lists the head in its own history (it seeds the walk\n // with the head), so a repeat is a malformed or tampered projection and is\n // refused as such, rather than letting the head reach its verification\n // through the history cache and relying on the cached branch to re-run\n // every check the fresh path would.\n if (\n history.some(\n (bundle) =>\n bundle.manifestHash === input.projection.documentManifest.manifestHash,\n )\n ) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n \"Document writer projection history repeats the current head\",\n );\n }\n\n const verifiedByHash = new Map<string, VerifiedDocumentLinkSetManifest>();\n for (let index = history.length - 1; index >= 0; index -= 1) {\n const bundle = history[index];\n if (!bundle) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `Document writer projection manifest history[${index}] is missing`,\n );\n }\n await verifyDocumentManifestBundle({\n authorizationEvidence: input.authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle,\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n containerPathByManifestHash: input.containerPathByManifestHash,\n enforceLocalCheckpoint: false,\n label: `Document writer projection manifest history[${index}]`,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n }\n\n const headManifest = await verifyDocumentManifestBundle({\n authorizationEvidence: input.authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle: input.projection.documentManifest,\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n containerPathByManifestHash: input.containerPathByManifestHash,\n enforceLocalCheckpoint: true,\n label: \"Document writer projection\",\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n return { headManifest, verifiedByHash };\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { VerifiedContainerAccessManifest, VerifiedDocumentLinkSetManifest } from "../../internal/crypto/index.js";
|
|
2
2
|
import type { DocumentWriterProjectionResponse } from "../../internal/validators/response/index.js";
|
|
3
|
+
import type { PrincipalPolicyCheckpointEvidence } from "../principals/principalPolicyEvidence.js";
|
|
3
4
|
import type { ExecSql } from "../sqlite/sqlSchema.js";
|
|
4
5
|
import type { PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "./types.js";
|
|
5
6
|
type VerifiedManifestMap = Map<string, VerifiedContainerAccessManifest>;
|
|
@@ -17,7 +18,7 @@ interface DocumentWriterProjectionVerificationInput {
|
|
|
17
18
|
export interface DocumentWriterProjectionAuthorization {
|
|
18
19
|
readonly containerPathByManifestHash: ReadonlyMap<string, readonly VerifiedContainerAccessManifest[]>;
|
|
19
20
|
readonly documentManifestByHash: ReadonlyMap<string, VerifiedDocumentLinkSetManifest>;
|
|
20
|
-
readonly principalPolicies: readonly
|
|
21
|
+
readonly principalPolicies: readonly PrincipalPolicyCheckpointEvidence[];
|
|
21
22
|
}
|
|
22
23
|
export declare function verifyDocumentWriterProjection(input: DocumentWriterProjectionVerificationInput): Promise<VerifiedDocumentLinkSetManifest>;
|
|
23
24
|
export declare function verifyDocumentWriterProjectionAuthorization(input: DocumentWriterProjectionVerificationInput): Promise<DocumentWriterProjectionAuthorization>;
|
|
@@ -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ClB,CAAC;QACF,MAAM,6BAA6B,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;QAC9D,+BAA+B,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAClD,OAAO,QAAQ,CAAC,aAAa,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import { retainVerifiedProjectionHistory } from \"@tearleads/api-client\";\nimport type {\n AnyVerifiedPrincipalPolicy,\n VerifiedContainerAccessManifest,\n VerifiedDocumentLinkSetManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"./bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n type ProjectionCheckpointContext,\n} from \"./checkpointContext\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\nimport {\n addContainerWriterProjectionBundles,\n verifiedContainerManifestsForBundles,\n verifyContainerWriterProjectionWithContext,\n} from \"./containerProjectionVerification\";\nimport { documentContainerProjections } from \"./documentContainerProjections\";\nimport { verifyDocumentProjectionManifests } from \"./documentManifestVerification\";\nimport { rejectPurgedDocumentProjection } from \"./documentPurgeCheckpointEnforcement\";\nimport { throwKeyingVerificationShapeFailure } from \"./error\";\nimport { verifyProjectionAuthorizationEvidence } from \"./projectionAuthorizationEvidence\";\nimport { readAccessManifest } from \"./readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nimport { withGenerationGuardedPolicyWarmer } from \"./types\";\n\ntype VerifiedManifestMap = Map<string, VerifiedContainerAccessManifest>;\ntype PolicyWarmer = ReferencedPrincipalPolicyWarmer | undefined;\n\nfunction readDocumentProjectionContainerPaths(\n projection: DocumentWriterProjectionResponse,\n): AccessManifestBundleWireResponse[][] {\n return [\n ...projection.documentManifestContainerPaths,\n ...projection.authorizingContainerPaths.map((path) => path.path),\n ];\n}\n\nfunction collectDocumentProjectionContainerBundles(\n projection: DocumentWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n for (const [index, authorizing] of documentContainerProjections(\n projection,\n ).entries()) {\n addContainerWriterProjectionBundles(\n bundlesByHash,\n authorizing,\n `Document writer projection authorizing path[${index}]`,\n );\n }\n for (const [index, path] of readDocumentProjectionContainerPaths(\n projection,\n ).entries()) {\n for (const [pathIndex, bundle] of path.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection dependency path[${index}][${pathIndex}]`,\n );\n }\n }\n for (const [\n index,\n bundle,\n ] of projection.documentContainerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection container history[${index}]`,\n );\n }\n return bundlesByHash;\n}\n\nasync function verifyProjectionContainerPaths(input: {\n readonly authorizationEvidence: readonly AnyVerifiedPrincipalPolicy[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}): Promise<Map<string, readonly VerifiedContainerAccessManifest[]>> {\n const bundlesByHash = collectDocumentProjectionContainerBundles(\n input.projection,\n );\n const containerPathByManifestHash = new Map<\n string,\n readonly VerifiedContainerAccessManifest[]\n >();\n // Reuse a caller-supplied cache when provided so a later unwrap pass over the\n // same authorizing container paths does not re-verify identical manifests.\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n for (const projection of documentContainerProjections(input.projection)) {\n const path = await verifyContainerWriterProjectionWithContext(\n {\n authorizationEvidence: input.authorizationEvidence,\n principalPolicyCache: input.principalPolicyCache,\n projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n },\n input.checkpointContext,\n );\n const leaf = path.at(-1);\n if (leaf) {\n containerPathByManifestHash.set(leaf.manifestHash, path);\n }\n for (const manifest of path) {\n verifiedByHash.set(manifest.manifestHash, manifest);\n }\n }\n // Grouping supplies evidence only; each signed artifact selects its citations.\n for (const [\n index,\n path,\n ] of input.projection.documentManifestContainerPaths.entries()) {\n // Historical dependency evidence is verified without current checkpoint\n // enforcement. Its grouping cannot substitute an uncited ancestor into\n // document or content-write authorization.\n const verifiedPath = await verifyContainerManifestPath({\n authorizationEvidence: input.authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: false,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoints: false,\n label: `Document writer projection dependency path[${index}]`,\n path,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The authorizing path recorded for the same leaf takes precedence.\n const leaf = verifiedPath.at(-1);\n if (leaf && !containerPathByManifestHash.has(leaf.manifestHash)) {\n containerPathByManifestHash.set(leaf.manifestHash, verifiedPath);\n }\n }\n\n // Keep every verified head as evidence. Events and content headers select\n // their own signed paths through resolveEventContainerPaths.\n for (const [hash, manifest] of verifiedByHash) {\n if (!containerPathByManifestHash.has(hash))\n containerPathByManifestHash.set(hash, [manifest]);\n }\n\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: [],\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n return containerPathByManifestHash;\n}\n\ninterface DocumentWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}\nexport interface DocumentWriterProjectionAuthorization {\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly documentManifestByHash: ReadonlyMap<\n string,\n VerifiedDocumentLinkSetManifest\n >;\n readonly principalPolicies: readonly AnyVerifiedPrincipalPolicy[];\n}\n\ninterface VerifiedDocumentWriterProjectionResult {\n readonly authorization: DocumentWriterProjectionAuthorization;\n readonly headManifest: VerifiedDocumentLinkSetManifest;\n}\n\nasync function verifyDocumentWriterProjectionWithContext(\n input: Omit<DocumentWriterProjectionVerificationInput, \"execSql\">,\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedDocumentWriterProjectionResult> {\n const principalPolicyCache =\n input.principalPolicyCache ?? new Map<string, VerifiedPrincipalPolicy>();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [\n ...collectDocumentProjectionContainerBundles(input.projection).values(),\n ],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: readAccessManifest(\n input.projection.documentManifest.manifest,\n \"Document projection manifest\",\n ).organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n });\n const containerPathByManifestHash = await verifyProjectionContainerPaths({\n authorizationEvidence,\n checkpointContext,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const { headManifest, verifiedByHash } =\n await verifyDocumentProjectionManifests({\n authorizationEvidence,\n checkpointContext,\n containerPathByManifestHash,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await rejectPurgedDocumentProjection(\n headManifest.state.documentId,\n checkpointContext.execSql,\n );\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: [headManifest],\n verifiedManifests: [...verifiedByHash.values()],\n });\n\n return {\n authorization: {\n containerPathByManifestHash,\n documentManifestByHash: verifiedByHash,\n principalPolicies: authorizationEvidence,\n },\n headManifest,\n };\n}\n\nexport async function verifyDocumentWriterProjection(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<VerifiedDocumentLinkSetManifest> {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n retainVerifiedProjectionHistory(input.projection);\n return verified.headManifest;\n}\n\nexport async function verifyDocumentWriterProjectionAuthorization(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<DocumentWriterProjectionAuthorization> {\n try {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n retainVerifiedProjectionHistory(input.projection);\n return verified.authorization;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentProjectionVerification.js","sourceRoot":"","sources":["documentProjectionVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,uBAAuB,CAAC;AAYxE,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,GAEjC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,2BAA2B,EAAE,MAAM,6B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AccessManifest,\n VerifiedDocumentLinkSetManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"./bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n type ProjectionCheckpointContext,\n} from \"./checkpointContext\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\nimport {\n addContainerWriterProjectionBundles,\n verifiedContainerManifestsForBundles,\n verifyContainerWriterProjectionWithContext,\n} from \"./containerProjectionVerification\";\nimport { documentContainerProjections } from \"./documentContainerProjections\";\nimport { verifyDocumentProjectionManifests } from \"./documentManifestVerification\";\nimport { rejectPurgedDocumentProjection } from \"./documentPurgeCheckpointEnforcement\";\nimport { throwKeyingVerificationShapeFailure } from \"./error\";\nimport { verifyProjectionAuthorizationEvidence } from \"./projectionAuthorizationEvidence\";\nimport { readAccessManifest } from \"./readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nimport { withGenerationGuardedPolicyWarmer } from \"./types\";\n\ntype VerifiedManifestMap = Map<string, VerifiedContainerAccessManifest>;\ntype PolicyWarmer = ReferencedPrincipalPolicyWarmer | undefined;\n\nfunction readDocumentProjectionContainerPaths(\n projection: DocumentWriterProjectionResponse,\n): AccessManifestBundleWireResponse[][] {\n return [\n ...projection.documentManifestContainerPaths,\n ...projection.authorizingContainerPaths.map((path) => path.path),\n ];\n}\n\nfunction collectDocumentProjectionContainerBundles(\n projection: DocumentWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n for (const [index, authorizing] of documentContainerProjections(\n projection,\n ).entries()) {\n addContainerWriterProjectionBundles(\n bundlesByHash,\n authorizing,\n `Document writer projection authorizing path[${index}]`,\n );\n }\n for (const [index, path] of readDocumentProjectionContainerPaths(\n projection,\n ).entries()) {\n for (const [pathIndex, bundle] of path.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection dependency path[${index}][${pathIndex}]`,\n );\n }\n }\n for (const [\n index,\n bundle,\n ] of projection.documentContainerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection container history[${index}]`,\n );\n }\n return bundlesByHash;\n}\n\nasync function verifyProjectionContainerPaths(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyCheckpointEvidence[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}): Promise<Map<string, readonly VerifiedContainerAccessManifest[]>> {\n const bundlesByHash = collectDocumentProjectionContainerBundles(\n input.projection,\n );\n const containerPathByManifestHash = new Map<\n string,\n readonly VerifiedContainerAccessManifest[]\n >();\n // Reuse a caller-supplied cache when provided so a later unwrap pass over the\n // same authorizing container paths does not re-verify identical manifests.\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n for (const projection of documentContainerProjections(input.projection)) {\n const path = await verifyContainerWriterProjectionWithContext(\n {\n authorizationEvidence: input.authorizationEvidence,\n principalPolicyCache: input.principalPolicyCache,\n projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n },\n input.checkpointContext,\n );\n const leaf = path.at(-1);\n if (leaf) {\n containerPathByManifestHash.set(leaf.manifestHash, path);\n }\n for (const manifest of path) {\n verifiedByHash.set(manifest.manifestHash, manifest);\n }\n }\n // Grouping supplies evidence only; each signed artifact selects its citations.\n for (const [\n index,\n path,\n ] of input.projection.documentManifestContainerPaths.entries()) {\n // Historical dependency evidence is verified without current checkpoint\n // enforcement. Its grouping cannot substitute an uncited ancestor into\n // document or content-write authorization.\n const verifiedPath = await verifyContainerManifestPath({\n authorizationEvidence: input.authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: false,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoints: false,\n label: `Document writer projection dependency path[${index}]`,\n path,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The authorizing path recorded for the same leaf takes precedence.\n const leaf = verifiedPath.at(-1);\n if (leaf && !containerPathByManifestHash.has(leaf.manifestHash)) {\n containerPathByManifestHash.set(leaf.manifestHash, verifiedPath);\n }\n }\n\n // Keep every verified head as evidence. Events and content headers select\n // their own signed paths through resolveEventContainerPaths.\n for (const [hash, manifest] of verifiedByHash) {\n if (!containerPathByManifestHash.has(hash))\n containerPathByManifestHash.set(hash, [manifest]);\n }\n\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: [],\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n return containerPathByManifestHash;\n}\n\ninterface DocumentWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}\nexport interface DocumentWriterProjectionAuthorization {\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly documentManifestByHash: ReadonlyMap<\n string,\n VerifiedDocumentLinkSetManifest\n >;\n readonly principalPolicies: readonly PrincipalPolicyCheckpointEvidence[];\n}\n\ninterface VerifiedDocumentWriterProjectionResult {\n readonly authorization: DocumentWriterProjectionAuthorization;\n readonly headManifest: VerifiedDocumentLinkSetManifest;\n}\n\nasync function verifyDocumentWriterProjectionWithContext(\n input: Omit<DocumentWriterProjectionVerificationInput, \"execSql\">,\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedDocumentWriterProjectionResult> {\n const principalPolicyCache =\n input.principalPolicyCache ?? new Map<string, VerifiedPrincipalPolicy>();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [\n ...collectDocumentProjectionContainerBundles(input.projection).values(),\n ],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: readAccessManifest(\n input.projection.documentManifest.manifest,\n \"Document projection manifest\",\n ).organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n });\n const containerPathByManifestHash = await verifyProjectionContainerPaths({\n authorizationEvidence,\n checkpointContext,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const { headManifest, verifiedByHash } =\n await verifyDocumentProjectionManifests({\n authorizationEvidence,\n checkpointContext,\n containerPathByManifestHash,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await rejectPurgedDocumentProjection(\n headManifest.state.documentId,\n checkpointContext.execSql,\n );\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: [headManifest],\n verifiedManifests: [...verifiedByHash.values()],\n });\n\n return {\n authorization: {\n containerPathByManifestHash,\n documentManifestByHash: verifiedByHash,\n principalPolicies: authorizationEvidence,\n },\n headManifest,\n };\n}\n\nexport async function verifyDocumentWriterProjection(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<VerifiedDocumentLinkSetManifest> {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n retainVerifiedProjectionHistory(input.projection);\n return verified.headManifest;\n}\n\nexport async function verifyDocumentWriterProjectionAuthorization(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<DocumentWriterProjectionAuthorization> {\n try {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n retainVerifiedProjectionHistory(input.projection);\n return verified.authorization;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
|
|
@@ -14,11 +14,16 @@ export async function rememberRootBoundOrganizationFounder(input) {
|
|
|
14
14
|
return;
|
|
15
15
|
const organization = input.policies?.find((policy) => policy.principalType === "organization" &&
|
|
16
16
|
policy.principalId === root.state.organizationId);
|
|
17
|
-
|
|
18
|
-
// the complete signed chain needed to authenticate genesis.
|
|
19
|
-
if (!organization?.history)
|
|
17
|
+
if (!organization)
|
|
20
18
|
return;
|
|
21
|
-
const
|
|
19
|
+
const entries = "retainedHistory" in organization
|
|
20
|
+
? organization.retainedHistory
|
|
21
|
+
: organization.history;
|
|
22
|
+
if (!entries)
|
|
23
|
+
return;
|
|
24
|
+
const genesis = entries.find(({ state }) => state.version === 1)?.state;
|
|
25
|
+
if (!genesis)
|
|
26
|
+
throw new KeyingVerificationError("missing_dependency", "Organization founder requires verified genesis");
|
|
22
27
|
const created = verifiedContainerCreateManifest({
|
|
23
28
|
head: root,
|
|
24
29
|
label: "Organization founder root",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationFounderBinding.js","sourceRoot":"","sources":["organizationFounderBinding.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"organizationFounderBinding.js","sourceRoot":"","sources":["organizationFounderBinding.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,2BAA2B,EAAE,MAAM,+CAA+C,CAAC;AAG5F,OAAO,EAAE,+BAA+B,EAAE,MAAM,2BAA2B,CAAC;AAE5E;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAK1D;IACC,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC;IACvB,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,UAAU,KAAK,IAAI;QAAE,OAAO;IACpD,MAAM,YAAY,GAAG,KAAK,CAAC,QAAQ,EAAE,IAAI,CACvC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,cAAc;QACvC,MAAM,CAAC,WAAW,KAAK,IAAI,CAAC,KAAK,CAAC,cAAc,CACnD,CAAC;IACF,IAAI,CAAC,YAAY;QAAE,OAAO;IAC1B,MAAM,OAAO,GACX,iBAAiB,IAAI,YAAY;QAC/B,CAAC,CAAC,YAAY,CAAC,eAAe;QAC9B,CAAC,CAAC,YAAY,CAAC,OAAO,CAAC;IAC3B,IAAI,CAAC,OAAO;QAAE,OAAO;IACrB,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC;IACxE,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,gDAAgD,CACjD,CAAC;IACJ,MAAM,OAAO,GAAG,+BAA+B,CAAC;QAC9C,IAAI,EAAE,IAAI;QACV,KAAK,EAAE,2BAA2B;QAClC,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;IACH,IACE,OAAO,EAAE,YAAY,KAAK,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,YAAY;QAC1D,OAAO,CAAC,wBAAwB;YAC9B,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,oBAAoB;QAE1C,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,0EAA0E,CAC3E,CAAC;IACJ,MAAM,2BAA2B,CAAC;QAChC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { rememberOrganizationFounder } from \"../persistence/organizationFounderPersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { verifiedContainerCreateManifest } from \"./containerCreateManifest\";\n\n/**\n * A directory can cite someone else's public policies. Bind its founder to the\n * verified personal root's creator before trusting it to authorize a rehome.\n * Metadata roots can be created by later admins and cannot establish this pin.\n * This immutable identity anchor survives read-only verification and canceled\n * views; it neither advances nor replaces a current-policy checkpoint.\n */\nexport async function rememberRootBoundOrganizationFounder(input: {\n readonly execSql: ExecSql;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[] | undefined;\n readonly root: VerifiedContainerAccessManifest | undefined;\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): Promise<void> {\n const { root } = input;\n if (!root || root.state.systemSlot !== null) return;\n const organization = input.policies?.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === root.state.organizationId,\n );\n if (!organization) return;\n const entries =\n \"retainedHistory\" in organization\n ? organization.retainedHistory\n : organization.history;\n if (!entries) return;\n const genesis = entries.find(({ state }) => state.version === 1)?.state;\n if (!genesis)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization founder requires verified genesis\",\n );\n const created = verifiedContainerCreateManifest({\n head: root,\n label: \"Organization founder root\",\n verifiedByHash: input.verifiedByHash,\n });\n if (\n genesis?.signerUserId !== created.event.event.signerUserId ||\n genesis.signerUserKeyFingerprint !==\n created.event.event.signerKeyFingerprint\n )\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"Organization founder does not match its verified personal root's creator\",\n );\n await rememberOrganizationFounder({\n execSql: input.execSql,\n organization,\n });\n}\n"]}
|
|
@@ -3,6 +3,7 @@ import { loadPrincipalPolicyCheckpoint } from "../persistence/keyingCheckpointPe
|
|
|
3
3
|
import { verifiedPrincipalPolicyMeetsCheckpoint } from "../persistence/principalPolicyCheckpointSelection.js";
|
|
4
4
|
import { loadPrincipalPolicyBundleForReference } from "../persistence/principalPolicyReferencePersistence.js";
|
|
5
5
|
import { principalStateMatchesReference } from "../principalPolicyStates.js";
|
|
6
|
+
import { principalPolicyEvidenceEntries, } from "../principals/principalPolicyEvidence.js";
|
|
6
7
|
/**
|
|
7
8
|
* Cache key for a referenced principal policy. The in-memory principal-policy
|
|
8
9
|
* cache is populated and read from several call sites; they must agree on this
|
|
@@ -35,9 +36,7 @@ export function dedupeReferencedPrincipalStates(references) {
|
|
|
35
36
|
export function principalPolicyCacheForVerifiedPolicies(policies) {
|
|
36
37
|
const cache = new Map();
|
|
37
38
|
for (const policy of policies) {
|
|
38
|
-
const states = policy.
|
|
39
|
-
policy.state,
|
|
40
|
-
];
|
|
39
|
+
const states = principalPolicyEvidenceEntries(policy).map((entry) => entry.state);
|
|
41
40
|
for (const state of states) {
|
|
42
41
|
cache.set(referencedPrincipalPolicyKey({
|
|
43
42
|
principalType: state.principalType,
|
|
@@ -52,7 +51,7 @@ export function principalPolicyCacheForVerifiedPolicies(policies) {
|
|
|
52
51
|
return cache;
|
|
53
52
|
}
|
|
54
53
|
export function verifiedPrincipalPolicyContainsReference(policy, reference) {
|
|
55
|
-
const states = policy.
|
|
54
|
+
const states = principalPolicyEvidenceEntries(policy).map(({ state }) => state);
|
|
56
55
|
return states.some((state) => principalStateMatchesReference(state, reference));
|
|
57
56
|
}
|
|
58
57
|
// Identify which referenced policies are absent from both the in-memory cache
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyCache.js","sourceRoot":"","sources":["principalPolicyCache.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"principalPolicyCache.js","sourceRoot":"","sources":["principalPolicyCache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAC;AAC3F,OAAO,EAAE,sCAAsC,EAAE,MAAM,mDAAmD,CAAC;AAC3G,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,8BAA8B,EAAE,MAAM,0BAA0B,CAAC;AAC1E,OAAO,EAEL,8BAA8B,GAC/B,MAAM,uCAAuC,CAAC;AAG/C;;;;;GAKG;AACH,MAAM,UAAU,4BAA4B,CAC1C,SAAkC;IAElC,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,SAAS,CAAC,aAAa;QACvB,SAAS,CAAC,WAAW;QACrB,SAAS,CAAC,OAAO;QACjB,SAAS,CAAC,SAAS;QACnB,SAAS,CAAC,QAAQ;QAClB,SAAS,CAAC,cAAc;KACzB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAE7C,UAAqC;IACrC,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAsB,CAAC;IACxD,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,iBAAiB,CAAC,GAAG,CAAC,4BAA4B,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC,CAAC;IAC5E,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAA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AM,UAAU,GAAG,MAAM,6BAA6B,CACpD,KAAK,CAAC,OAAO,EACb,SAAS,CAAC,aAAa,EACvB,SAAS,CAAC,WAAW,CACtB,CAAC;QACF,MAAM,YAAY,GAAG,KAAK,CAAC,oBAAoB,CAAC,GAAG,CACjD,4BAA4B,CAAC,SAAS,CAAC,CACxC,CAAC;QACF,IAAI,YAAY,EAAE,CAAC;YACjB,IACE,CAAC,wCAAwC,CAAC,YAAY,EAAE,SAAS,CAAC,EAClE,CAAC;gBACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,qEAAqE,CACtE,CAAC;YACJ,CAAC;YACD,IAAI,sCAAsC,CAAC,YAAY,EAAE,UAAU,CAAC,EAAE,CAAC;gBACrE,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,qCAAqC,CACxD,KAAK,CAAC,OAAO,EACb,SAAS,EACT,UAAU,CACX,CAAC;QACF,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACnC,CAAC,CAAC,CACH,CAAC;IACF,OAAO,OAAO,CAAC,MAAM,CACnB,CAAC,SAAS,EAAwC,EAAE,CAAC,SAAS,KAAK,IAAI,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../persistence/keyingCheckpointPersistence\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"../persistence/principalPolicyCheckpointSelection\";\nimport { loadPrincipalPolicyBundleForReference } from \"../persistence/principalPolicyReferencePersistence\";\nimport { principalStateMatchesReference } from \"../principalPolicyStates\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\n\n/**\n * Cache key for a referenced principal policy. The in-memory principal-policy\n * cache is populated and read from several call sites; they must agree on this\n * format byte-for-byte or a populated entry looks uncached (extra warm fetches)\n * — so this is the single source of truth, imported rather than re-declared.\n */\nexport function referencedPrincipalPolicyKey(\n reference: ReferencedPrincipalHead,\n): string {\n return JSON.stringify([\n reference.principalType,\n reference.principalId,\n reference.version,\n reference.stateHash,\n reference.keyEpoch,\n reference.keyFingerprint,\n ]);\n}\n\n/**\n * Dedupes references by their exact head identity, keyed with\n * {@link referencedPrincipalPolicyKey} so every consumer agrees on what\n * \"the same reference\" means. Later duplicates win, preserving each\n * caller's original last-wins behavior.\n */\nexport function dedupeReferencedPrincipalStates<\n TReference extends ReferencedPrincipalHead,\n>(references: ReadonlyArray<TReference>): TReference[] {\n const referencesByState = new Map<string, TReference>();\n for (const reference of references) {\n referencesByState.set(referencedPrincipalPolicyKey(reference), reference);\n }\n return Array.from(referencesByState.values());\n}\n\nexport function principalPolicyCacheForVerifiedPolicies(\n policies: readonly PrincipalPolicyCurrentEvidence[],\n): Map<string, PrincipalPolicyCurrentEvidence> {\n const cache = new Map<string, PrincipalPolicyCurrentEvidence>();\n for (const policy of policies) {\n const states = principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.state,\n );\n for (const state of states) {\n cache.set(\n referencedPrincipalPolicyKey({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash: state.stateHash,\n keyFingerprint: state.keyFingerprint,\n }),\n policy,\n );\n }\n }\n return cache;\n}\n\nexport function verifiedPrincipalPolicyContainsReference(\n policy: PrincipalPolicyCurrentEvidence,\n reference: ReferencedPrincipalHead,\n): boolean {\n const states = principalPolicyEvidenceEntries(policy).map(\n ({ state }) => state,\n );\n return states.some((state) =>\n principalStateMatchesReference(state, reference),\n );\n}\n\n// Identify which referenced policies are absent from both the in-memory cache\n// and local storage, so the warmer fetches only what is genuinely missing.\nexport async function filterUncachedPrincipalPolicyReferences(input: {\n execSql: ExecSql;\n principalPolicyCache: ReadonlyMap<string, PrincipalPolicyCurrentEvidence>;\n references: readonly ReferencedPrincipalHead[];\n}): Promise<ReferencedPrincipalHead[]> {\n const results = await Promise.all(\n input.references.map(async (reference) => {\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n reference.principalType,\n reference.principalId,\n );\n const cachedPolicy = input.principalPolicyCache.get(\n referencedPrincipalPolicyKey(reference),\n );\n if (cachedPolicy) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, checkpoint)) {\n return null;\n }\n }\n const bundle = await loadPrincipalPolicyBundleForReference(\n input.execSql,\n reference,\n checkpoint,\n );\n return bundle ? null : reference;\n }),\n );\n return results.filter(\n (reference): reference is ReferencedPrincipalHead => reference !== null,\n );\n}\n"]}
|
|
@@ -10,6 +10,7 @@ import { observePrincipalPolicy, } from "./checkpointContext.js";
|
|
|
10
10
|
import { ProjectionDependencyUnavailableError } from "./dependencyUnavailable.js";
|
|
11
11
|
import { rethrowProjectionVerificationBoundaryError } from "./error.js";
|
|
12
12
|
import { filterUncachedPrincipalPolicyReferences, referencedPrincipalPolicyKey, verifiedPrincipalPolicyContainsReference, } from "./principalPolicyCache.js";
|
|
13
|
+
import { resolveReferencedPrincipalPolicy } from "./resolvedPrincipalPolicy.js";
|
|
13
14
|
import { assertProjectionVerificationCurrent, generationGuardedPrincipalPolicyWarmer, } from "./types.js";
|
|
14
15
|
function principalPolicyReferenceLabel(reference) {
|
|
15
16
|
return `${reference.principalType}:${reference.principalId}@${reference.version}`;
|
|
@@ -158,7 +159,7 @@ async function verifyReferencedPrincipalPolicy(input) {
|
|
|
158
159
|
const cachedPolicy = input.principalPolicyCache.get(cacheKey);
|
|
159
160
|
const execSql = input.checkpointContext.execSql;
|
|
160
161
|
const localCheckpoint = await loadPrincipalPolicyCheckpoint(execSql, input.reference.principalType, input.reference.principalId);
|
|
161
|
-
if (cachedPolicy) {
|
|
162
|
+
if (cachedPolicy && !("retainedHistory" in cachedPolicy)) {
|
|
162
163
|
if (!verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)) {
|
|
163
164
|
throw new KeyingVerificationError("hash_mismatch", "in-memory principal policy cache does not match its exact reference");
|
|
164
165
|
}
|
|
@@ -169,6 +170,11 @@ async function verifyReferencedPrincipalPolicy(input) {
|
|
|
169
170
|
}
|
|
170
171
|
const referenceLabel = principalPolicyReferenceLabel(input.reference);
|
|
171
172
|
let bundle = await loadPrincipalPolicyBundleForReference(execSql, input.reference, localCheckpoint);
|
|
173
|
+
if (!bundle) {
|
|
174
|
+
const recovered = await resolveReferencedPrincipalPolicy(input);
|
|
175
|
+
if (recovered)
|
|
176
|
+
return recovered;
|
|
177
|
+
}
|
|
172
178
|
if (!bundle && input.warmReferencedPrincipalPolicies) {
|
|
173
179
|
// The reference is not cached locally — the common case for a member who
|
|
174
180
|
// gained access via another org's group grant and never hydrated that
|
|
@@ -216,7 +222,8 @@ export async function collectReferencedPrincipalPolicies(input) {
|
|
|
216
222
|
// Warm every missing reference in one batched fetch before verifying, so a
|
|
217
223
|
// path that references several uncached policies makes a single round of
|
|
218
224
|
// requests rather than one per reference.
|
|
219
|
-
if (warmReferencedPrincipalPolicies
|
|
225
|
+
if (warmReferencedPrincipalPolicies &&
|
|
226
|
+
!warmReferencedPrincipalPolicies.resolveReference) {
|
|
220
227
|
const uncached = await filterUncachedPrincipalPolicyReferences({
|
|
221
228
|
execSql: input.checkpointContext.execSql,
|
|
222
229
|
principalPolicyCache: input.principalPolicyCache,
|
|
@@ -231,11 +238,14 @@ export async function collectReferencedPrincipalPolicies(input) {
|
|
|
231
238
|
assertProjectionVerificationCurrent(input.stillCurrent);
|
|
232
239
|
}
|
|
233
240
|
}
|
|
241
|
+
const recoveryBatch = {};
|
|
234
242
|
return Promise.all(references.map((reference) => verifyReferencedPrincipalPolicy({
|
|
243
|
+
recoveryBatch,
|
|
235
244
|
checkpointContext: input.checkpointContext,
|
|
236
245
|
organizationId: input.organizationId,
|
|
237
246
|
principalPolicyCache: input.principalPolicyCache,
|
|
238
247
|
reference,
|
|
248
|
+
stillCurrent: input.stillCurrent,
|
|
239
249
|
resolveUserKey: input.resolveUserKey,
|
|
240
250
|
warmReferencedPrincipalPolicies,
|
|
241
251
|
})));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,aAAa,EAEb,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAC;AAC3F,OAAO,EACL,kCAAkC,EAClC,sCAAsC,GACvC,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,yBAAyB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,kCAAkC,EAClC,kCAAkC,EAClC,6BAA6B,EAC7B,yDAAyD,GAC1D,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,sBAAsB,GAEvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,oCAAoC,EAAE,MAAM,yBAAyB,CAAC;AAC/E,OAAO,EAAE,0CAA0C,EAAE,MAAM,SAAS,CAAC;AACrE,OAAO,EACL,uCAAuC,EACvC,4BAA4B,EAC5B,wCAAwC,GACzC,MAAM,wBAAwB,CAAC;AAMhC,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GACvC,MAAM,SAAS,CAAC;AAEjB,SAAS,6BAA6B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mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACxD,MAAM,+BAA+B,CAAC;gBACpC,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,UAAU,EAAE,QAAQ;aACrB,CAAC,CAAC;YACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QAC1D,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC,GAAG,CAChB,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAC3B,+BAA+B,CAAC;QAC9B,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,SAAS;QACT,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B;KAChC,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n toFingerprint,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { loadPrincipalPolicyCheckpoint } from \"../persistence/keyingCheckpointPersistence\";\nimport {\n principalPolicyHeadMeetsCheckpoint,\n verifiedPrincipalPolicyMeetsCheckpoint,\n} from \"../persistence/principalPolicyCheckpointSelection\";\nimport { loadPrincipalPolicyBundle } from \"../persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../persistence/principalPolicyReferencePersistence\";\nimport { principalPolicyBundleStates } from \"../principalPolicyStates\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../principals/principalPolicyAdminSigners\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"./checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"./dependencyUnavailable\";\nimport { rethrowProjectionVerificationBoundaryError } from \"./error\";\nimport {\n filterUncachedPrincipalPolicyReferences,\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n} from \"./types\";\n\nfunction principalPolicyReferenceLabel(\n reference: ReferencedPrincipalHead,\n): string {\n return `${reference.principalType}:${reference.principalId}@${reference.version}`;\n}\n\n/**\n * A referenced principal policy is not in the local store and warming could\n * not fetch it this pass — a transient cold-cache condition, typical for a\n * member whose access arrives via a group policy the device has not hydrated\n * yet. Sync passes discriminate on this type to defer the affected container\n * and retry on a later trigger, rather than failing the whole pass.\n */\nexport class PrincipalPolicyNotCachedError extends Error {\n constructor(referenceLabel: string) {\n super(`Principal policy ${referenceLabel} is not cached`);\n this.name = \"PrincipalPolicyNotCachedError\";\n }\n}\n\nexport function isPrincipalPolicyNotCachedError(error: unknown): boolean {\n return (\n error instanceof PrincipalPolicyNotCachedError ||\n (error instanceof Error && error.name === \"PrincipalPolicyNotCachedError\")\n );\n}\n\nasync function collectPrincipalPolicySignerPublicKeys(input: {\n bundle: PrincipalPolicyBundleResponse;\n label: string;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<PrincipalPolicySignerPublicKey[]> {\n const signerPublicKeysByKey = new Map<\n string,\n PrincipalPolicySignerPublicKey\n >();\n\n for (const state of principalPolicyBundleStates(input.bundle)) {\n const cacheKey = `${state.signerUserId}:${state.signerUserKeyFingerprint}`;\n if (signerPublicKeysByKey.has(cacheKey)) {\n continue;\n }\n\n const signerKey = await input.resolveUserKey(state.signerUserId);\n if (!signerKey) {\n throw new ProjectionDependencyUnavailableError(\n `${input.label} signer key could not be resolved for ${state.signerUserId}`,\n );\n }\n\n const signingKeyFingerprint = await toFingerprint(\n signerKey.signingPublicKey,\n );\n if (signingKeyFingerprint !== state.signerUserKeyFingerprint) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${input.label} signer key fingerprint mismatch`,\n );\n }\n\n signerPublicKeysByKey.set(cacheKey, {\n userId: state.signerUserId,\n signingKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n });\n }\n\n return [...signerPublicKeysByKey.values()];\n}\n\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: Awaited<\n ReturnType<typeof loadPrincipalPolicyCheckpoint>\n >;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (\n !principalPolicyHeadMeetsCheckpoint(bundle.currentState, localCheckpoint) &&\n input.warmReferencedPrincipalPolicies\n ) {\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [principalPolicyReferenceFromBundle(bundle)],\n });\n bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n }\n\n return { bundle, localCheckpoint };\n}\n\nfunction assertReservedAdminsPolicyShape(\n policy: VerifiedPrincipalPolicy,\n): void {\n const history = policy.history ?? [{ projection: policy.projection }];\n if (\n history.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\nasync function verifyOrganizationAdminsPolicy(input: {\n adminGroupId: string;\n execSql: ProjectionCheckpointContext[\"execSql\"];\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n if (!adminBundle) {\n return undefined;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(adminBundle),\n input.expectedHead,\n )\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Admins policy does not match the signed organization directory\",\n );\n }\n const adminCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: adminBundle,\n label: `Admins policy ${input.adminGroupId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyPrincipalPolicyBundle({\n bundle: adminBundle,\n expectedReference: input.expectedHead,\n localCheckpoint: adminCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n assertReservedAdminsPolicyShape(verified.value);\n return verified.value;\n}\n\nasync function loadOrganizationExternalAuthority(\n input: OrganizationAdminPolicyInput,\n): Promise<ReturnType<typeof organizationAdminExternalAuthority> | null> {\n const organizationPolicy = await loadOrganizationPolicyForVerification(input);\n if (!organizationPolicy) {\n return null;\n }\n\n try {\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: organizationPolicy.bundle,\n label: `Organization policy ${input.organizationId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyOrganizationAdminPolicy({\n bundle: organizationPolicy.bundle,\n localCheckpoint: organizationPolicy.localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n const descriptor = parseOrganizationAuthorityDescriptor(\n organizationPolicy.bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n const verifiedAdmins = await verifyOrganizationAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n execSql: input.checkpointContext.execSql,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n });\n if (!verifiedAdmins) {\n return null;\n }\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n observePrincipalPolicy(\n input.checkpointContext,\n verifiedAdmins,\n input.organizationId,\n );\n return organizationAdminExternalAuthority(verifiedAdmins);\n } catch (error) {\n rethrowProjectionVerificationBoundaryError(error);\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n\nasync function verifyReferencedPrincipalPolicy(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n reference: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<VerifiedPrincipalPolicy> {\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n input.reference.principalType,\n input.reference.principalId,\n );\n if (cachedPolicy) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, localCheckpoint)) {\n observePrincipalPolicy(\n input.checkpointContext,\n cachedPolicy,\n input.organizationId,\n );\n return cachedPolicy;\n }\n }\n\n const referenceLabel = principalPolicyReferenceLabel(input.reference);\n let bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n if (!bundle && input.warmReferencedPrincipalPolicies) {\n // The reference is not cached locally — the common case for a member who\n // gained access via another org's group grant and never hydrated that\n // group's policy. Fetch+verify+persist it, then re-read from the cache.\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [input.reference],\n });\n bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n }\n if (!bundle) {\n throw new PrincipalPolicyNotCachedError(referenceLabel);\n }\n\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n label: `Principal policy ${referenceLabel}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: input.reference,\n loadExternalAuthority: () =>\n loadOrganizationExternalAuthority({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n input.principalPolicyCache.set(cacheKey, verified.value);\n return verified.value;\n}\n\nexport async function collectReferencedPrincipalPolicies(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n references: readonly ReferencedPrincipalHead[];\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const uniqueReferences = new Map<string, ReferencedPrincipalHead>();\n for (const reference of input.references) {\n uniqueReferences.set(referencedPrincipalPolicyKey(reference), reference);\n }\n\n const references = [...uniqueReferences.values()];\n // Warm every missing reference in one batched fetch before verifying, so a\n // path that references several uncached policies makes a single round of\n // requests rather than one per reference.\n if (warmReferencedPrincipalPolicies) {\n const uncached = await filterUncachedPrincipalPolicyReferences({\n execSql: input.checkpointContext.execSql,\n principalPolicyCache: input.principalPolicyCache,\n references,\n });\n if (uncached.length > 0) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: uncached,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n }\n\n return Promise.all(\n references.map((reference) =>\n verifyReferencedPrincipalPolicy({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n reference,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n }),\n ),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,aAAa,EAEb,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAC;AAC3F,OAAO,EACL,kCAAkC,EAClC,sCAAsC,GACvC,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,yBAAyB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAC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;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,SAAS;QACT,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B;KAChC,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n toFingerprint,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { loadPrincipalPolicyCheckpoint } from \"../persistence/keyingCheckpointPersistence\";\nimport {\n principalPolicyHeadMeetsCheckpoint,\n verifiedPrincipalPolicyMeetsCheckpoint,\n} from \"../persistence/principalPolicyCheckpointSelection\";\nimport { loadPrincipalPolicyBundle } from \"../persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../persistence/principalPolicyReferencePersistence\";\nimport { principalPolicyBundleStates } from \"../principalPolicyStates\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../principals/principalPolicyEvidence\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"./checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"./dependencyUnavailable\";\nimport { rethrowProjectionVerificationBoundaryError } from \"./error\";\nimport {\n filterUncachedPrincipalPolicyReferences,\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport { resolveReferencedPrincipalPolicy } from \"./resolvedPrincipalPolicy\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n} from \"./types\";\n\nfunction principalPolicyReferenceLabel(\n reference: ReferencedPrincipalHead,\n): string {\n return `${reference.principalType}:${reference.principalId}@${reference.version}`;\n}\n\n/**\n * A referenced principal policy is not in the local store and warming could\n * not fetch it this pass — a transient cold-cache condition, typical for a\n * member whose access arrives via a group policy the device has not hydrated\n * yet. Sync passes discriminate on this type to defer the affected container\n * and retry on a later trigger, rather than failing the whole pass.\n */\nexport class PrincipalPolicyNotCachedError extends Error {\n constructor(referenceLabel: string) {\n super(`Principal policy ${referenceLabel} is not cached`);\n this.name = \"PrincipalPolicyNotCachedError\";\n }\n}\n\nexport function isPrincipalPolicyNotCachedError(error: unknown): boolean {\n return (\n error instanceof PrincipalPolicyNotCachedError ||\n (error instanceof Error && error.name === \"PrincipalPolicyNotCachedError\")\n );\n}\n\nasync function collectPrincipalPolicySignerPublicKeys(input: {\n bundle: PrincipalPolicyBundleResponse;\n label: string;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<PrincipalPolicySignerPublicKey[]> {\n const signerPublicKeysByKey = new Map<\n string,\n PrincipalPolicySignerPublicKey\n >();\n\n for (const state of principalPolicyBundleStates(input.bundle)) {\n const cacheKey = `${state.signerUserId}:${state.signerUserKeyFingerprint}`;\n if (signerPublicKeysByKey.has(cacheKey)) {\n continue;\n }\n\n const signerKey = await input.resolveUserKey(state.signerUserId);\n if (!signerKey) {\n throw new ProjectionDependencyUnavailableError(\n `${input.label} signer key could not be resolved for ${state.signerUserId}`,\n );\n }\n\n const signingKeyFingerprint = await toFingerprint(\n signerKey.signingPublicKey,\n );\n if (signingKeyFingerprint !== state.signerUserKeyFingerprint) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${input.label} signer key fingerprint mismatch`,\n );\n }\n\n signerPublicKeysByKey.set(cacheKey, {\n userId: state.signerUserId,\n signingKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n });\n }\n\n return [...signerPublicKeysByKey.values()];\n}\n\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: Awaited<\n ReturnType<typeof loadPrincipalPolicyCheckpoint>\n >;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (\n !principalPolicyHeadMeetsCheckpoint(bundle.currentState, localCheckpoint) &&\n input.warmReferencedPrincipalPolicies\n ) {\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [principalPolicyReferenceFromBundle(bundle)],\n });\n bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n }\n\n return { bundle, localCheckpoint };\n}\n\nfunction assertReservedAdminsPolicyShape(\n policy: VerifiedPrincipalPolicy,\n): void {\n const history = policy.history ?? [{ projection: policy.projection }];\n if (\n history.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\nasync function verifyOrganizationAdminsPolicy(input: {\n adminGroupId: string;\n execSql: ProjectionCheckpointContext[\"execSql\"];\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n if (!adminBundle) {\n return undefined;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(adminBundle),\n input.expectedHead,\n )\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Admins policy does not match the signed organization directory\",\n );\n }\n const adminCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: adminBundle,\n label: `Admins policy ${input.adminGroupId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyPrincipalPolicyBundle({\n bundle: adminBundle,\n expectedReference: input.expectedHead,\n localCheckpoint: adminCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n assertReservedAdminsPolicyShape(verified.value);\n return verified.value;\n}\n\nasync function loadOrganizationExternalAuthority(\n input: OrganizationAdminPolicyInput,\n): Promise<ReturnType<typeof organizationAdminExternalAuthority> | null> {\n const organizationPolicy = await loadOrganizationPolicyForVerification(input);\n if (!organizationPolicy) {\n return null;\n }\n\n try {\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: organizationPolicy.bundle,\n label: `Organization policy ${input.organizationId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyOrganizationAdminPolicy({\n bundle: organizationPolicy.bundle,\n localCheckpoint: organizationPolicy.localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n const descriptor = parseOrganizationAuthorityDescriptor(\n organizationPolicy.bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n const verifiedAdmins = await verifyOrganizationAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n execSql: input.checkpointContext.execSql,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n });\n if (!verifiedAdmins) {\n return null;\n }\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n observePrincipalPolicy(\n input.checkpointContext,\n verifiedAdmins,\n input.organizationId,\n );\n return organizationAdminExternalAuthority(verifiedAdmins);\n } catch (error) {\n rethrowProjectionVerificationBoundaryError(error);\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n\nasync function verifyReferencedPrincipalPolicy(input: {\n recoveryBatch: object;\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n reference: ReferencedPrincipalHead;\n stillCurrent?: (() => boolean) | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence> {\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n input.reference.principalType,\n input.reference.principalId,\n );\n if (cachedPolicy && !(\"retainedHistory\" in cachedPolicy)) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, localCheckpoint)) {\n observePrincipalPolicy(\n input.checkpointContext,\n cachedPolicy,\n input.organizationId,\n );\n return cachedPolicy;\n }\n }\n\n const referenceLabel = principalPolicyReferenceLabel(input.reference);\n let bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n if (!bundle) {\n const recovered = await resolveReferencedPrincipalPolicy(input);\n if (recovered) return recovered;\n }\n if (!bundle && input.warmReferencedPrincipalPolicies) {\n // The reference is not cached locally — the common case for a member who\n // gained access via another org's group grant and never hydrated that\n // group's policy. Fetch+verify+persist it, then re-read from the cache.\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [input.reference],\n });\n bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n }\n if (!bundle) {\n throw new PrincipalPolicyNotCachedError(referenceLabel);\n }\n\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n label: `Principal policy ${referenceLabel}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: input.reference,\n loadExternalAuthority: () =>\n loadOrganizationExternalAuthority({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n input.principalPolicyCache.set(cacheKey, verified.value);\n return verified.value;\n}\n\nexport async function collectReferencedPrincipalPolicies(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n references: readonly ReferencedPrincipalHead[];\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const uniqueReferences = new Map<string, ReferencedPrincipalHead>();\n for (const reference of input.references) {\n uniqueReferences.set(referencedPrincipalPolicyKey(reference), reference);\n }\n\n const references = [...uniqueReferences.values()];\n // Warm every missing reference in one batched fetch before verifying, so a\n // path that references several uncached policies makes a single round of\n // requests rather than one per reference.\n if (\n warmReferencedPrincipalPolicies &&\n !warmReferencedPrincipalPolicies.resolveReference\n ) {\n const uncached = await filterUncachedPrincipalPolicyReferences({\n execSql: input.checkpointContext.execSql,\n principalPolicyCache: input.principalPolicyCache,\n references,\n });\n if (uncached.length > 0) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: uncached,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n }\n\n const recoveryBatch = {};\n return Promise.all(\n references.map((reference) =>\n verifyReferencedPrincipalPolicy({\n recoveryBatch,\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n reference,\n stillCurrent: input.stillCurrent,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n }),\n ),\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"projectionAuthorizationEvidence.js","sourceRoot":"","sources":["projectionAuthorizationEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"projectionAuthorizationEvidence.js","sourceRoot":"","sources":["projectionAuthorizationEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,EAAE,8BAA8B,EAAE,MAAM,4BAA4B,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAG/C,mFAAmF;AACnF,KAAK,UAAU,sCAAsC,CAAC,KAOrD;IACC,M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,cAAc;YACpC,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CAAC;KACH,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n principalPolicyMatchesReference,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ProjectionPolicyEvidenceResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ProjectionCheckpointContext } from \"./checkpointContext\";\nimport { collectReferencedPrincipalPolicies } from \"./principalPolicyVerification\";\nimport { verifyProjectionPolicyEvidence } from \"./projectionPolicyEvidence\";\nimport { readAccessManifest } from \"./readers\";\nimport type { PrincipalPolicyCache, ProjectionUserKeyResolver } from \"./types\";\n\n/** Locally planned successors may cite an already verified, uncommitted policy. */\nasync function resolveProjectionAuthorizationEvidence(input: {\n readonly bundles: readonly AccessManifestBundleWireResponse[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly evidence: readonly PrincipalPolicyCheckpointEvidence[];\n readonly organizationId: string;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<PrincipalPolicyCheckpointEvidence[]> {\n const references = input.bundles\n .flatMap(\n (bundle) =>\n readAccessManifest(bundle.manifest, \"Projection manifest\")\n .referencedPrincipalHeads,\n )\n .filter(\n (reference) =>\n !input.evidence.some((policy) =>\n principalPolicyMatchesReference({ policy, reference }),\n ),\n );\n const known = [...input.principalPolicyCache.values()];\n if (\n references.some(\n (reference) =>\n !known.some((policy) =>\n principalPolicyMatchesReference({ policy, reference }),\n ),\n )\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection omits required principal policy evidence\",\n );\n return [\n ...input.evidence,\n ...(await collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references,\n resolveUserKey: input.resolveUserKey,\n })),\n ];\n}\n\nexport async function verifyProjectionAuthorizationEvidence(\n input: Omit<\n Parameters<typeof resolveProjectionAuthorizationEvidence>[0],\n \"evidence\"\n > & { readonly policyEvidence: ProjectionPolicyEvidenceResponse },\n) {\n return resolveProjectionAuthorizationEvidence({\n ...input,\n evidence: await verifyProjectionPolicyEvidence({\n evidence: input.policyEvidence,\n execSql: input.checkpointContext.execSql,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n }),\n });\n}\n"]}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { KeyingVerificationError, } from "../../internal/crypto/index.js";
|
|
2
|
+
import { loadPrincipalPolicyCheckpoint } from "../persistence/keyingCheckpointPersistence.js";
|
|
3
|
+
import { verifiedPrincipalPolicyMeetsCheckpoint } from "../persistence/principalPolicyCheckpointSelection.js";
|
|
4
|
+
import { observePrincipalPolicy, } from "./checkpointContext.js";
|
|
5
|
+
import { referencedPrincipalPolicyKey, verifiedPrincipalPolicyContainsReference, } from "./principalPolicyCache.js";
|
|
6
|
+
import { assertProjectionVerificationCurrent, } from "./types.js";
|
|
7
|
+
// Sparse cache hits must carry the organization binding and every dependency
|
|
8
|
+
// into each new admission batch; a bare current-policy capability is insufficient.
|
|
9
|
+
// The caller owns this cache. Cross-generation reuse is deliberately disabled by
|
|
10
|
+
// the saved guard; a new lifetime restores authenticated persistent evidence.
|
|
11
|
+
const recoveredByCache = new WeakMap();
|
|
12
|
+
async function meetsCheckpoints(context, result, refreshMissing) {
|
|
13
|
+
for (const policy of [...result.dependencies, result.policy]) {
|
|
14
|
+
const checkpoint = await loadPrincipalPolicyCheckpoint(context.execSql, policy.principalType, policy.principalId);
|
|
15
|
+
if (refreshMissing &&
|
|
16
|
+
checkpoint &&
|
|
17
|
+
(policy.version < checkpoint.version ||
|
|
18
|
+
(policy.version > checkpoint.version &&
|
|
19
|
+
!policy.retainedHistory.some((entry) => entry.state.version === checkpoint.version))))
|
|
20
|
+
return false;
|
|
21
|
+
if (!verifiedPrincipalPolicyMeetsCheckpoint(policy, checkpoint))
|
|
22
|
+
throw new KeyingVerificationError("rollback", "Recovered principal evidence predates the durable checkpoint");
|
|
23
|
+
}
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
export async function resolveReferencedPrincipalPolicy(input) {
|
|
27
|
+
assertProjectionVerificationCurrent(input.stillCurrent);
|
|
28
|
+
const key = referencedPrincipalPolicyKey(input.reference);
|
|
29
|
+
const remembered = recoveredByCache.get(input.principalPolicyCache)?.get(key);
|
|
30
|
+
let result = remembered?.organizationId === input.organizationId &&
|
|
31
|
+
remembered.policy === input.principalPolicyCache.get(key) &&
|
|
32
|
+
remembered.stillCurrent()
|
|
33
|
+
? remembered
|
|
34
|
+
: undefined;
|
|
35
|
+
if (result &&
|
|
36
|
+
!(await meetsCheckpoints(input.checkpointContext, result, true)))
|
|
37
|
+
result = undefined;
|
|
38
|
+
if (!result) {
|
|
39
|
+
const resolve = input.warmReferencedPrincipalPolicies?.resolveReference;
|
|
40
|
+
if (!resolve)
|
|
41
|
+
return null;
|
|
42
|
+
result = await resolve({
|
|
43
|
+
recoveryBatch: input.recoveryBatch,
|
|
44
|
+
organizationId: input.organizationId,
|
|
45
|
+
reference: input.reference,
|
|
46
|
+
stillCurrent: input.stillCurrent,
|
|
47
|
+
});
|
|
48
|
+
await meetsCheckpoints(input.checkpointContext, result, false);
|
|
49
|
+
}
|
|
50
|
+
assertProjectionVerificationCurrent(input.stillCurrent);
|
|
51
|
+
assertProjectionVerificationCurrent(result.stillCurrent);
|
|
52
|
+
if (result.organizationId !== input.organizationId)
|
|
53
|
+
throw new KeyingVerificationError("object_mismatch", "Recovered principal evidence belongs to another organization");
|
|
54
|
+
if (!verifiedPrincipalPolicyContainsReference(result.policy, input.reference))
|
|
55
|
+
throw new KeyingVerificationError("object_mismatch", "Recovered principal evidence does not contain the exact citation");
|
|
56
|
+
for (const policy of [...result.dependencies, result.policy])
|
|
57
|
+
observePrincipalPolicy(input.checkpointContext, policy, input.organizationId);
|
|
58
|
+
let rememberedPolicies = recoveredByCache.get(input.principalPolicyCache);
|
|
59
|
+
if (!rememberedPolicies) {
|
|
60
|
+
rememberedPolicies = new Map();
|
|
61
|
+
recoveredByCache.set(input.principalPolicyCache, rememberedPolicies);
|
|
62
|
+
}
|
|
63
|
+
rememberedPolicies.set(key, {
|
|
64
|
+
...result,
|
|
65
|
+
dependencies: [...result.dependencies],
|
|
66
|
+
});
|
|
67
|
+
input.principalPolicyCache.set(key, result.policy);
|
|
68
|
+
return result.policy;
|
|
69
|
+
}
|
|
70
|
+
//# sourceMappingURL=resolvedPrincipalPolicy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolvedPrincipalPolicy.js","sourceRoot":"","sources":["resolvedPrincipalPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAC;AAC3F,OAAO,EAAE,sCAAsC,EAAE,MAAM,mDAAmD,CAAC;AAC3G,OAAO,EACL,sBAAsB,GAEvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,4BAA4B,EAC5B,wCAAwC,GACzC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,mCAAmC,GAIpC,MAAM,SAAS,CAAC;AAEjB,6EAA6E;AAC7E,mFAAmF;AACnF,iFAAiF;AACjF,8EAA8E;AAC9E,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAGjC,CAAC;AAEJ,KAAK,UAAU,gBAAgB,CAC7B,OAAoC,EACpC,MAAuC,EACvC,cAAuB;IAEvB,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7D,MAAM,UAAU,GAAG,MAAM,6BAA6B,CACpD,OAAO,CAAC,OAAO,EACf,MAAM,CAAC,aAAa,EACpB,MAAM,CAAC,WAAW,CACnB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QACT,YAAY,EAAE,CAAC,GAAG,MAAM,CAAC,YAAY,CAAC;KACvC,CAAC,CAAC;IACH,KAAK,CAAC,oBAAoB,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnD,OAAO,MAAM,CAAC,MAAM,CAAC;AACvB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../persistence/keyingCheckpointPersistence\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"../persistence/principalPolicyCheckpointSelection\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"./checkpointContext\";\nimport {\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyCache,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"./types\";\n\n// Sparse cache hits must carry the organization binding and every dependency\n// into each new admission batch; a bare current-policy capability is insufficient.\n// The caller owns this cache. Cross-generation reuse is deliberately disabled by\n// the saved guard; a new lifetime restores authenticated persistent evidence.\nconst recoveredByCache = new WeakMap<\n PrincipalPolicyCache,\n Map<string, ResolvedPrincipalPolicyEvidence>\n>();\n\nasync function meetsCheckpoints(\n context: ProjectionCheckpointContext,\n result: ResolvedPrincipalPolicyEvidence,\n refreshMissing: boolean,\n): Promise<boolean> {\n for (const policy of [...result.dependencies, result.policy]) {\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n context.execSql,\n policy.principalType,\n policy.principalId,\n );\n if (\n refreshMissing &&\n checkpoint &&\n (policy.version < checkpoint.version ||\n (policy.version > checkpoint.version &&\n !policy.retainedHistory.some(\n (entry) => entry.state.version === checkpoint.version,\n )))\n )\n return false;\n if (!verifiedPrincipalPolicyMeetsCheckpoint(policy, checkpoint))\n throw new KeyingVerificationError(\n \"rollback\",\n \"Recovered principal evidence predates the durable checkpoint\",\n );\n }\n return true;\n}\n\nexport async function resolveReferencedPrincipalPolicy(input: {\n readonly recoveryBatch?: object | undefined;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly organizationId: string;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly reference: ReferencedPrincipalHead;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<VerifiedPrincipalPolicyCurrent | null> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const key = referencedPrincipalPolicyKey(input.reference);\n const remembered = recoveredByCache.get(input.principalPolicyCache)?.get(key);\n let result =\n remembered?.organizationId === input.organizationId &&\n remembered.policy === input.principalPolicyCache.get(key) &&\n remembered.stillCurrent()\n ? remembered\n : undefined;\n if (\n result &&\n !(await meetsCheckpoints(input.checkpointContext, result, true))\n )\n result = undefined;\n if (!result) {\n const resolve = input.warmReferencedPrincipalPolicies?.resolveReference;\n if (!resolve) return null;\n result = await resolve({\n recoveryBatch: input.recoveryBatch,\n organizationId: input.organizationId,\n reference: input.reference,\n stillCurrent: input.stillCurrent,\n });\n await meetsCheckpoints(input.checkpointContext, result, false);\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n assertProjectionVerificationCurrent(result.stillCurrent);\n if (result.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Recovered principal evidence belongs to another organization\",\n );\n if (!verifiedPrincipalPolicyContainsReference(result.policy, input.reference))\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Recovered principal evidence does not contain the exact citation\",\n );\n for (const policy of [...result.dependencies, result.policy])\n observePrincipalPolicy(\n input.checkpointContext,\n policy,\n input.organizationId,\n );\n let rememberedPolicies = recoveredByCache.get(input.principalPolicyCache);\n if (!rememberedPolicies) {\n rememberedPolicies = new Map();\n recoveredByCache.set(input.principalPolicyCache, rememberedPolicies);\n }\n rememberedPolicies.set(key, {\n ...result,\n dependencies: [...result.dependencies],\n });\n input.principalPolicyCache.set(key, result.policy);\n return result.policy;\n}\n"]}
|