@tearleads/client-sdk 0.1.117 → 0.1.118
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/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +8 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +15 -0
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js +3 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/document/documentProjectionVerification.js +2 -1
- package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
- package/data/persistence/verifiedCitations/citationScope.js +121 -0
- package/data/persistence/verifiedCitations/citationScope.js.map +1 -0
- package/data/persistence/verifiedCitations/kekLevelCitations.d.ts +33 -0
- package/data/persistence/verifiedCitations/kekLevelCitations.js +44 -0
- package/data/persistence/verifiedCitations/kekLevelCitations.js.map +1 -0
- package/data/persistence/verifiedManifestBundlePersistence.d.ts +17 -12
- package/data/persistence/verifiedManifestBundlePersistence.js +75 -104
- package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
- package/data/sqlite/schema/verifiedManifestBundleSchema.d.ts +7 -2
- package/data/sqlite/schema/verifiedManifestBundleSchema.js +7 -2
- package/data/sqlite/schema/verifiedManifestBundleSchema.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +3 -2
- package/internal/api-client/ApiClient.js +3 -2
- package/internal/api-client/ApiClient.js.map +1 -1
- package/internal/api-client/index.d.ts +1 -1
- package/internal/api-client/index.js.map +1 -1
- package/internal/api-client/types.d.ts +7 -0
- package/internal/api-client/types.js.map +1 -1
- package/internal/api-client/verifiedManifestCitations.d.ts +26 -9
- package/internal/api-client/verifiedManifestCitations.js +44 -25
- package/internal/api-client/verifiedManifestCitations.js.map +1 -1
- package/internal/api-client/writerProjectionRequests.js +21 -10
- package/internal/api-client/writerProjectionRequests.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/canonicalJsonGuard.d.ts +7 -0
- package/internal/crypto/keying/canonicalJsonGuard.js +20 -0
- package/internal/crypto/keying/canonicalJsonGuard.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/validators/knownManifestsRefinements.js +1 -1
- package/internal/validators/knownManifestsRefinements.js.map +1 -1
- package/internal/validators/operation/writerProjections.d.ts +42 -18
- package/internal/validators/response/container.d.ts +137 -16
- package/internal/validators/response/container.js +23 -2
- package/internal/validators/response/container.js.map +1 -1
- package/internal/validators/response/documentMutation.d.ts +20 -8
- package/internal/validators/response/index.d.ts +2 -2
- package/internal/validators/response/index.js +2 -2
- package/internal/validators/response/index.js.map +1 -1
- package/internal/validators/response/writerProjectionWire.d.ts +19 -8
- package/internal/validators/response/writerProjectionWire.js +78 -20
- package/internal/validators/response/writerProjectionWire.js.map +1 -1
- package/internal/validators/util/index.d.ts +1 -1
- package/internal/validators/util/index.js +1 -1
- package/internal/validators/util/index.js.map +1 -1
- package/internal/validators/util/knownManifestWire.d.ts +13 -3
- package/internal/validators/util/knownManifestWire.js +37 -10
- package/internal/validators/util/knownManifestWire.js.map +1 -1
- package/package.json +1 -1
- package/workflows/container-contents/remoteHydration/destination/destinationPrefetch.js +10 -5
- package/workflows/container-contents/remoteHydration/destination/destinationPrefetch.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +4 -6
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +2 -2
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type AccessManifestCheckpoint, type VerifiedAccessManifestCheckpointEvidence, type VerifiedContainerAccessManifest, type VerifiedPrincipalPolicySelection } from "../../../internal/crypto/index.js";
|
|
2
|
-
import type
|
|
2
|
+
import { type AccessManifestBundleWireResponse, type ContainerKeyingPathResponse } from "../../../internal/validators/response/index.js";
|
|
3
3
|
import type { DocumentPurgeCheckpoint } from "../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js";
|
|
4
4
|
import type { VerifiedManifestBundle } from "../../persistence/verifiedManifestBundlePersistence.js";
|
|
5
5
|
import type { PrincipalPolicyCheckpointEvidence } from "../../principals/principalPolicyEvidence.js";
|
|
@@ -32,6 +32,13 @@ export declare function observeAccessManifestCheckpoints(context: ProjectionChec
|
|
|
32
32
|
export declare function observeVerifiedProjectionBundles(context: ProjectionCheckpointContext, bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>, verifiedByHash: ReadonlyMap<string, {
|
|
33
33
|
readonly checkpoint: AccessManifestCheckpoint;
|
|
34
34
|
}>): void;
|
|
35
|
+
/**
|
|
36
|
+
* Records every KEK level of paths this verification accepted in full, so
|
|
37
|
+
* the finalizing transaction stores them for later citation by digest. A
|
|
38
|
+
* cited level is refilled from these bytes only when the API's current
|
|
39
|
+
* level has the same digest, and is verified again like a served one.
|
|
40
|
+
*/
|
|
41
|
+
export declare function observeVerifiedKekLevels(context: ProjectionCheckpointContext, paths: readonly ContainerKeyingPathResponse[]): void;
|
|
35
42
|
export declare function observePrincipalPolicy(context: ProjectionCheckpointContext, policy: PrincipalPolicyCheckpointEvidence, organizationId?: string | undefined): void;
|
|
36
43
|
export declare function commitProjectionCheckpoints(context: ProjectionCheckpointContext, input?: {
|
|
37
44
|
readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
|
+
import { containerKekWireLevel, } from "../../../internal/validators/response/index.js";
|
|
2
3
|
import { rememberVerifiedContainerHeads } from "../../containers/shared/heldContainerHeads.js";
|
|
3
4
|
import { PrincipalAuthorizationCheckpointUnavailableError } from "../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js";
|
|
4
5
|
import { ProjectionDependencyUnavailableError } from "../dependencyUnavailable.js";
|
|
@@ -41,6 +42,20 @@ export function observeVerifiedProjectionBundles(context, bundlesByHash, verifie
|
|
|
41
42
|
context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });
|
|
42
43
|
}
|
|
43
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* Records every KEK level of paths this verification accepted in full, so
|
|
47
|
+
* the finalizing transaction stores them for later citation by digest. A
|
|
48
|
+
* cited level is refilled from these bytes only when the API's current
|
|
49
|
+
* level has the same digest, and is verified again like a served one.
|
|
50
|
+
*/
|
|
51
|
+
export function observeVerifiedKekLevels(context, paths) {
|
|
52
|
+
for (const path of paths)
|
|
53
|
+
for (const kek of path.containerKeks)
|
|
54
|
+
context.verifiedBundles.push({
|
|
55
|
+
kekLevel: containerKekWireLevel(kek),
|
|
56
|
+
organizationId: path.organizationId,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
44
59
|
export function observePrincipalPolicy(context, policy, organizationId) {
|
|
45
60
|
if (organizationId !== undefined &&
|
|
46
61
|
context.organizationId !== undefined &&
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAE5F,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAIzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EACL,gCAAgC,EAChC,iC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AAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { rememberVerifiedContainerHeads } from \"../../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,qBAAqB,GACtB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAE5F,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAIzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EACL,gCAAgC,E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KAAK,CAAC,8BAA8B,KAAK,KAAK,EAAE,CAAC;QACnD,MAAM,6BAA6B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACpD,OAAO;IACT,CAAC;IACD,MAAM,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAClD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO;IAC7C,MAAM,cAAc,GAClB,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport { rememberVerifiedContainerHeads } from \"../../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, toFingerprint, verifyContainerKekState, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { addBundleByHash } from "../checkpoints/bundleVerification.js";
|
|
3
|
-
import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeAccessManifestCheckpoints, observeVerifiedProjectionBundles, } from "../checkpoints/checkpointContext.js";
|
|
3
|
+
import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeAccessManifestCheckpoints, observeVerifiedKekLevels, observeVerifiedProjectionBundles, } from "../checkpoints/checkpointContext.js";
|
|
4
4
|
import { ProjectionDependencyUnavailableError } from "../dependencyUnavailable.js";
|
|
5
5
|
import { throwKeyingVerificationShapeFailure } from "../error.js";
|
|
6
6
|
import { collectReferencedPrincipalPolicies } from "../principalPolicy/principalPolicyVerification.js";
|
|
@@ -185,6 +185,7 @@ export async function verifyContainerWriterProjection(input) {
|
|
|
185
185
|
const verifiedPath = await verifyContainerWriterProjectionWithContext(guardedInput, checkpointContext);
|
|
186
186
|
assertProjectionVerificationCurrent(input.stillCurrent);
|
|
187
187
|
observeVerifiedProjectionBundles(checkpointContext, collectContainerProjectionBundles(input.projection), verifiedByHash);
|
|
188
|
+
observeVerifiedKekLevels(checkpointContext, [input.projection]);
|
|
188
189
|
await finalizeProjectionCheckpoints(checkpointContext, input);
|
|
189
190
|
assertProjectionVerificationCurrent(input.stillCurrent);
|
|
190
191
|
return verifiedPath;
|
|
@@ -222,6 +223,7 @@ export async function collectContainerWriterProjectionPrincipalPolicies(input) {
|
|
|
222
223
|
});
|
|
223
224
|
assertProjectionVerificationCurrent(input.stillCurrent);
|
|
224
225
|
observeVerifiedProjectionBundles(checkpointContext, collectContainerProjectionBundles(input.projection), verifiedByHash);
|
|
226
|
+
observeVerifiedKekLevels(checkpointContext, [input.projection]);
|
|
225
227
|
await finalizeProjectionCheckpoints(checkpointContext, input);
|
|
226
228
|
assertProjectionVerificationCurrent(input.stillCurrent);
|
|
227
229
|
return policies;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerProjectionVerification.js","sourceRoot":"","sources":["containerProjectionVerification.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,sCAAsC,EACtC,4BAA4B,EAC5B,aAAa,EAGb,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AACpG,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EACL,+BAA+B,EAC/B,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAMpB,OAAO,EACL,mCAAmC,EACnC,sCAAsC,EACtC,iCAAiC,GAClC,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAE1E,KAAK,UAAU,iCAAiC,CAAC,KAGhD;IACC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,GAAG,CACR,KAAK,CAAC,iBAAiB,CAAC,KAAK,CAAC,YAAY;aACvC,MAAM,CAAC,CAAC,KAAK,EAAE,EAA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AE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAC5E,CAAC;IAEF,OAAO,kCAAkC,CAAC;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,wBAAwB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyAuthorization } from \"@tearleads/crypto\";\nimport {\n type ContainerUserRecipientKey,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n toFingerprint,\n type VerifiedContainerAccessManifest,\n type VerifiedContainerKekState,\n verifyContainerKekState,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { collectReferencedPrincipalPolicies } from \"../principalPolicy/principalPolicyVerification\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport {\n readContainerKekRecipientTarget,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n withGenerationGuardedPolicyWarmer,\n} from \"../types\";\nimport { verifyContainerManifestBundle } from \"./containerManifestVerification\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\n\nasync function collectContainerUserRecipientKeys(input: {\n readonly containerManifest: VerifiedContainerAccessManifest;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<ContainerUserRecipientKey[]> {\n const userIds = [\n ...new Set(\n input.containerManifest.state.directGrants\n .filter((grant) => grant.subjectType === \"user\")\n .map((grant) => grant.subjectId),\n ),\n ].sort();\n const userRecipientKeys: ContainerUserRecipientKey[] = [];\n\n for (const userId of userIds) {\n const userKey = await input.resolveUserKey(userId);\n if (!userKey) {\n throw new ProjectionDependencyUnavailableError(\n `Container writer projection recipient key could not be resolved for ${userId}`,\n );\n }\n const recipientKeyFingerprint = await toFingerprint(\n userKey.encapsulationPublicKey,\n );\n userRecipientKeys.push({\n userId,\n recipientKeyEpochId: `user:${userId}:encapsulation:${recipientKeyFingerprint}`,\n recipientKeyFingerprint,\n });\n }\n\n return userRecipientKeys;\n}\n\nfunction containerKekManifestHistory(input: {\n readonly history: readonly VerifiedContainerAccessManifest[];\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n}): VerifiedContainerAccessManifest[] {\n const historyByHash = new Map<string, VerifiedContainerAccessManifest>();\n\n for (const manifest of input.history) {\n if (\n manifest.state.containerId === input.verifiedManifest.state.containerId &&\n manifest.manifestHash !== input.verifiedManifest.manifestHash\n ) {\n historyByHash.set(manifest.manifestHash, manifest);\n }\n }\n\n return [...historyByHash.values()];\n}\n\nasync function verifyContainerKekProjection(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly kek: ContainerWriterProjectionResponse[\"containerKeks\"][number];\n readonly label: string;\n readonly parentKekState: VerifiedContainerKekState | null;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n readonly verifiedManifestHistory: readonly VerifiedContainerAccessManifest[];\n readonly parentManifestHistory: readonly VerifiedContainerAccessManifest[];\n}): Promise<VerifiedContainerKekState> {\n if (input.verifiedManifest.state.parentContainerId && !input.parentKekState) {\n throw new Error(`${input.label} requires verified parent KEK state`);\n }\n\n const keyEpoch = readContainerKeyEpoch(\n input.kek.keyEpoch,\n `${input.label} key epoch`,\n );\n const wraps = input.kek.wraps.map((wrap, index) =>\n readContainerKeyWrap(wrap, `${input.label} wrap[${index}]`),\n );\n const userRecipientKeys = await collectContainerUserRecipientKeys({\n containerManifest: input.verifiedManifest,\n resolveUserKey: input.resolveUserKey,\n });\n const verifiedKekManifestHistory = containerKekManifestHistory({\n history: input.verifiedManifestHistory,\n verifiedManifest: input.verifiedManifest,\n });\n const verified = await verifyContainerKekState({\n allowHistoricalParentEpoch: true,\n containerManifest: input.verifiedManifest,\n containerManifestHistory: verifiedKekManifestHistory,\n parentManifestHistory: input.parentManifestHistory,\n keyEpoch,\n parentKekState: input.parentKekState,\n principalPolicies: input.authorizationEvidence,\n userRecipientKeys,\n wraps,\n });\n if (!verified.ok) {\n throw new Error(`${input.label} KEK verification failed`);\n }\n\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n if (keyEpochHash !== input.kek.keyEpochHash) {\n throw new Error(`${input.label} key epoch hash mismatch`);\n }\n const recipientTargets = input.kek.recipientTargets.map((target, index) =>\n readContainerKekRecipientTarget(\n target,\n `${input.label} recipient target[${index}]`,\n ),\n );\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n if (\n keyTargetHash !== input.kek.keyTargetHash ||\n keyTargetHash !== verified.value.keyTargetHash\n ) {\n throw new Error(`${input.label} target hash mismatch`);\n }\n if (\n verified.value.containerKeyEpochId !== input.kek.containerKeyEpochId ||\n verified.value.containerKeyEpoch !== input.kek.containerKeyEpoch ||\n verified.value.accessManifestHash !== input.kek.accessManifestHash ||\n verified.value.parentContainerKeyEpochId !==\n input.kek.parentContainerKeyEpochId\n ) {\n throw new Error(`${input.label} identity mismatch`);\n }\n\n return verified.value;\n}\n\ninterface ContainerWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nexport function verifiedContainerManifestsForBundles(\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n): VerifiedContainerAccessManifest[] {\n return [...bundlesByHash.keys()].flatMap((manifestHash) => {\n const verified = verifiedByHash.get(manifestHash);\n return verified ? [verified] : [];\n });\n}\n\nfunction collectContainerProjectionBundles(\n projection: ContainerWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n projection,\n \"Container writer projection\",\n );\n return bundlesByHash;\n}\n\nexport async function verifyContainerWriterProjectionWithContext(\n input: Omit<ContainerWriterProjectionVerificationInput, \"execSql\"> & {\n readonly authorizationEvidence?: readonly PrincipalPolicyAuthorization[];\n },\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedContainerAccessManifest[]> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n\n const bundlesByHash = collectContainerProjectionBundles(input.projection);\n\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verification = {\n checkpointContext,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n };\n const authorizationEvidence =\n input.authorizationEvidence ??\n (await verifyProjectionAuthorizationEvidence({\n ...verification,\n bundles: [...bundlesByHash.values()],\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n stillCurrent: input.stillCurrent,\n }));\n const verifiedPath = await verifyContainerManifestPath({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: true,\n bundlesByHash,\n enforceLocalCheckpoints: true,\n label: \"Container writer projection path\",\n path: input.projection.path,\n verifiedByHash,\n });\n\n const verifiedKekStates: VerifiedContainerKekState[] = [];\n for (const [index, kek] of input.projection.containerKeks.entries()) {\n const verifiedManifest = verifiedPath[index];\n if (!verifiedManifest) {\n throw new Error(`Container writer projection KEK[${index}] is missing`);\n }\n const verifiedManifestHistory: VerifiedContainerAccessManifest[] = [];\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n verifiedManifestHistory.push(\n await verifyContainerManifestBundle({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle,\n bundlesByHash,\n enforceLocalCheckpoint: false,\n label: `Container writer projection KEK[${index}] history[${historyIndex}]`,\n parentPath: verifiedPath.slice(0, index),\n verifiedByHash,\n }),\n );\n }\n\n const verifiedKekState = await verifyContainerKekProjection({\n authorizationEvidence,\n kek,\n label: `Container writer projection KEK[${index}]`,\n parentKekState: index > 0 ? (verifiedKekStates[index - 1] ?? null) : null,\n resolveUserKey: input.resolveUserKey,\n verifiedManifest,\n verifiedManifestHistory,\n parentManifestHistory: [...verifiedByHash.values()],\n });\n verifiedKekStates.push(verifiedKekState);\n }\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: verifiedPath,\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n checkpointContext.heldContainerHeads.push(...verifiedPath);\n return verifiedPath;\n}\n\nexport async function verifyContainerWriterProjection(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<VerifiedContainerAccessManifest[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const guardedInput = {\n ...withGenerationGuardedPolicyWarmer(input),\n verifiedByHash,\n };\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n guardedInput,\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return verifiedPath;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport async function collectContainerWriterProjectionPrincipalPolicies(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<PrincipalPolicyCurrentEvidence[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n {\n principalPolicyCache,\n projection: input.projection,\n verifiedByHash,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n },\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n\n const policies = await collectPrincipalPoliciesForContainerPaths({\n checkpointContext,\n organizationId: input.projection.organizationId,\n paths: [verifiedPath],\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function addContainerWriterProjectionBundles(\n bundlesByHash: Map<string, AccessManifestBundleWireResponse>,\n projection: ContainerWriterProjectionResponse,\n label: string,\n): void {\n for (const [index, bundle] of projection.path.entries()) {\n addBundleByHash(bundlesByHash, bundle, `${label} path[${index}]`);\n }\n for (const [kekIndex, kek] of projection.containerKeks.entries()) {\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `${label} KEK[${kekIndex}] history[${historyIndex}]`,\n );\n }\n }\n}\n\nasync function collectPrincipalPoliciesForContainerPaths(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n paths: readonly (readonly VerifiedContainerAccessManifest[] | undefined)[];\n principalPolicyCache: PrincipalPolicyCache;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const referencedPrincipalHeads = input.paths.flatMap((path) =>\n (path ?? []).flatMap((manifest) => manifest.state.referencedPrincipalHeads),\n );\n\n return collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references: referencedPrincipalHeads,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerProjectionVerification.js","sourceRoot":"","sources":["containerProjectionVerification.ts"],"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KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,wBAAwB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyAuthorization } from \"@tearleads/crypto\";\nimport {\n type ContainerUserRecipientKey,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n toFingerprint,\n type VerifiedContainerAccessManifest,\n type VerifiedContainerKekState,\n verifyContainerKekState,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { collectReferencedPrincipalPolicies } from \"../principalPolicy/principalPolicyVerification\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport {\n readContainerKekRecipientTarget,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n withGenerationGuardedPolicyWarmer,\n} from \"../types\";\nimport { verifyContainerManifestBundle } from \"./containerManifestVerification\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\n\nasync function collectContainerUserRecipientKeys(input: {\n readonly containerManifest: VerifiedContainerAccessManifest;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<ContainerUserRecipientKey[]> {\n const userIds = [\n ...new Set(\n input.containerManifest.state.directGrants\n .filter((grant) => grant.subjectType === \"user\")\n .map((grant) => grant.subjectId),\n ),\n ].sort();\n const userRecipientKeys: ContainerUserRecipientKey[] = [];\n\n for (const userId of userIds) {\n const userKey = await input.resolveUserKey(userId);\n if (!userKey) {\n throw new ProjectionDependencyUnavailableError(\n `Container writer projection recipient key could not be resolved for ${userId}`,\n );\n }\n const recipientKeyFingerprint = await toFingerprint(\n userKey.encapsulationPublicKey,\n );\n userRecipientKeys.push({\n userId,\n recipientKeyEpochId: `user:${userId}:encapsulation:${recipientKeyFingerprint}`,\n recipientKeyFingerprint,\n });\n }\n\n return userRecipientKeys;\n}\n\nfunction containerKekManifestHistory(input: {\n readonly history: readonly VerifiedContainerAccessManifest[];\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n}): VerifiedContainerAccessManifest[] {\n const historyByHash = new Map<string, VerifiedContainerAccessManifest>();\n\n for (const manifest of input.history) {\n if (\n manifest.state.containerId === input.verifiedManifest.state.containerId &&\n manifest.manifestHash !== input.verifiedManifest.manifestHash\n ) {\n historyByHash.set(manifest.manifestHash, manifest);\n }\n }\n\n return [...historyByHash.values()];\n}\n\nasync function verifyContainerKekProjection(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly kek: ContainerWriterProjectionResponse[\"containerKeks\"][number];\n readonly label: string;\n readonly parentKekState: VerifiedContainerKekState | null;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n readonly verifiedManifestHistory: readonly VerifiedContainerAccessManifest[];\n readonly parentManifestHistory: readonly VerifiedContainerAccessManifest[];\n}): Promise<VerifiedContainerKekState> {\n if (input.verifiedManifest.state.parentContainerId && !input.parentKekState) {\n throw new Error(`${input.label} requires verified parent KEK state`);\n }\n\n const keyEpoch = readContainerKeyEpoch(\n input.kek.keyEpoch,\n `${input.label} key epoch`,\n );\n const wraps = input.kek.wraps.map((wrap, index) =>\n readContainerKeyWrap(wrap, `${input.label} wrap[${index}]`),\n );\n const userRecipientKeys = await collectContainerUserRecipientKeys({\n containerManifest: input.verifiedManifest,\n resolveUserKey: input.resolveUserKey,\n });\n const verifiedKekManifestHistory = containerKekManifestHistory({\n history: input.verifiedManifestHistory,\n verifiedManifest: input.verifiedManifest,\n });\n const verified = await verifyContainerKekState({\n allowHistoricalParentEpoch: true,\n containerManifest: input.verifiedManifest,\n containerManifestHistory: verifiedKekManifestHistory,\n parentManifestHistory: input.parentManifestHistory,\n keyEpoch,\n parentKekState: input.parentKekState,\n principalPolicies: input.authorizationEvidence,\n userRecipientKeys,\n wraps,\n });\n if (!verified.ok) {\n throw new Error(`${input.label} KEK verification failed`);\n }\n\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n if (keyEpochHash !== input.kek.keyEpochHash) {\n throw new Error(`${input.label} key epoch hash mismatch`);\n }\n const recipientTargets = input.kek.recipientTargets.map((target, index) =>\n readContainerKekRecipientTarget(\n target,\n `${input.label} recipient target[${index}]`,\n ),\n );\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n if (\n keyTargetHash !== input.kek.keyTargetHash ||\n keyTargetHash !== verified.value.keyTargetHash\n ) {\n throw new Error(`${input.label} target hash mismatch`);\n }\n if (\n verified.value.containerKeyEpochId !== input.kek.containerKeyEpochId ||\n verified.value.containerKeyEpoch !== input.kek.containerKeyEpoch ||\n verified.value.accessManifestHash !== input.kek.accessManifestHash ||\n verified.value.parentContainerKeyEpochId !==\n input.kek.parentContainerKeyEpochId\n ) {\n throw new Error(`${input.label} identity mismatch`);\n }\n\n return verified.value;\n}\n\ninterface ContainerWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nexport function verifiedContainerManifestsForBundles(\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n): VerifiedContainerAccessManifest[] {\n return [...bundlesByHash.keys()].flatMap((manifestHash) => {\n const verified = verifiedByHash.get(manifestHash);\n return verified ? [verified] : [];\n });\n}\n\nfunction collectContainerProjectionBundles(\n projection: ContainerWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n projection,\n \"Container writer projection\",\n );\n return bundlesByHash;\n}\n\nexport async function verifyContainerWriterProjectionWithContext(\n input: Omit<ContainerWriterProjectionVerificationInput, \"execSql\"> & {\n readonly authorizationEvidence?: readonly PrincipalPolicyAuthorization[];\n },\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedContainerAccessManifest[]> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n\n const bundlesByHash = collectContainerProjectionBundles(input.projection);\n\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verification = {\n checkpointContext,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n };\n const authorizationEvidence =\n input.authorizationEvidence ??\n (await verifyProjectionAuthorizationEvidence({\n ...verification,\n bundles: [...bundlesByHash.values()],\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n stillCurrent: input.stillCurrent,\n }));\n const verifiedPath = await verifyContainerManifestPath({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: true,\n bundlesByHash,\n enforceLocalCheckpoints: true,\n label: \"Container writer projection path\",\n path: input.projection.path,\n verifiedByHash,\n });\n\n const verifiedKekStates: VerifiedContainerKekState[] = [];\n for (const [index, kek] of input.projection.containerKeks.entries()) {\n const verifiedManifest = verifiedPath[index];\n if (!verifiedManifest) {\n throw new Error(`Container writer projection KEK[${index}] is missing`);\n }\n const verifiedManifestHistory: VerifiedContainerAccessManifest[] = [];\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n verifiedManifestHistory.push(\n await verifyContainerManifestBundle({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle,\n bundlesByHash,\n enforceLocalCheckpoint: false,\n label: `Container writer projection KEK[${index}] history[${historyIndex}]`,\n parentPath: verifiedPath.slice(0, index),\n verifiedByHash,\n }),\n );\n }\n\n const verifiedKekState = await verifyContainerKekProjection({\n authorizationEvidence,\n kek,\n label: `Container writer projection KEK[${index}]`,\n parentKekState: index > 0 ? (verifiedKekStates[index - 1] ?? null) : null,\n resolveUserKey: input.resolveUserKey,\n verifiedManifest,\n verifiedManifestHistory,\n parentManifestHistory: [...verifiedByHash.values()],\n });\n verifiedKekStates.push(verifiedKekState);\n }\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: verifiedPath,\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n checkpointContext.heldContainerHeads.push(...verifiedPath);\n return verifiedPath;\n}\n\nexport async function verifyContainerWriterProjection(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<VerifiedContainerAccessManifest[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const guardedInput = {\n ...withGenerationGuardedPolicyWarmer(input),\n verifiedByHash,\n };\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n guardedInput,\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return verifiedPath;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport async function collectContainerWriterProjectionPrincipalPolicies(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<PrincipalPolicyCurrentEvidence[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n {\n principalPolicyCache,\n projection: input.projection,\n verifiedByHash,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n },\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n\n const policies = await collectPrincipalPoliciesForContainerPaths({\n checkpointContext,\n organizationId: input.projection.organizationId,\n paths: [verifiedPath],\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function addContainerWriterProjectionBundles(\n bundlesByHash: Map<string, AccessManifestBundleWireResponse>,\n projection: ContainerWriterProjectionResponse,\n label: string,\n): void {\n for (const [index, bundle] of projection.path.entries()) {\n addBundleByHash(bundlesByHash, bundle, `${label} path[${index}]`);\n }\n for (const [kekIndex, kek] of projection.containerKeks.entries()) {\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `${label} KEK[${kekIndex}] history[${historyIndex}]`,\n );\n }\n }\n}\n\nasync function collectPrincipalPoliciesForContainerPaths(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n paths: readonly (readonly VerifiedContainerAccessManifest[] | undefined)[];\n principalPolicyCache: PrincipalPolicyCache;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const referencedPrincipalHeads = input.paths.flatMap((path) =>\n (path ?? []).flatMap((manifest) => manifest.state.referencedPrincipalHeads),\n );\n\n return collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references: referencedPrincipalHeads,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { addBundleByHash } from "../checkpoints/bundleVerification.js";
|
|
2
|
-
import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeAccessManifestCheckpoints, observeVerifiedProjectionBundles, } from "../checkpoints/checkpointContext.js";
|
|
2
|
+
import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeAccessManifestCheckpoints, observeVerifiedKekLevels, observeVerifiedProjectionBundles, } from "../checkpoints/checkpointContext.js";
|
|
3
3
|
import { verifyContainerManifestPath } from "../container/containerPathVerification.js";
|
|
4
4
|
import { addContainerWriterProjectionBundles, verifiedContainerManifestsForBundles, verifyContainerWriterProjectionWithContext, } from "../container/containerProjectionVerification.js";
|
|
5
5
|
import { rejectPurgedDocumentProjection } from "../documentPurge/documentPurgeCheckpointEnforcement.js";
|
|
@@ -145,6 +145,7 @@ function observeVerifiedDocumentProjectionBundles(checkpointContext, projection,
|
|
|
145
145
|
observeVerifiedProjectionBundles(checkpointContext, collectDocumentProjectionContainerBundles(projection), new Map([...authorization.containerPathByManifestHash.values()]
|
|
146
146
|
.flat()
|
|
147
147
|
.map((manifest) => [manifest.manifestHash, manifest])));
|
|
148
|
+
observeVerifiedKekLevels(checkpointContext, projection.authorizingContainerPaths);
|
|
148
149
|
}
|
|
149
150
|
export async function verifyDocumentWriterProjection(input) {
|
|
150
151
|
const checkpointContext = createProjectionCheckpointContext({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentProjectionVerification.js","sourceRoot":"","sources":["documentProjectionVerification.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EACL,mCAAmC,EACnC,oCAAoC,EACpC,0CAA0C,GAC3C,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,8BAA8B,EAAE,MAAM,qDAAqD,CAAC;AACrG,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;A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AAO,QAAQ,CAAC,YAAY,CAAC;AAC/B,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2CAA2C,CAC/D,KAAgD;IAEhD,IAAI,CAAC;QACH,MAAM,iBAAiB,GAAG,iCAAiC,CAAC;YAC1D,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CAAC,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,iCAAiC,CAAC,KAAK,CAAC,EACxC,iBAAiB,CAClB,CAAC;QACF,wCAAwC,CACtC,iBAAiB,EACjB,KAAK,CAAC,UAAU,EAChB,QAAQ,CAAC,aAAa,CACvB,CAAC;QACF,MAAM,6BAA6B,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;QAC9D,OAAO,QAAQ,CAAC,aAAa,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n PrincipalPolicyAuthorization,\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 \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyContainerManifestPath } from \"../container/containerPathVerification\";\nimport {\n addContainerWriterProjectionBundles,\n verifiedContainerManifestsForBundles,\n verifyContainerWriterProjectionWithContext,\n} from \"../container/containerProjectionVerification\";\nimport { rejectPurgedDocumentProjection } from \"../documentPurge/documentPurgeCheckpointEnforcement\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { readAccessManifest } from \"../readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { withGenerationGuardedPolicyWarmer } from \"../types\";\nimport { documentContainerProjections } from \"./documentContainerProjections\";\nimport { verifyDocumentProjectionManifests } from \"./documentManifestVerification\";\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 PrincipalPolicyAuthorization[];\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 PrincipalPolicyAuthorization[];\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 input.projection.documentManifest,\n ...input.projection.documentManifestHistory,\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 stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\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\n/** Each served bundle, document and container, whose manifest verified. */\nfunction observeVerifiedDocumentProjectionBundles(\n checkpointContext: ProjectionCheckpointContext,\n projection: DocumentWriterProjectionResponse,\n authorization: DocumentWriterProjectionAuthorization,\n): void {\n observeVerifiedProjectionBundles(\n checkpointContext,\n new Map(\n [projection.documentManifest, ...projection.documentManifestHistory].map(\n (bundle) => [bundle.manifestHash, bundle],\n ),\n ),\n authorization.documentManifestByHash,\n );\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectDocumentProjectionContainerBundles(projection),\n new Map(\n [...authorization.containerPathByManifestHash.values()]\n .flat()\n .map((manifest) => [manifest.manifestHash, manifest]),\n ),\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 observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\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 observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\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":"AAWA,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EACL,mCAAmC,EACnC,oCAAoC,EACpC,0CAA0C,GAC3C,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,8BAA8B,EAAE,MAAM,qDAAqD,CAAC;AACrG,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAMhD,OAAO,EAAE,iCAAiC,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UAAU,2CAA2C,CAC/D,KAAgD;IAEhD,IAAI,CAAC;QACH,MAAM,iBAAiB,GAAG,iCAAiC,CAAC;YAC1D,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CAAC,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,iCAAiC,CAAC,KAAK,CAAC,EACxC,iBAAiB,CAClB,CAAC;QACF,wCAAwC,CACtC,iBAAiB,EACjB,KAAK,CAAC,UAAU,EAChB,QAAQ,CAAC,aAAa,CACvB,CAAC;QACF,MAAM,6BAA6B,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;QAC9D,OAAO,QAAQ,CAAC,aAAa,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n PrincipalPolicyAuthorization,\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 \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyContainerManifestPath } from \"../container/containerPathVerification\";\nimport {\n addContainerWriterProjectionBundles,\n verifiedContainerManifestsForBundles,\n verifyContainerWriterProjectionWithContext,\n} from \"../container/containerProjectionVerification\";\nimport { rejectPurgedDocumentProjection } from \"../documentPurge/documentPurgeCheckpointEnforcement\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { readAccessManifest } from \"../readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { withGenerationGuardedPolicyWarmer } from \"../types\";\nimport { documentContainerProjections } from \"./documentContainerProjections\";\nimport { verifyDocumentProjectionManifests } from \"./documentManifestVerification\";\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 PrincipalPolicyAuthorization[];\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 PrincipalPolicyAuthorization[];\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 input.projection.documentManifest,\n ...input.projection.documentManifestHistory,\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 stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\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\n/** Each served bundle, document and container, whose manifest verified. */\nfunction observeVerifiedDocumentProjectionBundles(\n checkpointContext: ProjectionCheckpointContext,\n projection: DocumentWriterProjectionResponse,\n authorization: DocumentWriterProjectionAuthorization,\n): void {\n observeVerifiedProjectionBundles(\n checkpointContext,\n new Map(\n [projection.documentManifest, ...projection.documentManifestHistory].map(\n (bundle) => [bundle.manifestHash, bundle],\n ),\n ),\n authorization.documentManifestByHash,\n );\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectDocumentProjectionContainerBundles(projection),\n new Map(\n [...authorization.containerPathByManifestHash.values()]\n .flat()\n .map((manifest) => [manifest.manifestHash, manifest]),\n ),\n );\n observeVerifiedKekLevels(\n checkpointContext,\n projection.authorizingContainerPaths,\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 observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\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 observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n return verified.authorization;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { MAX_CONTAINER_PATH_LENGTH } from "../../../internal/validators/util/index.js";
|
|
2
|
+
import { and, eq, inArray } from "drizzle-orm";
|
|
3
|
+
import { documentContainerProjection } from "../../sqlite/schema/index.js";
|
|
4
|
+
import { containers } from "../../sqlite/schema/containerSchema.js";
|
|
5
|
+
import { documentDiscoveryHeads, pendingDocumentDiscoveries, } from "../../sqlite/schema/documentDiscoveryEvidenceSchema.js";
|
|
6
|
+
import { verifiedAccessManifestBundles as bundles } from "../../sqlite/schema/verifiedManifestBundleSchema.js";
|
|
7
|
+
/** The requested object first, then each container whose lineage it cites. */
|
|
8
|
+
async function containerLineage(db, containerId, prefix = []) {
|
|
9
|
+
const lineage = [...prefix, containerId];
|
|
10
|
+
while (lineage.length < MAX_CONTAINER_PATH_LENGTH) {
|
|
11
|
+
const [row] = await db
|
|
12
|
+
.select({ parentId: containers.parentId })
|
|
13
|
+
.from(containers)
|
|
14
|
+
.where(eq(containers.id, lineage.at(-1) ?? ""))
|
|
15
|
+
.limit(1);
|
|
16
|
+
const parentId = row?.parentId;
|
|
17
|
+
if (!parentId || lineage.includes(parentId))
|
|
18
|
+
break;
|
|
19
|
+
lineage.push(parentId);
|
|
20
|
+
}
|
|
21
|
+
return lineage;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A container the device has not stored yet has no local parent, so its
|
|
25
|
+
* listing names one: the lineage continues through the listed parent's
|
|
26
|
+
* stored lineage. A wrong parent only changes which held hashes are cited.
|
|
27
|
+
*/
|
|
28
|
+
async function containerTargetLineage(db, target) {
|
|
29
|
+
const parentId = target.listing?.parentId;
|
|
30
|
+
if (!parentId || parentId === target.id)
|
|
31
|
+
return containerLineage(db, target.id);
|
|
32
|
+
const [stored] = await db
|
|
33
|
+
.select({ id: containers.id })
|
|
34
|
+
.from(containers)
|
|
35
|
+
.where(eq(containers.id, target.id))
|
|
36
|
+
.limit(1);
|
|
37
|
+
return stored
|
|
38
|
+
? containerLineage(db, target.id)
|
|
39
|
+
: containerLineage(db, parentId, [target.id]);
|
|
40
|
+
}
|
|
41
|
+
export async function citedObjects(db, target) {
|
|
42
|
+
if (target.kind === "container")
|
|
43
|
+
return (await containerTargetLineage(db, target)).map((id) => ({
|
|
44
|
+
kind: "container",
|
|
45
|
+
id,
|
|
46
|
+
}));
|
|
47
|
+
// Linked containers, containers listing the document before its signed
|
|
48
|
+
// placement is checked, and a container whose metadata document it is.
|
|
49
|
+
const placements = [
|
|
50
|
+
...(await db
|
|
51
|
+
.select({ containerId: documentContainerProjection.containerId })
|
|
52
|
+
.from(documentContainerProjection)
|
|
53
|
+
.where(eq(documentContainerProjection.documentId, target.id))),
|
|
54
|
+
...(await db
|
|
55
|
+
.select({ containerId: pendingDocumentDiscoveries.containerId })
|
|
56
|
+
.from(pendingDocumentDiscoveries)
|
|
57
|
+
.where(eq(pendingDocumentDiscoveries.documentId, target.id))),
|
|
58
|
+
...(await db
|
|
59
|
+
.select({ containerId: containers.id })
|
|
60
|
+
.from(containers)
|
|
61
|
+
.where(eq(containers.metadataDocumentId, target.id))),
|
|
62
|
+
];
|
|
63
|
+
const containerIds = new Set();
|
|
64
|
+
for (const { containerId } of placements)
|
|
65
|
+
if (containerId)
|
|
66
|
+
for (const id of await containerLineage(db, containerId))
|
|
67
|
+
containerIds.add(id);
|
|
68
|
+
return [
|
|
69
|
+
{ kind: "document", id: target.id },
|
|
70
|
+
...[...containerIds].map((id) => ({ kind: "container", id })),
|
|
71
|
+
];
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The one organization every local source places the read in. Verified
|
|
75
|
+
* ownership (stored verified bundles of the target and of the containers on
|
|
76
|
+
* its walk, and a document's verified discovery head) and local placement
|
|
77
|
+
* (listed container rows reached through links, pending listings, metadata,
|
|
78
|
+
* or parents) must all agree: any disagreement, or no source at all, yields
|
|
79
|
+
* null, so the read is sent with no hints rather than another
|
|
80
|
+
* organization's.
|
|
81
|
+
*/
|
|
82
|
+
export async function targetOrganization(db, target, objects) {
|
|
83
|
+
const containerIds = objects
|
|
84
|
+
.filter((object) => object.kind === "container")
|
|
85
|
+
.map((object) => object.id);
|
|
86
|
+
const listed = containerIds.length === 0
|
|
87
|
+
? []
|
|
88
|
+
: await db
|
|
89
|
+
.select({ organizationId: containers.organizationId })
|
|
90
|
+
.from(containers)
|
|
91
|
+
.where(inArray(containers.id, containerIds));
|
|
92
|
+
const verifiedContainers = containerIds.length === 0
|
|
93
|
+
? []
|
|
94
|
+
: await db
|
|
95
|
+
.select({ organizationId: bundles.organizationId })
|
|
96
|
+
.from(bundles)
|
|
97
|
+
.where(and(eq(bundles.objectKind, "container"), inArray(bundles.objectId, containerIds)));
|
|
98
|
+
const verifiedTarget = await db
|
|
99
|
+
.select({ organizationId: bundles.organizationId })
|
|
100
|
+
.from(bundles)
|
|
101
|
+
.where(and(eq(bundles.objectKind, target.kind), eq(bundles.objectId, target.id)));
|
|
102
|
+
const discovered = target.kind === "document"
|
|
103
|
+
? await db
|
|
104
|
+
.select({ organizationId: documentDiscoveryHeads.organizationId })
|
|
105
|
+
.from(documentDiscoveryHeads)
|
|
106
|
+
.where(eq(documentDiscoveryHeads.documentId, target.id))
|
|
107
|
+
: [];
|
|
108
|
+
// The listing that placed an unstored container must agree as well.
|
|
109
|
+
const listing = target.listing ? [target.listing] : [];
|
|
110
|
+
const sources = [
|
|
111
|
+
listed,
|
|
112
|
+
verifiedContainers,
|
|
113
|
+
verifiedTarget,
|
|
114
|
+
discovered,
|
|
115
|
+
listing,
|
|
116
|
+
];
|
|
117
|
+
const organizations = new Set(sources.flat().map((row) => row.organizationId));
|
|
118
|
+
const [organizationId] = organizations;
|
|
119
|
+
return organizations.size === 1 && organizationId ? organizationId : null;
|
|
120
|
+
}
|
|
121
|
+
//# sourceMappingURL=citationScope.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"citationScope.js","sourceRoot":"","sources":["citationScope.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AACjE,OAAO,EACL,sBAAsB,EACtB,0BAA0B,GAC3B,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,6BAA6B,IAAI,OAAO,EAAE,MAAM,kDAAkD,CAAC;AAS5G,8EAA8E;AAC9E,KAAK,UAAU,gBAAgB,CAC7B,EAAwB,EACxB,WAAmB,EACnB,SAA4B,EAAE;IAE9B,MAAM,OAAO,GAAG,CAAC,GAAG,MAAM,EAAE,WAAW,CAAC,CAAC;IACzC,OAAO,OAAO,CAAC,MAAM,GAAG,yBAAyB,EAAE,CAAC;QAClD,MAAM,CAAC,GAAG,CAAC,GAAG,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5B,MAAM,CAAC,EAAE,cAAc,EAAE,OAAO,CAAC,cAAc,EAAE,CAAC;SAClD,IAAI,CAAC,OAAO,CAAC;SACb,KAAK,CACJ,GAAG,CAAC,EAAE,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC,CAC1E,CAAC;IACJ,MAAM,UAAU,GACd,MAAM,CAAC,IAAI,KAAK,UAAU;QACxB,CAAC,CAAC,MAAM,EAAE;aACL,MAAM,CAAC,EAAE,cAAc,EAAE,sBAAsB,CAAC,cAAc,EAAE,CAAC;aACjE,IAAI,CAAC,sBAAsB,CAAC;aAC5B,KAAK,CAAC,EAAE,CAAC,sBAAsB,CAAC,UAAU,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;QAC5D,CAAC,CAAC,EAAE,CAAC;IACT,oEAAoE;IACpE,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACvD,MAAM,OAAO,GAAG;QACd,MAAM;QACN,kBAAkB;QAClB,cAAc;QACd,UAAU;QACV,OAAO;KACR,CAAC;IACF,MAAM,aAAa,GAAG,IAAI,GAAG,CAC3B,OAAO,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,cAAc,CAAC,CAChD,CAAC;IACF,MAAM,CAAC,cAAc,CAAC,GAAG,aAAa,CAAC;IACvC,OAAO,aAAa,CAAC,IAAI,KAAK,CAAC,IAAI,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC;AAC5E,CAAC","sourcesContent":["import type { WriterProjectionTarget } from \"@tearleads/api-client\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { and, eq, inArray } from \"drizzle-orm\";\nimport { documentContainerProjection } from \"../../sqlite/schema\";\nimport { containers } from \"../../sqlite/schema/containerSchema\";\nimport {\n documentDiscoveryHeads,\n pendingDocumentDiscoveries,\n} from \"../../sqlite/schema/documentDiscoveryEvidenceSchema\";\nimport { verifiedAccessManifestBundles as bundles } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport type { ClientSQLiteDatabase } from \"../../sqlite/sqlitePersistenceRuntime\";\n\n/** An object whose verified bytes a projection read may cite. */\nexport interface CitedObject {\n readonly kind: string;\n readonly id: string;\n}\n\n/** The requested object first, then each container whose lineage it cites. */\nasync function containerLineage(\n db: ClientSQLiteDatabase,\n containerId: string,\n prefix: readonly string[] = [],\n): Promise<string[]> {\n const lineage = [...prefix, containerId];\n while (lineage.length < MAX_CONTAINER_PATH_LENGTH) {\n const [row] = await db\n .select({ parentId: containers.parentId })\n .from(containers)\n .where(eq(containers.id, lineage.at(-1) ?? \"\"))\n .limit(1);\n const parentId = row?.parentId;\n if (!parentId || lineage.includes(parentId)) break;\n lineage.push(parentId);\n }\n return lineage;\n}\n\n/**\n * A container the device has not stored yet has no local parent, so its\n * listing names one: the lineage continues through the listed parent's\n * stored lineage. A wrong parent only changes which held hashes are cited.\n */\nasync function containerTargetLineage(\n db: ClientSQLiteDatabase,\n target: WriterProjectionTarget,\n): Promise<string[]> {\n const parentId = target.listing?.parentId;\n if (!parentId || parentId === target.id)\n return containerLineage(db, target.id);\n const [stored] = await db\n .select({ id: containers.id })\n .from(containers)\n .where(eq(containers.id, target.id))\n .limit(1);\n return stored\n ? containerLineage(db, target.id)\n : containerLineage(db, parentId, [target.id]);\n}\n\nexport async function citedObjects(\n db: ClientSQLiteDatabase,\n target: WriterProjectionTarget,\n): Promise<{ readonly kind: string; readonly id: string }[]> {\n if (target.kind === \"container\")\n return (await containerTargetLineage(db, target)).map((id) => ({\n kind: \"container\",\n id,\n }));\n // Linked containers, containers listing the document before its signed\n // placement is checked, and a container whose metadata document it is.\n const placements = [\n ...(await db\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(eq(documentContainerProjection.documentId, target.id))),\n ...(await db\n .select({ containerId: pendingDocumentDiscoveries.containerId })\n .from(pendingDocumentDiscoveries)\n .where(eq(pendingDocumentDiscoveries.documentId, target.id))),\n ...(await db\n .select({ containerId: containers.id })\n .from(containers)\n .where(eq(containers.metadataDocumentId, target.id))),\n ];\n const containerIds = new Set<string>();\n for (const { containerId } of placements)\n if (containerId)\n for (const id of await containerLineage(db, containerId))\n containerIds.add(id);\n return [\n { kind: \"document\", id: target.id },\n ...[...containerIds].map((id) => ({ kind: \"container\", id })),\n ];\n}\n\n/**\n * The one organization every local source places the read in. Verified\n * ownership (stored verified bundles of the target and of the containers on\n * its walk, and a document's verified discovery head) and local placement\n * (listed container rows reached through links, pending listings, metadata,\n * or parents) must all agree: any disagreement, or no source at all, yields\n * null, so the read is sent with no hints rather than another\n * organization's.\n */\nexport async function targetOrganization(\n db: ClientSQLiteDatabase,\n target: WriterProjectionTarget,\n objects: readonly { readonly kind: string; readonly id: string }[],\n): Promise<string | null> {\n const containerIds = objects\n .filter((object) => object.kind === \"container\")\n .map((object) => object.id);\n const listed =\n containerIds.length === 0\n ? []\n : await db\n .select({ organizationId: containers.organizationId })\n .from(containers)\n .where(inArray(containers.id, containerIds));\n const verifiedContainers =\n containerIds.length === 0\n ? []\n : await db\n .select({ organizationId: bundles.organizationId })\n .from(bundles)\n .where(\n and(\n eq(bundles.objectKind, \"container\"),\n inArray(bundles.objectId, containerIds),\n ),\n );\n const verifiedTarget = await db\n .select({ organizationId: bundles.organizationId })\n .from(bundles)\n .where(\n and(eq(bundles.objectKind, target.kind), eq(bundles.objectId, target.id)),\n );\n const discovered =\n target.kind === \"document\"\n ? await db\n .select({ organizationId: documentDiscoveryHeads.organizationId })\n .from(documentDiscoveryHeads)\n .where(eq(documentDiscoveryHeads.documentId, target.id))\n : [];\n // The listing that placed an unstored container must agree as well.\n const listing = target.listing ? [target.listing] : [];\n const sources = [\n listed,\n verifiedContainers,\n verifiedTarget,\n discovered,\n listing,\n ];\n const organizations = new Set(\n sources.flat().map((row) => row.organizationId),\n );\n const [organizationId] = organizations;\n return organizations.size === 1 && organizationId ? organizationId : null;\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type ContainerKekWireLevel } from "../../../internal/validators/response/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Typed rows in the verified-bundle cache that hold one container KEK level
|
|
4
|
+
* each. `manifestHash` (the cache key) and `bundleDigest` are the level's
|
|
5
|
+
* citation digest, the SHA-256 of `bundleJson`, its canonical wire bytes;
|
|
6
|
+
* `objectId` and `epoch` are the level's container and key epoch.
|
|
7
|
+
*/
|
|
8
|
+
export declare const KEK_LEVEL_OBJECT_KIND = "container-kek-level";
|
|
9
|
+
/** A KEK level a projection verification accepted, with its organization. */
|
|
10
|
+
export interface VerifiedKekLevel {
|
|
11
|
+
readonly kekLevel: ContainerKekWireLevel;
|
|
12
|
+
readonly organizationId: string;
|
|
13
|
+
}
|
|
14
|
+
export interface KekLevelRow {
|
|
15
|
+
readonly manifestHash: string;
|
|
16
|
+
readonly organizationId: string;
|
|
17
|
+
readonly objectKind: string;
|
|
18
|
+
readonly objectId: string;
|
|
19
|
+
readonly epoch: number;
|
|
20
|
+
readonly bundleJson: string;
|
|
21
|
+
readonly bundleDigest: string;
|
|
22
|
+
}
|
|
23
|
+
/** Null when the level has no canonical form; such a level is not cited. */
|
|
24
|
+
export declare function kekLevelRow({ kekLevel, organizationId, }: VerifiedKekLevel): Promise<KekLevelRow | null>;
|
|
25
|
+
/**
|
|
26
|
+
* The stored level, or null for a damaged row: its bytes must parse as a
|
|
27
|
+
* full KEK level whose recomputed digest is the row's key.
|
|
28
|
+
*/
|
|
29
|
+
export declare function readStoredKekLevel(row: {
|
|
30
|
+
readonly bundleDigest: string;
|
|
31
|
+
readonly bundleJson: string;
|
|
32
|
+
readonly manifestHash: string;
|
|
33
|
+
}): Promise<ContainerKekWireLevel | null>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { computeContainerKekLevelDigest, readKeyingCanonicalJson, serializeKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
|
|
2
|
+
import { isContainerKekWireLevel, } from "../../../internal/validators/response/index.js";
|
|
3
|
+
/**
|
|
4
|
+
* Typed rows in the verified-bundle cache that hold one container KEK level
|
|
5
|
+
* each. `manifestHash` (the cache key) and `bundleDigest` are the level's
|
|
6
|
+
* citation digest, the SHA-256 of `bundleJson`, its canonical wire bytes;
|
|
7
|
+
* `objectId` and `epoch` are the level's container and key epoch.
|
|
8
|
+
*/
|
|
9
|
+
export const KEK_LEVEL_OBJECT_KIND = "container-kek-level";
|
|
10
|
+
/** Null when the level has no canonical form; such a level is not cited. */
|
|
11
|
+
export async function kekLevelRow({ kekLevel, organizationId, }) {
|
|
12
|
+
const digest = await computeContainerKekLevelDigest(kekLevel);
|
|
13
|
+
if (digest === null)
|
|
14
|
+
return null;
|
|
15
|
+
return {
|
|
16
|
+
manifestHash: digest,
|
|
17
|
+
organizationId,
|
|
18
|
+
objectKind: KEK_LEVEL_OBJECT_KIND,
|
|
19
|
+
objectId: kekLevel.containerId,
|
|
20
|
+
epoch: kekLevel.containerKeyEpoch,
|
|
21
|
+
// Canonical: the digest above is the SHA-256 of exactly these bytes.
|
|
22
|
+
bundleJson: serializeKeyingCanonicalJson(readKeyingCanonicalJson(kekLevel, "Verified KEK level")),
|
|
23
|
+
bundleDigest: digest,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The stored level, or null for a damaged row: its bytes must parse as a
|
|
28
|
+
* full KEK level whose recomputed digest is the row's key.
|
|
29
|
+
*/
|
|
30
|
+
export async function readStoredKekLevel(row) {
|
|
31
|
+
if (row.bundleDigest !== row.manifestHash)
|
|
32
|
+
return null;
|
|
33
|
+
try {
|
|
34
|
+
const level = JSON.parse(row.bundleJson);
|
|
35
|
+
return isContainerKekWireLevel(level) &&
|
|
36
|
+
(await computeContainerKekLevelDigest(level)) === row.manifestHash
|
|
37
|
+
? level
|
|
38
|
+
: null;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=kekLevelCitations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kekLevelCitations.js","sourceRoot":"","sources":["kekLevelCitations.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,8BAA8B,EAC9B,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAEL,uBAAuB,GACxB,MAAM,gCAAgC,CAAC;AAExC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,qBAAqB,CAAC;AAkB3D,4EAA4E;AAC5E,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,EAChC,QAAQ,EACR,cAAc,GACG;IACjB,MAAM,MAAM,GAAG,MAAM,8BAA8B,CAAC,QAAQ,CAAC,CAAC;IAC9D,IAAI,MAAM,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IACjC,OAAO;QACL,YAAY,EAAE,MAAM;QACpB,cAAc;QACd,UAAU,EAAE,qBAAqB;QACjC,QAAQ,EAAE,QAAQ,CAAC,WAAW;QAC9B,KAAK,EAAE,QAAQ,CAAC,iBAAiB;QACjC,qEAAqE;QACrE,UAAU,EAAE,4BAA4B,CACtC,uBAAuB,CAAC,QAAQ,EAAE,oBAAoB,CAAC,CACxD;QACD,YAAY,EAAE,MAAM;KACrB,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,GAIxC;IACC,IAAI,GAAG,CAAC,YAAY,KAAK,GAAG,CAAC,YAAY;QAAE,OAAO,IAAI,CAAC;IACvD,IAAI,CAAC;QACH,MAAM,KAAK,GAAY,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAClD,OAAO,uBAAuB,CAAC,KAAK,CAAC;YACnC,CAAC,MAAM,8BAA8B,CAAC,KAAK,CAAC,CAAC,KAAK,GAAG,CAAC,YAAY;YAClE,CAAC,CAAC,KAAK;YACP,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n computeContainerKekLevelDigest,\n readKeyingCanonicalJson,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport {\n type ContainerKekWireLevel,\n isContainerKekWireLevel,\n} from \"@tearleads/validators/response\";\n\n/**\n * Typed rows in the verified-bundle cache that hold one container KEK level\n * each. `manifestHash` (the cache key) and `bundleDigest` are the level's\n * citation digest, the SHA-256 of `bundleJson`, its canonical wire bytes;\n * `objectId` and `epoch` are the level's container and key epoch.\n */\nexport const KEK_LEVEL_OBJECT_KIND = \"container-kek-level\";\n\n/** A KEK level a projection verification accepted, with its organization. */\nexport interface VerifiedKekLevel {\n readonly kekLevel: ContainerKekWireLevel;\n readonly organizationId: string;\n}\n\nexport interface KekLevelRow {\n readonly manifestHash: string;\n readonly organizationId: string;\n readonly objectKind: string;\n readonly objectId: string;\n readonly epoch: number;\n readonly bundleJson: string;\n readonly bundleDigest: string;\n}\n\n/** Null when the level has no canonical form; such a level is not cited. */\nexport async function kekLevelRow({\n kekLevel,\n organizationId,\n}: VerifiedKekLevel): Promise<KekLevelRow | null> {\n const digest = await computeContainerKekLevelDigest(kekLevel);\n if (digest === null) return null;\n return {\n manifestHash: digest,\n organizationId,\n objectKind: KEK_LEVEL_OBJECT_KIND,\n objectId: kekLevel.containerId,\n epoch: kekLevel.containerKeyEpoch,\n // Canonical: the digest above is the SHA-256 of exactly these bytes.\n bundleJson: serializeKeyingCanonicalJson(\n readKeyingCanonicalJson(kekLevel, \"Verified KEK level\"),\n ),\n bundleDigest: digest,\n };\n}\n\n/**\n * The stored level, or null for a damaged row: its bytes must parse as a\n * full KEK level whose recomputed digest is the row's key.\n */\nexport async function readStoredKekLevel(row: {\n readonly bundleDigest: string;\n readonly bundleJson: string;\n readonly manifestHash: string;\n}): Promise<ContainerKekWireLevel | null> {\n if (row.bundleDigest !== row.manifestHash) return null;\n try {\n const level: unknown = JSON.parse(row.bundleJson);\n return isContainerKekWireLevel(level) &&\n (await computeContainerKekLevelDigest(level)) === row.manifestHash\n ? level\n : null;\n } catch {\n return null;\n }\n}\n"]}
|