@tearleads/client-sdk 0.1.219 → 0.1.220
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/organizations/organizationGroupHistory.js +1 -1
- package/client/organizations/organizationGroupHistory.js.map +1 -1
- package/client/organizations/organizationGroupPresentation.js +1 -1
- package/client/organizations/organizationGroupPresentation.js.map +1 -1
- package/client/organizations/organizationHistory.js +1 -1
- package/client/organizations/organizationHistory.js.map +1 -1
- package/client/organizations/principalMutations.js +1 -1
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/organizations/recipientAdmission.js +1 -1
- package/client/organizations/recipientAdmission.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/bundleVerification.js +1 -1
- package/data/keyingProjectionVerification/checkpoints/bundleVerification.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js +1 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js.map +1 -1
- package/data/keyingProjectionVerification/error.js +1 -1
- package/data/keyingProjectionVerification/error.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/projectionPolicyEvidence.js +1 -1
- package/data/keyingProjectionVerification/principalPolicy/projectionPolicyEvidence.js.map +1 -1
- package/data/principals/principalIdentityCommitments.js +1 -1
- package/data/principals/principalIdentityCommitments.js.map +1 -1
- package/data/trustedUserIdentity/apiAdapter.js +1 -1
- package/data/trustedUserIdentity/apiAdapter.js.map +1 -1
- package/package.json +1 -1
- package/workflows/blobs/verification/attachmentDecryptor.js +1 -1
- package/workflows/blobs/verification/attachmentDecryptor.js.map +1 -1
- package/workflows/blobs/verification/verifiedWrapScope.js +1 -1
- package/workflows/blobs/verification/verifiedWrapScope.js.map +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +1 -1
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -1
- package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
- package/workflows/container-contents/container-state/share/groupShareEpoch.js +1 -1
- package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -1
- package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
- package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
- package/workflows/containers/child/revoke.js +1 -1
- package/workflows/containers/child/revoke.js.map +1 -1
- package/workflows/containers/child/share/index.js +1 -1
- package/workflows/containers/child/share/index.js.map +1 -1
- package/workflows/documents/create/createResponse.js +1 -1
- package/workflows/documents/create/createResponse.js.map +1 -1
- package/workflows/documents/linkSet/linkSetBlobRewraps.js +1 -1
- package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -1
- package/workflows/documents/purge/index.js +1 -1
- package/workflows/documents/purge/index.js.map +1 -1
- package/workflows/documents/syncFailures/syncFailureClassification.js +1 -1
- package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
- package/workflows/organizations/currentOrganizationAuthority.js +1 -1
- package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js +1 -1
- package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataRuntime.js +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -1
- package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js +1 -1
- package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -1
- package/workflows/organizations/groupNames/organizationGroupNames.js +1 -1
- package/workflows/organizations/groupNames/organizationGroupNames.js.map +1 -1
- package/workflows/organizations/groupShare/groupShareReplan.js +1 -1
- package/workflows/organizations/groupShare/groupShareReplan.js.map +1 -1
- package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +1 -1
- package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
- package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js +1 -1
- package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
- package/workflows/principals/principalPolicyService.js +1 -1
- package/workflows/principals/principalPolicyService.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryOutage.js +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryOutage.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.js +1 -1
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
- package/workflows/principals/runtimeProjectionPolicyRecovery.js +1 -1
- package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
- /package/data/{keyingProjectionVerification → shared}/dependencyUnavailable.js +0 -0
- /package/data/{keyingProjectionVerification → shared}/dependencyUnavailable.js.map +0 -0
package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentPurgeCheckpointCurrency.js","sourceRoot":"","sources":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,CAAC;AACL,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,KAA2B;IAE3B,OAAO,4BAA4B,CAAC,KAAK,CAAC,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,KAEC;IAED,OAAO,4BAA4B,CAAC,KAAK,EAAE,KAAK,CAAC,uBAAuB,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedAccessManifestCheckpointEvidence,\n VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"../../persistence/keyingCheckpoints/keyingCheckpointEvidence\";\nimport { accessManifestObjectKey } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n PrincipalAuthorizationCheckpointUnavailableError,\n validatePrincipalAuthorizationCheckpoints,\n} from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport { PrincipalPolicyBundleRepository } from \"../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { registerClientSQLiteCommitGuard } from \"../../sqlite/sqliteCommitGuards\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { validateAccessManifestCheckpoints } from \"../checkpoints/accessManifestCheckpointEnforcement\";\nimport {\n commitProjectionCheckpoints,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { admitDocumentPurgePolicyCheckpoints } from \"./documentPurgePolicyCheckpoints\";\nimport type { PurgePolicyCurrencyEvidence } from \"./documentPurgePolicyCurrency\";\n\ninterface PurgeCheckpointInput {\n readonly context: ProjectionCheckpointContext;\n readonly execSql: ExecSql;\n readonly principalPolicies: readonly VerifiedPrincipalPolicySelection[];\n readonly currencyPolicies: readonly PurgePolicyCurrencyEvidence[];\n readonly observedPrincipalHeads: readonly ReferencedPrincipalHead[];\n}\n\n/** All artifacts must already be authenticated before currency is considered. */\nasync function currentContainerHeads(input: PurgeCheckpointInput) {\n const current: VerifiedAccessManifestCheckpointEvidence[] = [];\n let superseded = false;\n for (const head of input.context.verifiedHeads) {\n const checkpoint = head.checkpoint;\n const local =\n checkpoint.objectKind === \"container\"\n ? await new KeyingCheckpointRepository(\n input.execSql,\n ).loadAccessManifestCheckpoint(\n \"container\",\n checkpoint.organizationId,\n checkpoint.objectId,\n )\n : null;\n if (!local || checkpoint.epoch >= local.epoch) {\n current.push(head);\n continue;\n }\n // A newer head does not order this separately signed purge event. Still\n // reject signed forks visible in the supplied evidence before deferring.\n const key = accessManifestObjectKey(checkpoint);\n validateAccessManifestCheckpointEvidence({\n head,\n localCheckpoint: local,\n predecessors: input.context.verifiedManifests.filter(\n (evidence) =>\n accessManifestObjectKey(evidence.checkpoint) === key &&\n evidence.manifestHash !== head.manifestHash,\n ),\n });\n superseded = true;\n }\n return { current, superseded };\n}\n\nasync function checkPurgeCheckpointCurrency(\n input: PurgeCheckpointInput,\n documentPurgeCheckpoint?: DocumentPurgeCheckpoint,\n): Promise<void> {\n // Keep comparison and optional advancement in the same immediate transaction.\n // Pass the locked executor through nested readers and checkpoint commits.\n await runSerializedSqlMutation(input.execSql, async (execSql) => {\n await getClientSQLitePersistenceRuntime(execSql).transaction(\n async (transaction) => {\n const stillCurrent = projectionLifetimeGuard(input.context);\n registerClientSQLiteCommitGuard(execSql, () =>\n assertProjectionVerificationCurrent(stillCurrent),\n );\n const { current, superseded } = await currentContainerHeads({\n ...input,\n execSql,\n });\n // An older container must not conceal a document fork, a policy fork, or\n // conflicting current evidence for another container in the same proof.\n await validateAccessManifestCheckpoints({\n execSql,\n policies: [],\n verifiedHeads: current,\n verifiedManifests: input.context.verifiedManifests,\n });\n if (input.currencyPolicies.length) {\n await new PrincipalPolicyBundleRepository(\n execSql,\n ).ensurePrincipalPolicyTables();\n await validatePrincipalAuthorizationCheckpoints(\n transaction,\n input.currencyPolicies,\n );\n }\n if (superseded) {\n throw new ProjectionDependencyUnavailableError(\n \"Document purge cannot be ordered against a newer container checkpoint\",\n );\n }\n if (documentPurgeCheckpoint) {\n // Only the complete authenticated terminal proof admits these public\n // observations. Page recovery and baseline verification never pin.\n await admitDocumentPurgePolicyCheckpoints({\n transaction,\n organizationId: input.context.organizationId,\n policies: input.principalPolicies,\n heads: input.observedPrincipalHeads,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n await commitProjectionCheckpoints(\n {\n ...input.context,\n policies: [],\n // Currency was rechecked above in this same transaction. Private\n // ancestry bridges must never become newly admitted purge heads.\n authorizationPolicies: [],\n },\n {\n documentPurgeCheckpoint,\n execSql,\n },\n );\n }\n },\n { behavior: \"immediate\" },\n );\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n}\n\nexport function validateDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput,\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input);\n}\n\nexport function commitDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput & {\n readonly documentPurgeCheckpoint: DocumentPurgeCheckpoint;\n },\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input, input.documentPurgeCheckpoint);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentPurgeCheckpointCurrency.js","sourceRoot":"","sources":["documentPurgeCheckpointCurrency.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,wCAAwC,EAAE,MAAM,8DAA8D,CAAC;AACxH,OAAO,EAAE,uBAAuB,EAAE,MAAM,iEAAiE,CAAC;A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C5C,KAEC;IAED,OAAO,4BAA4B,CAAC,KAAK,EAAE,KAAK,CAAC,uBAAuB,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedAccessManifestCheckpointEvidence,\n VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"../../persistence/keyingCheckpoints/keyingCheckpointEvidence\";\nimport { accessManifestObjectKey } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n PrincipalAuthorizationCheckpointUnavailableError,\n validatePrincipalAuthorizationCheckpoints,\n} from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport { PrincipalPolicyBundleRepository } from \"../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport { registerClientSQLiteCommitGuard } from \"../../sqlite/sqliteCommitGuards\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { validateAccessManifestCheckpoints } from \"../checkpoints/accessManifestCheckpointEnforcement\";\nimport {\n commitProjectionCheckpoints,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { admitDocumentPurgePolicyCheckpoints } from \"./documentPurgePolicyCheckpoints\";\nimport type { PurgePolicyCurrencyEvidence } from \"./documentPurgePolicyCurrency\";\n\ninterface PurgeCheckpointInput {\n readonly context: ProjectionCheckpointContext;\n readonly execSql: ExecSql;\n readonly principalPolicies: readonly VerifiedPrincipalPolicySelection[];\n readonly currencyPolicies: readonly PurgePolicyCurrencyEvidence[];\n readonly observedPrincipalHeads: readonly ReferencedPrincipalHead[];\n}\n\n/** All artifacts must already be authenticated before currency is considered. */\nasync function currentContainerHeads(input: PurgeCheckpointInput) {\n const current: VerifiedAccessManifestCheckpointEvidence[] = [];\n let superseded = false;\n for (const head of input.context.verifiedHeads) {\n const checkpoint = head.checkpoint;\n const local =\n checkpoint.objectKind === \"container\"\n ? await new KeyingCheckpointRepository(\n input.execSql,\n ).loadAccessManifestCheckpoint(\n \"container\",\n checkpoint.organizationId,\n checkpoint.objectId,\n )\n : null;\n if (!local || checkpoint.epoch >= local.epoch) {\n current.push(head);\n continue;\n }\n // A newer head does not order this separately signed purge event. Still\n // reject signed forks visible in the supplied evidence before deferring.\n const key = accessManifestObjectKey(checkpoint);\n validateAccessManifestCheckpointEvidence({\n head,\n localCheckpoint: local,\n predecessors: input.context.verifiedManifests.filter(\n (evidence) =>\n accessManifestObjectKey(evidence.checkpoint) === key &&\n evidence.manifestHash !== head.manifestHash,\n ),\n });\n superseded = true;\n }\n return { current, superseded };\n}\n\nasync function checkPurgeCheckpointCurrency(\n input: PurgeCheckpointInput,\n documentPurgeCheckpoint?: DocumentPurgeCheckpoint,\n): Promise<void> {\n // Keep comparison and optional advancement in the same immediate transaction.\n // Pass the locked executor through nested readers and checkpoint commits.\n await runSerializedSqlMutation(input.execSql, async (execSql) => {\n await getClientSQLitePersistenceRuntime(execSql).transaction(\n async (transaction) => {\n const stillCurrent = projectionLifetimeGuard(input.context);\n registerClientSQLiteCommitGuard(execSql, () =>\n assertProjectionVerificationCurrent(stillCurrent),\n );\n const { current, superseded } = await currentContainerHeads({\n ...input,\n execSql,\n });\n // An older container must not conceal a document fork, a policy fork, or\n // conflicting current evidence for another container in the same proof.\n await validateAccessManifestCheckpoints({\n execSql,\n policies: [],\n verifiedHeads: current,\n verifiedManifests: input.context.verifiedManifests,\n });\n if (input.currencyPolicies.length) {\n await new PrincipalPolicyBundleRepository(\n execSql,\n ).ensurePrincipalPolicyTables();\n await validatePrincipalAuthorizationCheckpoints(\n transaction,\n input.currencyPolicies,\n );\n }\n if (superseded) {\n throw new ProjectionDependencyUnavailableError(\n \"Document purge cannot be ordered against a newer container checkpoint\",\n );\n }\n if (documentPurgeCheckpoint) {\n // Only the complete authenticated terminal proof admits these public\n // observations. Page recovery and baseline verification never pin.\n await admitDocumentPurgePolicyCheckpoints({\n transaction,\n organizationId: input.context.organizationId,\n policies: input.principalPolicies,\n heads: input.observedPrincipalHeads,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n await commitProjectionCheckpoints(\n {\n ...input.context,\n policies: [],\n // Currency was rechecked above in this same transaction. Private\n // ancestry bridges must never become newly admitted purge heads.\n authorizationPolicies: [],\n },\n {\n documentPurgeCheckpoint,\n execSql,\n },\n );\n }\n },\n { behavior: \"immediate\" },\n );\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n}\n\nexport function validateDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput,\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input);\n}\n\nexport function commitDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput & {\n readonly documentPurgeCheckpoint: DocumentPurgeCheckpoint;\n },\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input, input.documentPurgeCheckpoint);\n}\n"]}
|
package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { KeyingVerificationError, readKeyingCanonicalJson, verifyDocumentLinkSetSnapshot, } from "../../../internal/crypto/index.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
|
|
2
3
|
import { addBundleByHash, assertCanonicalEqual, verifyAccessEventBundle, } from "../checkpoints/bundleVerification.js";
|
|
3
4
|
import { observeAccessManifestCheckpoints, } from "../checkpoints/checkpointContext.js";
|
|
4
5
|
import { loadManifestCheckpointVerification } from "../checkpoints/manifestCheckpointVerification.js";
|
|
5
|
-
import { ProjectionDependencyUnavailableError } from "../dependencyUnavailable.js";
|
|
6
6
|
import { verifyDocumentManifestBundle } from "../document/documentManifestVerification.js";
|
|
7
7
|
import { readAccessManifest, readDocumentAccessEventBody } from "../readers.js";
|
|
8
8
|
async function verifyPinnedChainEndpoint(input) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentPurgeDocumentChainVerification.js","sourceRoot":"","sources":["documentPurgeDocumentChainVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,uBAAuB,EAKvB,6BAA6B,GAC9B,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,kCAAkC,EAAE,MAAM,+CAA+C,CAAC;AACnG,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AACxF,OAAO,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,MAAM,YAAY,CAAC;AAG7E,KAAK,UAAU,yBAAyB,CAAC,KAGxC;IACC,MAAM,QAAQ,GAAG,kBAAkB,CACjC,KAAK,CAAC,MAAM,CAAC,QAAQ,EACrB,8CAA8C,CAC/C,CAAC;IACF,MAAM,sBAAsB,GAAG,MAAM,kCAAkC,CAAC;QACtE,OAAO,EAAE,QAAQ;QACjB,OAAO,EAAE,KAAK,CAAC,iBAAiB,CAAC,OAAO;QACxC,gBAAgB,EAAE,KAAK,CAAC,iBAAiB,CAAC,gBAAgB;QAC1D,iBAAiB,EAAE,IAAI,GAAG,EAAE;KAC7B,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,sBAAsB,C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;AAC1B,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyAuthorization,\n readKeyingCanonicalJson,\n type VerifiedAccessManifestSnapshot,\n type VerifiedContainerAccessManifest,\n type VerifiedDocumentLinkSetManifest,\n type VerifiedDocumentLinkSetSnapshot,\n verifyDocumentLinkSetSnapshot,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentPurgeProofResponse,\n} from \"@tearleads/validators/response\";\nimport {\n addBundleByHash,\n assertCanonicalEqual,\n verifyAccessEventBundle,\n} from \"../checkpoints/bundleVerification\";\nimport {\n observeAccessManifestCheckpoints,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { loadManifestCheckpointVerification } from \"../checkpoints/manifestCheckpointVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { verifyDocumentManifestBundle } from \"../document/documentManifestVerification\";\nimport { readAccessManifest, readDocumentAccessEventBody } from \"../readers\";\nimport type { PrincipalPolicyCache, ProjectionUserKeyResolver } from \"../types\";\n\nasync function verifyPinnedChainEndpoint(input: {\n readonly bundle: AccessManifestBundleWireResponse;\n readonly checkpointContext: ProjectionCheckpointContext;\n}): Promise<VerifiedDocumentLinkSetSnapshot> {\n const manifest = readAccessManifest(\n input.bundle.manifest,\n \"Document purge predecessor endpoint manifest\",\n );\n const checkpointVerification = await loadManifestCheckpointVerification({\n current: manifest,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: new Map(),\n });\n const localCheckpoint = checkpointVerification.localCheckpoint;\n if (!localCheckpoint) {\n throw new ProjectionDependencyUnavailableError(\n \"Document purge history needs a local checkpoint or signed genesis\",\n );\n }\n if (\n localCheckpoint.epoch !== manifest.epoch ||\n localCheckpoint.manifestHash !== input.bundle.manifestHash\n ) {\n throw new KeyingVerificationError(\n localCheckpoint.epoch > manifest.epoch ? \"rollback\" : \"stale_predecessor\",\n \"Document purge predecessor chain does not start at the local checkpoint\",\n );\n }\n const verified = await verifyDocumentLinkSetSnapshot({\n ...checkpointVerification,\n expectedManifestHash: input.bundle.manifestHash,\n manifest,\n state: input.bundle.state,\n });\n if (!verified.ok) throw verified.error;\n assertCanonicalEqual({\n actual: input.bundle.state,\n expected: readKeyingCanonicalJson(\n verified.value.state,\n \"Document purge predecessor endpoint state\",\n ),\n label: \"Document purge predecessor endpoint state\",\n });\n return verified.value;\n}\n\nasync function recordSnapshotContainerEvidence(input: {\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly manifest: VerifiedDocumentLinkSetSnapshot;\n readonly proof: DocumentPurgeProofResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly usedContainerManifests?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n}): Promise<void> {\n if (!input.usedContainerManifests) return;\n const event = await verifyAccessEventBundle({\n bundle: input.proof.documentManifest,\n label: \"Document purge manifest snapshot\",\n resolveUserKey: input.resolveUserKey,\n });\n if (event.eventHash !== input.manifest.manifest.eventHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Document purge manifest snapshot event is not bound to its manifest\",\n );\n }\n const body = readDocumentAccessEventBody(\n event.body,\n \"Document purge manifest snapshot event body\",\n );\n const manifestHashes = [\n ...event.event.dependencyManifestHashes,\n body.containerManifestHash,\n ];\n for (const manifestHash of manifestHashes) {\n for (const containerManifest of input.containerPathByManifestHash.get(\n manifestHash,\n ) ?? []) {\n input.usedContainerManifests.set(\n containerManifest.manifestHash,\n containerManifest,\n );\n }\n }\n}\n\nasync function verifyPurgeChainEndpoint(\n input: Parameters<typeof verifySignedPurgeDocumentManifestChain>[0] & {\n readonly endpoint: AccessManifestBundleWireResponse;\n readonly bundlesByHash: ReadonlyMap<\n string,\n AccessManifestBundleWireResponse\n >;\n readonly verifiedByHash: Map<string, VerifiedDocumentLinkSetManifest>;\n },\n): Promise<VerifiedDocumentLinkSetSnapshot | null> {\n const endpointManifest = readAccessManifest(\n input.endpoint.manifest,\n \"Document purge chain endpoint\",\n );\n if (endpointManifest.previousManifestHash === null) {\n await verifyDocumentManifestBundle({\n ...input,\n authorizationMembership: \"referenced\",\n bundle: input.endpoint,\n enforceLocalCheckpoint: false,\n label: \"Document purge genesis\",\n requireAuthorizationEvidence: true,\n });\n return null;\n }\n if (!input.enforceLocalCheckpoints) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Initial document purge history does not reach signed genesis\",\n );\n }\n return verifyPinnedChainEndpoint({\n bundle: input.endpoint,\n checkpointContext: input.checkpointContext,\n });\n}\n\nasync function verifySignedPurgeDocumentManifestChain(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly enforceLocalCheckpoints: boolean;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly proof: DocumentPurgeProofResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly usedContainerManifests?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n}): Promise<VerifiedDocumentLinkSetManifest> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addBundleByHash(\n bundlesByHash,\n input.proof.documentManifest,\n \"Document purge manifest\",\n );\n for (const [\n index,\n bundle,\n ] of input.proof.documentManifestPredecessors.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document purge predecessor[${index}]`,\n );\n }\n\n const endpoint =\n input.proof.documentManifestPredecessors.at(-1) ??\n input.proof.documentManifest;\n const verifiedByHash = new Map<string, VerifiedDocumentLinkSetManifest>();\n const trustedPredecessorByHash = new Map<\n string,\n VerifiedDocumentLinkSetSnapshot\n >();\n const verifiedEndpoint = await verifyPurgeChainEndpoint({\n ...input,\n endpoint,\n bundlesByHash,\n verifiedByHash,\n });\n if (verifiedEndpoint) {\n trustedPredecessorByHash.set(\n verifiedEndpoint.manifestHash,\n verifiedEndpoint,\n );\n }\n\n const verificationInput = {\n ...input,\n authorizationMembership: \"referenced\" as const,\n bundlesByHash,\n requireAuthorizationEvidence: true,\n trustedPredecessorByHash,\n verifiedByHash,\n };\n for (\n let index = input.proof.documentManifestPredecessors.length - 2;\n index >= 0;\n index -= 1\n ) {\n const bundle = input.proof.documentManifestPredecessors[index];\n if (!bundle) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `Document purge predecessor[${index}] is missing`,\n );\n }\n await verifyDocumentManifestBundle({\n ...verificationInput,\n bundle,\n enforceLocalCheckpoint: false,\n label: `Document purge predecessor[${index}]`,\n });\n }\n const head = await verifyDocumentManifestBundle({\n ...verificationInput,\n bundle: input.proof.documentManifest,\n enforceLocalCheckpoint: input.enforceLocalCheckpoints,\n label: \"Document purge manifest\",\n });\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: [head],\n verifiedManifests: [...verifiedByHash.values()],\n });\n return head;\n}\n\nexport async function verifyPurgeDocumentManifest(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly enforceLocalCheckpoints: boolean;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly proof: DocumentPurgeProofResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly usedContainerManifests?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n}): Promise<VerifiedDocumentLinkSetManifest | VerifiedDocumentLinkSetSnapshot> {\n const verifiedByHash = new Map<string, VerifiedAccessManifestSnapshot>();\n const manifest = readAccessManifest(\n input.proof.documentManifest.manifest,\n \"Document purge manifest snapshot\",\n );\n const checkpointVerification = input.enforceLocalCheckpoints\n ? await loadManifestCheckpointVerification({\n current: manifest,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: verifiedByHash,\n })\n : undefined;\n const localCheckpoint = checkpointVerification?.localCheckpoint;\n const isPinnedHead =\n localCheckpoint?.epoch === manifest.epoch &&\n localCheckpoint.manifestHash === input.proof.documentManifest.manifestHash;\n // Baseline inspection may read a hash-only snapshot. Committing a purge\n // requires an exact existing pin or verified signed transitions from\n // that pin (or signed genesis for a fresh device).\n if (\n input.proof.documentManifestPredecessors.length > 0 ||\n (input.enforceLocalCheckpoints && !isPinnedHead)\n ) {\n return verifySignedPurgeDocumentManifestChain(input);\n }\n const verified = await verifyDocumentLinkSetSnapshot({\n ...(checkpointVerification ?? {}),\n expectedManifestHash: input.proof.documentManifest.manifestHash,\n manifest,\n state: input.proof.documentManifest.state,\n });\n if (!verified.ok) throw verified.error;\n const documentManifest = verified.value;\n await recordSnapshotContainerEvidence({\n containerPathByManifestHash: input.containerPathByManifestHash,\n manifest: documentManifest,\n proof: input.proof,\n resolveUserKey: input.resolveUserKey,\n usedContainerManifests: input.usedContainerManifests,\n });\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: [documentManifest],\n verifiedManifests: [...verifiedByHash.values()],\n });\n return documentManifest;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentPurgeDocumentChainVerification.js","sourceRoot":"","sources":["documentPurgeDocumentChainVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,uBAAuB,EAKvB,6BAA6B,GAC9B,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAC1F,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,kCAAkC,EAAE,MAAM,+CAA+C,CAAC;AACnG,OAAO,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AACxF,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C,MAAM,gBAAgB,GAAG,QAAQ,CAAC,KAAK,CAAC;IACxC,MAAM,+BAA+B,CAAC;QACpC,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;QAC9D,QAAQ,EAAE,gBAAgB;QAC1B,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;KACrD,CAAC,CAAC;IACH,gCAAgC,CAAC,KAAK,CAAC,iBAAiB,EAAE;QACxD,aAAa,EAAE,CAAC,gBAAgB,CAAC;QACjC,iBAAiB,EAAE,CAAC,GAAG,cAAc,CAAC,MAAM,EAAE,CAAC;KAChD,CAAC,CAAC;IACH,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyAuthorization,\n readKeyingCanonicalJson,\n type VerifiedAccessManifestSnapshot,\n type VerifiedContainerAccessManifest,\n type VerifiedDocumentLinkSetManifest,\n type VerifiedDocumentLinkSetSnapshot,\n verifyDocumentLinkSetSnapshot,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentPurgeProofResponse,\n} from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport {\n addBundleByHash,\n assertCanonicalEqual,\n verifyAccessEventBundle,\n} from \"../checkpoints/bundleVerification\";\nimport {\n observeAccessManifestCheckpoints,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { loadManifestCheckpointVerification } from \"../checkpoints/manifestCheckpointVerification\";\nimport { verifyDocumentManifestBundle } from \"../document/documentManifestVerification\";\nimport { readAccessManifest, readDocumentAccessEventBody } from \"../readers\";\nimport type { PrincipalPolicyCache, ProjectionUserKeyResolver } from \"../types\";\n\nasync function verifyPinnedChainEndpoint(input: {\n readonly bundle: AccessManifestBundleWireResponse;\n readonly checkpointContext: ProjectionCheckpointContext;\n}): Promise<VerifiedDocumentLinkSetSnapshot> {\n const manifest = readAccessManifest(\n input.bundle.manifest,\n \"Document purge predecessor endpoint manifest\",\n );\n const checkpointVerification = await loadManifestCheckpointVerification({\n current: manifest,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: new Map(),\n });\n const localCheckpoint = checkpointVerification.localCheckpoint;\n if (!localCheckpoint) {\n throw new ProjectionDependencyUnavailableError(\n \"Document purge history needs a local checkpoint or signed genesis\",\n );\n }\n if (\n localCheckpoint.epoch !== manifest.epoch ||\n localCheckpoint.manifestHash !== input.bundle.manifestHash\n ) {\n throw new KeyingVerificationError(\n localCheckpoint.epoch > manifest.epoch ? \"rollback\" : \"stale_predecessor\",\n \"Document purge predecessor chain does not start at the local checkpoint\",\n );\n }\n const verified = await verifyDocumentLinkSetSnapshot({\n ...checkpointVerification,\n expectedManifestHash: input.bundle.manifestHash,\n manifest,\n state: input.bundle.state,\n });\n if (!verified.ok) throw verified.error;\n assertCanonicalEqual({\n actual: input.bundle.state,\n expected: readKeyingCanonicalJson(\n verified.value.state,\n \"Document purge predecessor endpoint state\",\n ),\n label: \"Document purge predecessor endpoint state\",\n });\n return verified.value;\n}\n\nasync function recordSnapshotContainerEvidence(input: {\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly manifest: VerifiedDocumentLinkSetSnapshot;\n readonly proof: DocumentPurgeProofResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly usedContainerManifests?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n}): Promise<void> {\n if (!input.usedContainerManifests) return;\n const event = await verifyAccessEventBundle({\n bundle: input.proof.documentManifest,\n label: \"Document purge manifest snapshot\",\n resolveUserKey: input.resolveUserKey,\n });\n if (event.eventHash !== input.manifest.manifest.eventHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Document purge manifest snapshot event is not bound to its manifest\",\n );\n }\n const body = readDocumentAccessEventBody(\n event.body,\n \"Document purge manifest snapshot event body\",\n );\n const manifestHashes = [\n ...event.event.dependencyManifestHashes,\n body.containerManifestHash,\n ];\n for (const manifestHash of manifestHashes) {\n for (const containerManifest of input.containerPathByManifestHash.get(\n manifestHash,\n ) ?? []) {\n input.usedContainerManifests.set(\n containerManifest.manifestHash,\n containerManifest,\n );\n }\n }\n}\n\nasync function verifyPurgeChainEndpoint(\n input: Parameters<typeof verifySignedPurgeDocumentManifestChain>[0] & {\n readonly endpoint: AccessManifestBundleWireResponse;\n readonly bundlesByHash: ReadonlyMap<\n string,\n AccessManifestBundleWireResponse\n >;\n readonly verifiedByHash: Map<string, VerifiedDocumentLinkSetManifest>;\n },\n): Promise<VerifiedDocumentLinkSetSnapshot | null> {\n const endpointManifest = readAccessManifest(\n input.endpoint.manifest,\n \"Document purge chain endpoint\",\n );\n if (endpointManifest.previousManifestHash === null) {\n await verifyDocumentManifestBundle({\n ...input,\n authorizationMembership: \"referenced\",\n bundle: input.endpoint,\n enforceLocalCheckpoint: false,\n label: \"Document purge genesis\",\n requireAuthorizationEvidence: true,\n });\n return null;\n }\n if (!input.enforceLocalCheckpoints) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Initial document purge history does not reach signed genesis\",\n );\n }\n return verifyPinnedChainEndpoint({\n bundle: input.endpoint,\n checkpointContext: input.checkpointContext,\n });\n}\n\nasync function verifySignedPurgeDocumentManifestChain(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly enforceLocalCheckpoints: boolean;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly proof: DocumentPurgeProofResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly usedContainerManifests?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n}): Promise<VerifiedDocumentLinkSetManifest> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addBundleByHash(\n bundlesByHash,\n input.proof.documentManifest,\n \"Document purge manifest\",\n );\n for (const [\n index,\n bundle,\n ] of input.proof.documentManifestPredecessors.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document purge predecessor[${index}]`,\n );\n }\n\n const endpoint =\n input.proof.documentManifestPredecessors.at(-1) ??\n input.proof.documentManifest;\n const verifiedByHash = new Map<string, VerifiedDocumentLinkSetManifest>();\n const trustedPredecessorByHash = new Map<\n string,\n VerifiedDocumentLinkSetSnapshot\n >();\n const verifiedEndpoint = await verifyPurgeChainEndpoint({\n ...input,\n endpoint,\n bundlesByHash,\n verifiedByHash,\n });\n if (verifiedEndpoint) {\n trustedPredecessorByHash.set(\n verifiedEndpoint.manifestHash,\n verifiedEndpoint,\n );\n }\n\n const verificationInput = {\n ...input,\n authorizationMembership: \"referenced\" as const,\n bundlesByHash,\n requireAuthorizationEvidence: true,\n trustedPredecessorByHash,\n verifiedByHash,\n };\n for (\n let index = input.proof.documentManifestPredecessors.length - 2;\n index >= 0;\n index -= 1\n ) {\n const bundle = input.proof.documentManifestPredecessors[index];\n if (!bundle) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `Document purge predecessor[${index}] is missing`,\n );\n }\n await verifyDocumentManifestBundle({\n ...verificationInput,\n bundle,\n enforceLocalCheckpoint: false,\n label: `Document purge predecessor[${index}]`,\n });\n }\n const head = await verifyDocumentManifestBundle({\n ...verificationInput,\n bundle: input.proof.documentManifest,\n enforceLocalCheckpoint: input.enforceLocalCheckpoints,\n label: \"Document purge manifest\",\n });\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: [head],\n verifiedManifests: [...verifiedByHash.values()],\n });\n return head;\n}\n\nexport async function verifyPurgeDocumentManifest(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly enforceLocalCheckpoints: boolean;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly proof: DocumentPurgeProofResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly usedContainerManifests?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n}): Promise<VerifiedDocumentLinkSetManifest | VerifiedDocumentLinkSetSnapshot> {\n const verifiedByHash = new Map<string, VerifiedAccessManifestSnapshot>();\n const manifest = readAccessManifest(\n input.proof.documentManifest.manifest,\n \"Document purge manifest snapshot\",\n );\n const checkpointVerification = input.enforceLocalCheckpoints\n ? await loadManifestCheckpointVerification({\n current: manifest,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: verifiedByHash,\n })\n : undefined;\n const localCheckpoint = checkpointVerification?.localCheckpoint;\n const isPinnedHead =\n localCheckpoint?.epoch === manifest.epoch &&\n localCheckpoint.manifestHash === input.proof.documentManifest.manifestHash;\n // Baseline inspection may read a hash-only snapshot. Committing a purge\n // requires an exact existing pin or verified signed transitions from\n // that pin (or signed genesis for a fresh device).\n if (\n input.proof.documentManifestPredecessors.length > 0 ||\n (input.enforceLocalCheckpoints && !isPinnedHead)\n ) {\n return verifySignedPurgeDocumentManifestChain(input);\n }\n const verified = await verifyDocumentLinkSetSnapshot({\n ...(checkpointVerification ?? {}),\n expectedManifestHash: input.proof.documentManifest.manifestHash,\n manifest,\n state: input.proof.documentManifest.state,\n });\n if (!verified.ok) throw verified.error;\n const documentManifest = verified.value;\n await recordSnapshotContainerEvidence({\n containerPathByManifestHash: input.containerPathByManifestHash,\n manifest: documentManifest,\n proof: input.proof,\n resolveUserKey: input.resolveUserKey,\n usedContainerManifests: input.usedContainerManifests,\n });\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: [documentManifest],\n verifiedManifests: [...verifiedByHash.values()],\n });\n return documentManifest;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../shared/dependencyUnavailable.js";
|
|
2
3
|
import { errorMessage } from "../shared/errorMessage.js";
|
|
3
4
|
import { isDatabaseUnavailableError } from "../sync/databaseUnavailable.js";
|
|
4
|
-
import { ProjectionDependencyUnavailableError } from "./dependencyUnavailable.js";
|
|
5
5
|
import { rethrowProjectionVerificationCancelled } from "./types.js";
|
|
6
6
|
const KEYING_VERIFICATION_CONTEXT_LIMIT = 16;
|
|
7
7
|
const KEYING_VERIFICATION_CAUSE_LIMIT = 16;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.js","sourceRoot":"","sources":["error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"error.js","sourceRoot":"","sources":["error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,iCAAiC,CAAC;AACvF,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAKtD,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AACzE,OAAO,EAAE,sCAAsC,EAAE,MAAM,SAAS,CAAC;AAEjE,MAAM,iCAAiC,GAAG,EAAE,CAAC;AAC7C,MAAM,+BAA+B,GAAG,EAAE,CAAC;AAE3C,sEAAsE;AACtE,MAAM,UAAU,2BAA2B,CAAI,IAAa;IAC1D,IAAI,CAAC;QACH,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB;YAAE,MAAM,KAAK,CAAC;QAC1D,MAAM,IAAI,uBAAuB,CAAC,eAAe,EAAE,YAAY,CAAC,KAAK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CAAC;QAChC,CAAC,8BAA8B,CAAC,KAAK,CAAC;QAEtC,MAAM,KAAK,CAAC;IACd,MAAM,IAAI,uBAAuB,CAAC,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;AACpE,CAAC;AAED,MAAM,UAAU,uCAAuC,CACrD,KAAc,EACd,OAAe;IAEf,4EAA4E;IAC5E,0CAA0C,CAAC,KAAK,CAAC,CAAC;IAClD,IAAI,yBAAyB,CAAC,KAAK,CAAC,EAAE,CAAC;QACrC,yEAAyE;QACzE,2EAA2E;QAC3E,0EAA0E;QAC1E,gEAAgE;QAChE,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,4BAA4B,CAAC,CAAC;YAClE,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;gBACtC,CAAC,CAAC,CAAC,GAAG,QAAQ,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,iCAAiC,CAAC;gBAClE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;YACd,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,4BAA4B,EAAE;gBACzD,YAAY,EAAE,IAAI;gBAClB,UAAU,EAAE,KAAK;gBACjB,KAAK,EAAE,QAAQ;aAChB,CAAC,CAAC;QACL,CAAC;QAAC,MAAM,CAAC;YACP,gEAAgE;QAClE,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;IACD,MAAM,OAAO,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;IACpC,MAAM,IAAI,KAAK,CAAC,GAAG,OAAO,KAAK,OAAO,EAAE,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../shared/dependencyUnavailable\";\nimport { errorMessage } from \"../shared/errorMessage\";\nimport type {\n SecurityIncidentContext,\n SecurityIncidentReporter,\n} from \"../shared/securityIncidents\";\nimport { isDatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport { rethrowProjectionVerificationCancelled } from \"./types\";\n\nconst KEYING_VERIFICATION_CONTEXT_LIMIT = 16;\nconst KEYING_VERIFICATION_CAUSE_LIMIT = 16;\n\n/** Use only for synchronous parsing of received protocol material. */\nexport function readKeyingVerificationShape<T>(read: () => T): T {\n try {\n return read();\n } catch (error) {\n if (error instanceof KeyingVerificationError) throw error;\n throw new KeyingVerificationError(\"invalid_shape\", errorMessage(error));\n }\n}\n\n/**\n * Preserve identity and projection verification failures across workflow\n * boundaries that intentionally soften ordinary transport or availability\n * errors. These failures are terminal: retrying or falling back could continue\n * with an untrusted identity.\n */\nexport function isKeyingVerificationError(\n error: unknown,\n): error is Error & { readonly code?: unknown } {\n return (\n error instanceof KeyingVerificationError ||\n (error instanceof Error && error.name === \"KeyingVerificationError\")\n );\n}\n\nexport function rethrowKeyingVerificationError(error: unknown): void {\n if (isKeyingVerificationError(error)) {\n throw error;\n }\n}\n\nfunction keyingVerificationErrorInCauseChain(\n error: unknown,\n): (Error & { readonly code?: unknown }) | null {\n let current = error;\n const seen = new Set<unknown>();\n for (let depth = 0; depth < KEYING_VERIFICATION_CAUSE_LIMIT; depth += 1) {\n if (isKeyingVerificationError(current)) return current;\n if (!(current instanceof Error) || seen.has(current)) return null;\n seen.add(current);\n current = current.cause;\n }\n return null;\n}\n\nexport async function reportKeyingVerificationErrorInCauseChain(\n error: unknown,\n reporter: SecurityIncidentReporter | undefined,\n context: SecurityIncidentContext,\n): Promise<boolean> {\n const verificationError = keyingVerificationErrorInCauseChain(error);\n if (!verificationError) return false;\n try {\n await reporter?.(verificationError, context);\n } catch {\n // Incident reporting is best-effort at this boundary. It must never replace\n // the boundary behavior that stopped use of untrusted data.\n }\n return true;\n}\n\n/**\n * Persist a terminal integrity failure before preserving the boundary error.\n * Call only outside an open persistence transaction: the reporter serializes\n * its own write and awaiting it from that transaction would deadlock.\n */\nexport async function reportAndRethrowKeyingVerificationError(\n error: unknown,\n reporter: SecurityIncidentReporter | undefined,\n context: SecurityIncidentContext,\n): Promise<void> {\n const reported = await reportKeyingVerificationErrorInCauseChain(\n error,\n reporter,\n context,\n );\n if (!reported) return;\n throw error;\n}\n\nexport async function runWithSecurityIncidentReporting<T>(\n reporter: SecurityIncidentReporter | undefined,\n context: SecurityIncidentContext,\n operation: () => Promise<T>,\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n await reportAndRethrowKeyingVerificationError(error, reporter, context);\n throw error;\n }\n}\n\nexport function rethrowDatabaseUnavailableError(error: unknown): void {\n if (isDatabaseUnavailableError(error)) {\n throw error;\n }\n}\n\nexport function rethrowProjectionVerificationBoundaryError(\n error: unknown,\n): void {\n rethrowDatabaseUnavailableError(error);\n rethrowProjectionVerificationCancelled(error);\n if (error instanceof ProjectionDependencyUnavailableError) throw error;\n}\n\n/**\n * The verification layer reports a shape or hash failure in received protocol\n * material with a plain `Error` (or a `SyntaxError` from decoding its JSON).\n * Anything more specific is not evidence about that material: a boundary error\n * is retryable, a `TypeError` or other typed runtime failure is a defect, and a\n * non-Error value is a foreign throw. Those keep their type so callers can\n * classify them instead of recording them as tampering.\n */\nfunction isReceivedMaterialShapeFailure(error: unknown): error is Error {\n return (\n error instanceof Error &&\n (Object.getPrototypeOf(error) === Error.prototype ||\n error instanceof SyntaxError)\n );\n}\n\n/** Classify the failure of an async verification pass; never returns. */\nexport function throwKeyingVerificationShapeFailure(error: unknown): never {\n rethrowProjectionVerificationBoundaryError(error);\n if (\n isKeyingVerificationError(error) ||\n !isReceivedMaterialShapeFailure(error)\n )\n throw error;\n throw new KeyingVerificationError(\"invalid_shape\", error.message);\n}\n\nexport function throwKeyingVerificationErrorWithContext(\n error: unknown,\n context: string,\n): never {\n // Availability and cancellation keep their retryable types across contexts.\n rethrowProjectionVerificationBoundaryError(error);\n if (isKeyingVerificationError(error)) {\n // Preserve identity so nested reporting boundaries persist one incident.\n // The incident's operation supplies boundary context without minting a new\n // verification error that could bypass identity-based deduplication. Keep\n // the boundary labels non-enumerably for host-side diagnostics.\n try {\n const previous = Reflect.get(error, \"keyingVerificationContexts\");\n const contexts = Array.isArray(previous)\n ? [...previous, context].slice(-KEYING_VERIFICATION_CONTEXT_LIMIT)\n : [context];\n Object.defineProperty(error, \"keyingVerificationContexts\", {\n configurable: true,\n enumerable: false,\n value: contexts,\n });\n } catch {\n // A frozen foreign error still preserves its identity and code.\n }\n throw error;\n }\n const message = errorMessage(error);\n throw new Error(`${context}: ${message}`);\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError, toFingerprint, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { withUnauthenticatedPolicyIdentities } from "../../principals/principalIdentityCommitments.js";
|
|
3
3
|
import { principalPolicyBundleStates } from "../../principals/principalPolicyStates.js";
|
|
4
|
-
import { ProjectionDependencyUnavailableError } from "
|
|
4
|
+
import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
|
|
5
5
|
/**
|
|
6
6
|
* Signers and committed members of a fetched bundle, compared before its
|
|
7
7
|
* signatures are checked and pinned only by `publishVerifiedPolicyBundle`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicySigners.js","sourceRoot":"","sources":["principalPolicySigners.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,aAAa,GACd,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EAAE,oCAAoC,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"principalPolicySigners.js","sourceRoot":"","sources":["principalPolicySigners.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,aAAa,GACd,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAA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;gBAC7D,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,GAAG,KAAK,CAAC,KAAK,kCAAkC,CACjD,CAAC;YACJ,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE;gBACpB,MAAM,EAAE,KAAK,CAAC,YAAY;gBAC1B,qBAAqB;gBACrB,gBAAgB,EAAE,SAAS,CAAC,gBAAgB;aAC7C,CAAC,CAAC;QACL,CAAC;QACD,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAC/B,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicySignerPublicKey,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { withUnauthenticatedPolicyIdentities } from \"../../principals/principalIdentityCommitments\";\nimport { principalPolicyBundleStates } from \"../../principals/principalPolicyStates\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ProjectionUserKeyResolver } from \"../types\";\n\n/**\n * Signers and committed members of a fetched bundle, compared before its\n * signatures are checked and pinned only by `publishVerifiedPolicyBundle`\n * once the caller's verification succeeds.\n */\nexport async function collectPrincipalPolicySignerPublicKeys(input: {\n bundle: PrincipalPolicyBundleResponse;\n label: string;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<PrincipalPolicySignerPublicKey[]> {\n const states = principalPolicyBundleStates(input.bundle);\n // Signatures are checked after collection: compare, but pin nothing yet.\n return withUnauthenticatedPolicyIdentities(\n {\n signerUserIds: states.map((state) => state.signerUserId),\n projections: [\n ...input.bundle.previousStates.map((entry) => entry.projection),\n input.bundle.currentProjection,\n ],\n resolveTrustedUserIdentity: input.resolveUserKey,\n },\n async (resolve) => {\n const signers = new Map<string, PrincipalPolicySignerPublicKey>();\n for (const state of states) {\n const cacheKey = `${state.signerUserId}:${state.signerUserKeyFingerprint}`;\n if (signers.has(cacheKey)) continue;\n const signerKey = await resolve(state.signerUserId);\n if (!signerKey) {\n throw new ProjectionDependencyUnavailableError(\n `${input.label} signer key could not be resolved for ${state.signerUserId}`,\n );\n }\n const signingKeyFingerprint = await toFingerprint(\n signerKey.signingPublicKey,\n );\n if (signingKeyFingerprint !== state.signerUserKeyFingerprint) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${input.label} signer key fingerprint mismatch`,\n );\n }\n signers.set(cacheKey, {\n userId: state.signerUserId,\n signingKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n });\n }\n return [...signers.values()];\n },\n );\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
|
|
3
3
|
import { assertProjectionVerificationCurrent, } from "../types.js";
|
|
4
4
|
/** Recover public authorization without admitting historical heads as current policy. */
|
|
5
5
|
export async function verifyProjectionPolicyEvidence(input) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"projectionPolicyEvidence.js","sourceRoot":"","sources":["projectionPolicyEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"projectionPolicyEvidence.js","sourceRoot":"","sources":["projectionPolicyEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAC1F,OAAO,EACL,mCAAmC,GAGpC,MAAM,UAAU,CAAC;AAElB,yFAAyF;AACzF,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KASpD;IACC,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,CAAC;IAC5D,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,YAAY,EAAE,CAAC;QACjC,IACE,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM;YAC5B,KAAK,CAAC,QAAQ,CAAC,oBAAoB,CAAC,MAAM;YAC1C,KAAK,CAAC,UAAU,CAAC,MAAM;YAEvB,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,gDAAgD,CACjD,CAAC;QACJ,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,YAAY,EAAE,CAAC;IACxC,CAAC;IACD,MAAM,OAAO,GACX,KAAK,CAAC,+BAA+B,EAAE,wBAAwB,CAAC;IAClE,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,oDAAoD,CACrD,CAAC;IACJ,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;IACzD,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,mCAAmC,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IACzD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedProjectionPolicyHistory,\n} from \"../types\";\n\n/** Recover public authorization without admitting historical heads as current policy. */\nexport async function verifyProjectionPolicyEvidence(input: {\n readonly historicalProof?: boolean | undefined;\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly organizationId: string;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<ResolvedProjectionPolicyHistory> {\n const stillCurrent = () => input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n if (!input.evidence.organization) {\n if (\n input.evidence.groups.length ||\n input.evidence.organizationPayloads.length ||\n input.references.length\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection omits required organization history\",\n );\n return { policies: [], stillCurrent };\n }\n const resolve =\n input.warmReferencedPrincipalPolicies?.resolveProjectionHistory;\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Private projection history recovery is unavailable\",\n );\n const result = await resolve({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n assertProjectionVerificationCurrent(result.stillCurrent);\n return result;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { computeUserIdentityBundleFingerprint, KeyingVerificationError, } from "../../internal/crypto/index.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "../
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../shared/dependencyUnavailable.js";
|
|
3
3
|
/**
|
|
4
4
|
* Structural verification only: never recurse into roster admission here.
|
|
5
5
|
* Pass `authenticated` only once every projection's signed state verified.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalIdentityCommitments.js","sourceRoot":"","sources":["principalIdentityCommitments.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,uDAAuD,CAAC;AAO7G;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,kCAAkC,CAAC,KAMxD;IACC,MAAM,QAAQ,GAAG,KAAK,CAAC,0BAA0B,CAAC;IAClD,IAAI,CAAC,QAAQ,CAAC,oBAAoB;QAChC,OAAO,kBAAkB,CAAC,KAAK,CAAC,WAAW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B,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC1D,OAAO;QACL,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,IAAI;QACJ,yBAAyB,EACvB,MAAM,oCAAoC,CAAC,QAAQ,CAAC;KACvD,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeUserIdentityBundleFingerprint,\n KeyingVerificationError,\n type PrincipalHistorySigner,\n type PrincipalProjectionMember,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../keyingProjectionVerification/dependencyUnavailable\";\nimport type {\n StagedUserIdentityOptions,\n StagedUserIdentityResolver,\n TrustedUserIdentityResolver,\n} from \"../trustedUserIdentity\";\n\n/**\n * Structural verification only: never recurse into roster admission here.\n * Pass `authenticated` only once every projection's signed state verified.\n * Before that, a member seen for the first time is compared but not pinned,\n * so neither a forged projection nor a refused candidate reaches the store.\n */\nexport async function assertPrincipalIdentityCommitments(input: {\n readonly authenticated: boolean;\n readonly projections: readonly (readonly PrincipalProjectionMember[])[];\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The calling operation's lifetime, checked inside every pin write. */\n readonly assertCurrent?: (() => void) | undefined;\n}): Promise<void> {\n const resolver = input.resolveTrustedUserIdentity;\n if (!resolver.withPinnedIdentities)\n return compareCommitments(input.projections, resolver);\n return resolver.withPinnedIdentities(\n [\n ...new Set(\n input.projections.flatMap((projection) =>\n projection.map((member) => member.userId),\n ),\n ),\n ],\n (resolve) => compareCommitments(input.projections, resolve),\n { publish: input.authenticated, assertCurrent: input.assertCurrent },\n );\n}\n\ninterface PolicyIdentities {\n readonly signerUserIds: readonly string[];\n readonly projections: readonly (readonly PrincipalProjectionMember[])[];\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\n/** One staged scope over a policy's signers and committed members. */\nfunction withPolicyIdentities<T>(\n input: PolicyIdentities,\n resolveSigners: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n): Promise<T> {\n const check = async (resolve: StagedUserIdentityResolver) => {\n const signers = await resolveSigners(resolve);\n await compareCommitments(input.projections, resolve);\n return signers;\n };\n const resolver = input.resolveTrustedUserIdentity;\n if (!resolver.withPinnedIdentities) return check(resolver);\n return resolver.withPinnedIdentities(\n [\n ...new Set([\n ...input.signerUserIds,\n ...input.projections.flatMap((projection) =>\n projection.map((member) => member.userId),\n ),\n ]),\n ],\n check,\n options,\n );\n}\n\n/**\n * Resolve a policy's signers and compare its members' commitments before any\n * signature is checked, pinning nothing: a signer or member seen for the\n * first time stays staged, so a refused bundle leaves no durable pin to block\n * a corrected retry or the honest identity link. Existing pins are used as\n * they are. Callers pin first sights with `publishVerifiedPolicyIdentities`\n * once their own verification succeeds.\n */\nexport function withUnauthenticatedPolicyIdentities<T>(\n input: PolicyIdentities,\n resolveSigners: (resolve: StagedUserIdentityResolver) => Promise<T>,\n): Promise<T> {\n return withPolicyIdentities(input, resolveSigners, { publish: false });\n}\n\n/**\n * Pin a verified policy's signers and committed members, after the caller's\n * own verification of exactly these states and projections succeeded. The\n * answers are resolved again (existing pins as stored) and every signer's\n * signed fingerprint and committed bundle rechecked, so an answer changed\n * since verification is refused rather than pinned. A later substituted\n * answer then conflicts with this pin instead of becoming one.\n */\nasync function publishVerifiedPolicyIdentities(input: {\n readonly signers: readonly {\n readonly userId: string;\n readonly signingKeyFingerprint: string;\n }[];\n readonly projections: readonly (readonly PrincipalProjectionMember[])[];\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly assertCurrent?: (() => void) | undefined;\n}): Promise<void> {\n // Without staging, ordinary resolution already pinned every first sight.\n if (!input.resolveTrustedUserIdentity.withPinnedIdentities) return;\n await withPolicyIdentities(\n {\n signerUserIds: input.signers.map((signer) => signer.userId),\n projections: input.projections,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n },\n async (resolve) => {\n for (const signer of input.signers) {\n const identity = await resolve(signer.userId);\n if (!identity)\n throw new ProjectionDependencyUnavailableError(\n `Principal policy signer identity is unavailable: ${signer.userId}`,\n );\n if (identity.signingKeyFingerprint !== signer.signingKeyFingerprint)\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"Principal policy signer identity changed after verification\",\n );\n }\n },\n { publish: true, assertCurrent: input.assertCurrent },\n );\n}\n\n/**\n * Check every projection a verified selection hands to authorization, on\n * fresh and restored history alike: a restored prefix reads no page, so this\n * is the only commitment check its members get. Selections are already\n * signature-verified, so their members' first sights are published.\n */\nexport function assertSelectedPolicyCommitments(\n policies: readonly {\n readonly projection: readonly PrincipalProjectionMember[];\n readonly retainedHistory: readonly {\n readonly projection: readonly PrincipalProjectionMember[];\n }[];\n }[],\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n assertCurrent: () => void,\n): Promise<void> {\n return assertPrincipalIdentityCommitments({\n assertCurrent,\n authenticated: true,\n projections: policies.flatMap((policy) => [\n policy.projection,\n ...policy.retainedHistory.map((entry) => entry.projection),\n ]),\n resolveTrustedUserIdentity,\n });\n}\n\n/** Pin a bundle the caller just verified: every state's signer and projection. */\nexport function publishVerifiedPolicyBundle(\n bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n assertCurrent?: () => void,\n): Promise<void> {\n const entries = [\n ...bundle.previousStates,\n { state: bundle.currentState, projection: bundle.currentProjection },\n ];\n return publishVerifiedPolicyIdentities({\n signers: entries.map(({ state }) => ({\n userId: state.signerUserId,\n signingKeyFingerprint: state.signerUserKeyFingerprint,\n })),\n projections: entries.map((entry) => entry.projection),\n resolveTrustedUserIdentity,\n assertCurrent,\n });\n}\n\n/**\n * Pin the signers a history verifier accepted through its expected head,\n * rechecking each signed fingerprint and every committed bundle, within the\n * recovery's lifetime. The verifier records them in its sealed progress, so a\n * resumed recovery pins the signers of pages an earlier run accepted. Pages\n * pin nothing themselves: until the head connects, a forged prefix could\n * otherwise pin a substituted signer.\n */\nexport function publishAuthenticatedSigners(\n signers: readonly PrincipalHistorySigner[],\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n assertCurrent: () => void,\n): Promise<void> {\n if (signers.length === 0) return Promise.resolve();\n return publishVerifiedPolicyIdentities({\n signers,\n projections: [\n signers.flatMap((signer) =>\n signer.identityBundleFingerprint === null\n ? []\n : [\n {\n userId: signer.userId,\n role: \"member\" as const,\n identityBundleFingerprint: signer.identityBundleFingerprint,\n },\n ],\n ),\n ],\n resolveTrustedUserIdentity,\n assertCurrent,\n });\n}\n\nasync function compareCommitments(\n projections: readonly (readonly PrincipalProjectionMember[])[],\n resolve: StagedUserIdentityResolver,\n): Promise<void> {\n const identities = new Map<string, Promise<string>>();\n for (const projection of projections) {\n for (const member of projection) {\n let fingerprint = identities.get(member.userId);\n if (!fingerprint) {\n fingerprint = (async () => {\n const identity = await resolve(member.userId);\n if (!identity)\n throw new ProjectionDependencyUnavailableError(\n `Principal member identity is unavailable: ${member.userId}`,\n );\n if (identity.userId !== member.userId)\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Principal member identity has the wrong user\",\n );\n return computeUserIdentityBundleFingerprint(identity);\n })();\n identities.set(member.userId, fingerprint);\n }\n if ((await fingerprint) !== member.identityBundleFingerprint)\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `Principal member identity bundle mismatch: ${member.userId}`,\n );\n }\n }\n}\n\nexport async function createPrincipalProjectionMember(\n identity: {\n readonly userId: string;\n readonly identityTrustDomain: string;\n readonly signingPublicKey: Uint8Array;\n readonly encapsulationPublicKey: Uint8Array;\n },\n role: \"member\" | \"admin\",\n): Promise<PrincipalProjectionMember> {\n if (!identity.identityTrustDomain)\n throw new Error(\"Identity trust domain is unavailable\");\n return {\n userId: identity.userId,\n role,\n identityBundleFingerprint:\n await computeUserIdentityBundleFingerprint(identity),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalIdent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C;gBACL,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;YAC7C,CAAC;YACD,IAAI,CAAC,MAAM,WAAW,CAAC,KAAK,MAAM,CAAC,yBAAyB;gBAC1D,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,8CAA8C,MAAM,CAAC,MAAM,EAAE,CAC9D,CAAC;QACN,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,QAKC,EACD,IAAwB;IAExB,IAAI,CAAC,QAAQ,CAAC,mBAAmB;QAC/B,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC1D,OAAO;QACL,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,IAAI;QACJ,yBAAyB,EACvB,MAAM,oCAAoC,CAAC,QAAQ,CAAC;KACvD,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeUserIdentityBundleFingerprint,\n KeyingVerificationError,\n type PrincipalHistorySigner,\n type PrincipalProjectionMember,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../shared/dependencyUnavailable\";\nimport type {\n StagedUserIdentityOptions,\n StagedUserIdentityResolver,\n TrustedUserIdentityResolver,\n} from \"../trustedUserIdentity\";\n\n/**\n * Structural verification only: never recurse into roster admission here.\n * Pass `authenticated` only once every projection's signed state verified.\n * Before that, a member seen for the first time is compared but not pinned,\n * so neither a forged projection nor a refused candidate reaches the store.\n */\nexport async function assertPrincipalIdentityCommitments(input: {\n readonly authenticated: boolean;\n readonly projections: readonly (readonly PrincipalProjectionMember[])[];\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The calling operation's lifetime, checked inside every pin write. */\n readonly assertCurrent?: (() => void) | undefined;\n}): Promise<void> {\n const resolver = input.resolveTrustedUserIdentity;\n if (!resolver.withPinnedIdentities)\n return compareCommitments(input.projections, resolver);\n return resolver.withPinnedIdentities(\n [\n ...new Set(\n input.projections.flatMap((projection) =>\n projection.map((member) => member.userId),\n ),\n ),\n ],\n (resolve) => compareCommitments(input.projections, resolve),\n { publish: input.authenticated, assertCurrent: input.assertCurrent },\n );\n}\n\ninterface PolicyIdentities {\n readonly signerUserIds: readonly string[];\n readonly projections: readonly (readonly PrincipalProjectionMember[])[];\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\n/** One staged scope over a policy's signers and committed members. */\nfunction withPolicyIdentities<T>(\n input: PolicyIdentities,\n resolveSigners: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n): Promise<T> {\n const check = async (resolve: StagedUserIdentityResolver) => {\n const signers = await resolveSigners(resolve);\n await compareCommitments(input.projections, resolve);\n return signers;\n };\n const resolver = input.resolveTrustedUserIdentity;\n if (!resolver.withPinnedIdentities) return check(resolver);\n return resolver.withPinnedIdentities(\n [\n ...new Set([\n ...input.signerUserIds,\n ...input.projections.flatMap((projection) =>\n projection.map((member) => member.userId),\n ),\n ]),\n ],\n check,\n options,\n );\n}\n\n/**\n * Resolve a policy's signers and compare its members' commitments before any\n * signature is checked, pinning nothing: a signer or member seen for the\n * first time stays staged, so a refused bundle leaves no durable pin to block\n * a corrected retry or the honest identity link. Existing pins are used as\n * they are. Callers pin first sights with `publishVerifiedPolicyIdentities`\n * once their own verification succeeds.\n */\nexport function withUnauthenticatedPolicyIdentities<T>(\n input: PolicyIdentities,\n resolveSigners: (resolve: StagedUserIdentityResolver) => Promise<T>,\n): Promise<T> {\n return withPolicyIdentities(input, resolveSigners, { publish: false });\n}\n\n/**\n * Pin a verified policy's signers and committed members, after the caller's\n * own verification of exactly these states and projections succeeded. The\n * answers are resolved again (existing pins as stored) and every signer's\n * signed fingerprint and committed bundle rechecked, so an answer changed\n * since verification is refused rather than pinned. A later substituted\n * answer then conflicts with this pin instead of becoming one.\n */\nasync function publishVerifiedPolicyIdentities(input: {\n readonly signers: readonly {\n readonly userId: string;\n readonly signingKeyFingerprint: string;\n }[];\n readonly projections: readonly (readonly PrincipalProjectionMember[])[];\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly assertCurrent?: (() => void) | undefined;\n}): Promise<void> {\n // Without staging, ordinary resolution already pinned every first sight.\n if (!input.resolveTrustedUserIdentity.withPinnedIdentities) return;\n await withPolicyIdentities(\n {\n signerUserIds: input.signers.map((signer) => signer.userId),\n projections: input.projections,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n },\n async (resolve) => {\n for (const signer of input.signers) {\n const identity = await resolve(signer.userId);\n if (!identity)\n throw new ProjectionDependencyUnavailableError(\n `Principal policy signer identity is unavailable: ${signer.userId}`,\n );\n if (identity.signingKeyFingerprint !== signer.signingKeyFingerprint)\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"Principal policy signer identity changed after verification\",\n );\n }\n },\n { publish: true, assertCurrent: input.assertCurrent },\n );\n}\n\n/**\n * Check every projection a verified selection hands to authorization, on\n * fresh and restored history alike: a restored prefix reads no page, so this\n * is the only commitment check its members get. Selections are already\n * signature-verified, so their members' first sights are published.\n */\nexport function assertSelectedPolicyCommitments(\n policies: readonly {\n readonly projection: readonly PrincipalProjectionMember[];\n readonly retainedHistory: readonly {\n readonly projection: readonly PrincipalProjectionMember[];\n }[];\n }[],\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n assertCurrent: () => void,\n): Promise<void> {\n return assertPrincipalIdentityCommitments({\n assertCurrent,\n authenticated: true,\n projections: policies.flatMap((policy) => [\n policy.projection,\n ...policy.retainedHistory.map((entry) => entry.projection),\n ]),\n resolveTrustedUserIdentity,\n });\n}\n\n/** Pin a bundle the caller just verified: every state's signer and projection. */\nexport function publishVerifiedPolicyBundle(\n bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n assertCurrent?: () => void,\n): Promise<void> {\n const entries = [\n ...bundle.previousStates,\n { state: bundle.currentState, projection: bundle.currentProjection },\n ];\n return publishVerifiedPolicyIdentities({\n signers: entries.map(({ state }) => ({\n userId: state.signerUserId,\n signingKeyFingerprint: state.signerUserKeyFingerprint,\n })),\n projections: entries.map((entry) => entry.projection),\n resolveTrustedUserIdentity,\n assertCurrent,\n });\n}\n\n/**\n * Pin the signers a history verifier accepted through its expected head,\n * rechecking each signed fingerprint and every committed bundle, within the\n * recovery's lifetime. The verifier records them in its sealed progress, so a\n * resumed recovery pins the signers of pages an earlier run accepted. Pages\n * pin nothing themselves: until the head connects, a forged prefix could\n * otherwise pin a substituted signer.\n */\nexport function publishAuthenticatedSigners(\n signers: readonly PrincipalHistorySigner[],\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n assertCurrent: () => void,\n): Promise<void> {\n if (signers.length === 0) return Promise.resolve();\n return publishVerifiedPolicyIdentities({\n signers,\n projections: [\n signers.flatMap((signer) =>\n signer.identityBundleFingerprint === null\n ? []\n : [\n {\n userId: signer.userId,\n role: \"member\" as const,\n identityBundleFingerprint: signer.identityBundleFingerprint,\n },\n ],\n ),\n ],\n resolveTrustedUserIdentity,\n assertCurrent,\n });\n}\n\nasync function compareCommitments(\n projections: readonly (readonly PrincipalProjectionMember[])[],\n resolve: StagedUserIdentityResolver,\n): Promise<void> {\n const identities = new Map<string, Promise<string>>();\n for (const projection of projections) {\n for (const member of projection) {\n let fingerprint = identities.get(member.userId);\n if (!fingerprint) {\n fingerprint = (async () => {\n const identity = await resolve(member.userId);\n if (!identity)\n throw new ProjectionDependencyUnavailableError(\n `Principal member identity is unavailable: ${member.userId}`,\n );\n if (identity.userId !== member.userId)\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Principal member identity has the wrong user\",\n );\n return computeUserIdentityBundleFingerprint(identity);\n })();\n identities.set(member.userId, fingerprint);\n }\n if ((await fingerprint) !== member.identityBundleFingerprint)\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `Principal member identity bundle mismatch: ${member.userId}`,\n );\n }\n }\n}\n\nexport async function createPrincipalProjectionMember(\n identity: {\n readonly userId: string;\n readonly identityTrustDomain: string;\n readonly signingPublicKey: Uint8Array;\n readonly encapsulationPublicKey: Uint8Array;\n },\n role: \"member\" | \"admin\",\n): Promise<PrincipalProjectionMember> {\n if (!identity.identityTrustDomain)\n throw new Error(\"Identity trust domain is unavailable\");\n return {\n userId: identity.userId,\n role,\n identityBundleFingerprint:\n await computeUserIdentityBundleFingerprint(identity),\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "../
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../shared/dependencyUnavailable.js";
|
|
3
3
|
/**
|
|
4
4
|
* The sole SDK adapter allowed to consume the raw user-identity endpoint.
|
|
5
5
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiAdapter.js","sourceRoot":"","sources":["apiAdapter.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"apiAdapter.js","sourceRoot":"","sources":["apiAdapter.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,iCAAiC,CAAC;AAGvF;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B,CACzC,SAGC;IAED,OAAO;QACL,UAAU,CAAC,MAAM;YACf,SAAS,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;QACtC,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,MAAM;YACf,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;YACzD,IAAI,QAAQ,EAAE,CAAC;gBACb,OAAO,QAAQ,CAAC;YAClB,CAAC;YAED,MAAM,OAAO,GAAG,SAAS,CAAC,6BAA6B,CAAC,MAAM,CAAC,CAAC;YAChE,IAAI,OAAO,EAAE,IAAI,KAAK,MAAM,IAAI,OAAO,EAAE,IAAI,KAAK,OAAO,EAAE,CAAC;gBAC1D,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,kDAAkD,MAAM,EAAE,CAC3D,CAAC;YACJ,CAAC;YACD,IAAI,OAAO,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,MAAM,KAAK,GAAG,CAAC,EAAE,CAAC;gBACpE,MAAM,IAAI,oCAAoC,CAC5C,4BAA4B,MAAM,oBAAoB,OAAO,CAAC,OAAO,EAAE,CACxE,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../shared/dependencyUnavailable\";\nimport type { RemoteUserIdentitySource } from \"./types\";\n\n/**\n * The sole SDK adapter allowed to consume the raw user-identity endpoint.\n *\n * A null identity has two very different causes and callers must not conflate\n * them: a coded 404 is the server asserting that no such user exists, which is\n * integrity evidence once a signed artifact cites that user, whereas a fetch\n * failure or any other HTTP failure says nothing about the user at all. Only\n * the first stays `null`; the second is a retryable availability error.\n */\nexport function createApiUserIdentitySource(\n apiClient: Pick<\n ApiClient,\n \"evictUserIdentity\" | \"getUserIdentity\" | \"getUserIdentityRequestFailure\"\n >,\n): RemoteUserIdentitySource {\n return {\n invalidate(userId) {\n apiClient.evictUserIdentity(userId);\n },\n async load(userId) {\n const identity = await apiClient.getUserIdentity(userId);\n if (identity) {\n return identity;\n }\n\n const failure = apiClient.getUserIdentityRequestFailure(userId);\n if (failure?.kind === \"json\" || failure?.kind === \"shape\") {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Remote user identity response is malformed for ${userId}`,\n );\n }\n if (failure && !(failure.kind === \"http\" && failure.status === 404)) {\n throw new ProjectionDependencyUnavailableError(\n `Remote user identity for ${userId} is unavailable: ${failure.message}`,\n );\n }\n return null;\n },\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
2
1
|
import { isKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
3
3
|
import { decryptDocumentAttachmentBlob } from "../hydration/decrypt.js";
|
|
4
4
|
/**
|
|
5
5
|
* Proof material the cached projection lacks, such as a wrap-cited container
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentDecryptor.js","sourceRoot":"","sources":["attachmentDecryptor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"attachmentDecryptor.js","sourceRoot":"","sources":["attachmentDecryptor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,kDAAkD,CAAC;AAC7F,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAClG,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AASrE;;;GAGG;AACH,SAAS,4BAA4B,CAAC,KAAc;IAClD,OAAO,CACL,KAAK,YAAY,oCAAoC;QACrD,CAAC,yBAAyB,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC,CAC1E,CAAC;AACJ,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,2BAA2B,CAIzC,SAAkC,EAClC,UAAkB,EAClB,IAAuC;IAEvC,IAAI,SAAuE,CAAC;IAC5E,MAAM,OAAO,GAAG,GAAG,EAAE;QACnB,SAAS,KAAK,CAAC,KAAK,IAAI,EAAE;YACxB,SAAS,CAAC,6BAA6B,EAAE,CAAC,UAAU,CAAC,CAAC;YACtD,OAAO,SAAS,CAAC,2BAA2B,CAAC,UAAU,CAAC,CAAC;QAC3D,CAAC,CAAC,EAAE,CAAC;QACL,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;IACF,OAAO,KAAK,EAAE,KAAY,EAAE,EAAE;QAC5B,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC;QAC3B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,4BAA4B,CAAC,KAAK,CAAC;gBAAE,MAAM,KAAK,CAAC;YACtD,MAAM,gBAAgB,GAAG,MAAM,OAAO,EAAE,CAAC;YACzC,IAAI,CAAC,gBAAgB;gBAAE,MAAM,KAAK,CAAC;YACnC,yEAAyE;YACzE,wEAAwE;YACxE,OAAO,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,gBAAgB,EAAE,CAAC,CAAC;QAC9C,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,SAAkC,EAClC,UAAkB;IAElB,OAAO,2BAA2B,CAChC,SAAS,EACT,UAAU,EACV,6BAA6B,CAC9B,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { isKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { decryptDocumentAttachmentBlob } from \"../hydration/decrypt\";\n\ninterface AttachmentProjectionApi {\n evictDocumentWriterProjection?(documentId: string): void;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n}\n\n/**\n * Proof material the cached projection lacks, such as a wrap-cited container\n * manifest that a fresher projection serves. Not integrity evidence.\n */\nfunction isRefreshableProofDependency(error: unknown): boolean {\n return (\n error instanceof ProjectionDependencyUnavailableError ||\n (isKeyingVerificationError(error) && error.code === \"missing_dependency\")\n );\n}\n\n/** One fresh proof fetch shared by a hydration or key-rewrap run. */\nexport function createAttachmentProofReader<\n Input extends { writerProjection: DocumentWriterProjectionResponse },\n Result,\n>(\n apiClient: AttachmentProjectionApi,\n documentId: string,\n read: (input: Input) => Promise<Result>,\n) {\n let refreshed: Promise<DocumentWriterProjectionResponse | null> | undefined;\n const refresh = () => {\n refreshed ??= (async () => {\n apiClient.evictDocumentWriterProjection?.(documentId);\n return apiClient.getDocumentWriterProjection(documentId);\n })();\n return refreshed;\n };\n return async (input: Input) => {\n try {\n return await read(input);\n } catch (error) {\n if (!isRefreshableProofDependency(error)) throw error;\n const writerProjection = await refresh();\n if (!writerProjection) throw error;\n // Retry the same binding and ciphertext with fully verified fresh proof.\n // A second missing dependency escapes; it cannot trigger another fetch.\n return read({ ...input, writerProjection });\n }\n };\n}\n\nexport function createAttachmentDecryptor(\n apiClient: AttachmentProjectionApi,\n documentId: string,\n) {\n return createAttachmentProofReader(\n apiClient,\n documentId,\n decryptDocumentAttachmentBlob,\n );\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
3
3
|
/** A retained wrap must name a KEK committed by verified container history. */
|
|
4
4
|
export function assertBlobWrapScopeVerified(input) {
|
|
5
5
|
const targets = input.binding.contentKeyBundle.targets.filter((target) => target.bindingId === input.binding.bindingId &&
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifiedWrapScope.js","sourceRoot":"","sources":["verifiedWrapScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAG5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"verifiedWrapScope.js","sourceRoot":"","sources":["verifiedWrapScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAG5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,+EAA+E;AAC/E,MAAM,UAAU,2BAA2B,CAAC,KAI3C;IACC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,gBAAgB,CAAC,OAAO,CAAC,MAAM,CAC3D,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,SAAS,KAAK,KAAK,CAAC,OAAO,CAAC,SAAS;QAC5C,MAAM,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU,CACzC,CAAC;IACF,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QACtB,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,yCAAyC,CAC1C,CAAC;IACJ,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,IAAI,GAAG,KAAK,CAAC,aAAa,CAAC,2BAA2B,CAAC,GAAG,CAC9D,MAAM,CAAC,qBAAqB,CAC7B,CAAC;QACF,MAAM,QAAQ,GAAG,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9B,IAAI,CAAC,QAAQ;YACX,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,CAC9C,CAAC;QACJ,IACE,QAAQ,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW;YACjD,QAAQ,CAAC,KAAK,CAAC,mBAAmB,KAAK,MAAM,CAAC,mBAAmB,EACjE,CAAC;YACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6DAA6D,CAC9D,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { BlobAttachmentSummary } from \"@tearleads/validators/response\";\nimport type { DocumentWriterProjectionAuthorization } from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\n\n/** A retained wrap must name a KEK committed by verified container history. */\nexport function assertBlobWrapScopeVerified(input: {\n authorization: DocumentWriterProjectionAuthorization;\n binding: BlobAttachmentSummary;\n documentId: string;\n}): void {\n const targets = input.binding.contentKeyBundle.targets.filter(\n (target) =>\n target.bindingId === input.binding.bindingId &&\n target.documentId === input.documentId,\n );\n if (targets.length === 0)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Blob bundle lacks its attachment target\",\n );\n for (const target of targets) {\n const path = input.authorization.containerPathByManifestHash.get(\n target.containerManifestHash,\n );\n const manifest = path?.at(-1);\n if (!manifest)\n throw new ProjectionDependencyUnavailableError(\n \"Blob wrapped-target manifest is unavailable\",\n );\n if (\n manifest.state.containerId !== target.containerId ||\n manifest.state.containerKeyEpochId !== target.containerKeyEpochId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Blob wrapped target differs from verified container history\",\n );\n }\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../../../data/
|
|
1
|
+
import { ProjectionDependencyUnavailableError } from "../../../../data/shared/dependencyUnavailable.js";
|
|
2
2
|
import { buildMaterializedContainerCreatePlan, childContainerWriterProjectionFromCreatePlan, } from "../../../containers/index.js";
|
|
3
3
|
import { buildMaterializedDocumentCreatePlan, } from "../../../documents/index.js";
|
|
4
4
|
/** A folder's metadata document takes the folder's id, known before the create. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createWithMetadataPlan.js","sourceRoot":"","sources":["createWithMetadataPlan.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"createWithMetadataPlan.js","sourceRoot":"","sources":["createWithMetadataPlan.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM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AAgB,CAAC,cAAc,EACzE,CAAC;QACD,MAAM,IAAI,KAAK,CACb,0EAA0E,CAC3E,CAAC;IACJ,CAAC;IACD,OAAO,UAAU,CAAC,EAAE,GAAG,KAAK,EAAE,gBAAgB,EAAE,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../../data/persistence/documents/records\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/shared/dependencyUnavailable\";\nimport {\n buildMaterializedContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n} from \"../../../containers\";\nimport {\n buildMaterializedDocumentCreatePlan,\n type resolveDocumentCreateAuthor,\n} from \"../../../documents\";\n\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\nexport interface ContainerWithMetadataPlanInput {\n readonly author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n readonly containerEventId: string;\n readonly containerId: string;\n readonly containerKey: Uint8Array;\n readonly containerSignedAt: string;\n readonly metadataContentKey: Uint8Array;\n readonly metadataEventId: string;\n /** The queued update holding the metadata document's whole content. */\n readonly metadataSeedUpdate?: PendingUpdateRecord | undefined;\n readonly metadataSignedAt: string;\n readonly parentProjection: ContainerWriterProjectionResponse;\n readonly parentSecretKey: Uint8Array;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly runtime: ContainerWorkflowRuntime;\n readonly systemSlot?: ContainerSystemSlot | null | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/** A folder's metadata document takes the folder's id, known before the create. */\nexport function plannedContainerMetadataDocumentId(\n containerId: string,\n): string {\n return containerId;\n}\n\nasync function buildPlans(input: ContainerWithMetadataPlanInput) {\n const execSql = input.runtime.infra.execSql;\n // Rebuild parent- and policy-dependent hashes, signatures, and wraps on every\n // attempt while retaining the logical mutation identities and key material.\n const containerPlan = await buildMaterializedContainerCreatePlan({\n author: input.author,\n containerId: input.containerId,\n containerKey: input.containerKey,\n execSql,\n eventId: input.containerEventId,\n metadataDocumentId: plannedContainerMetadataDocumentId(input.containerId),\n systemSlot: input.systemSlot,\n parentProjection: input.parentProjection,\n parentSecretKey: input.parentSecretKey,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.containerSignedAt,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n const childProjection = childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.parentProjection,\n });\n const metadataDocumentPlan = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: childProjection,\n contentKey: input.metadataContentKey,\n documentId: containerPlan.plan.metadataDocumentId,\n eventId: input.metadataEventId,\n execSql,\n knownContainerKeks: new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]),\n signedAt: input.metadataSignedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.parentSecretKey,\n trustedLocalProjection: true,\n });\n return { containerPlan, childProjection, metadataDocumentPlan };\n}\n\n/** Refresh stale history evidence once, strictly before submitting the write. */\nexport async function buildContainerWithMetadataPlans(\n input: ContainerWithMetadataPlanInput,\n) {\n try {\n return await buildPlans(input);\n } catch (error) {\n if (!(error instanceof ProjectionDependencyUnavailableError)) throw error;\n }\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input.runtime;\n const parentId = input.parentProjection.containerId;\n apiClient.evictContainerWriterProjection(parentId);\n const parentProjection =\n await apiClient.getContainerWriterProjection(parentId);\n if (!parentProjection || input.stillCurrent?.() === false) return null;\n if (\n parentProjection.containerId !== parentId ||\n parentProjection.organizationId !== input.parentProjection.organizationId\n ) {\n throw new Error(\n \"Refreshed parent projection belongs to another container or organization\",\n );\n }\n return buildPlans({ ...input, parentProjection });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { isContainerNotFoundFailure } from "../../../data/containers/shared/mutationFailures.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
3
3
|
import { errorMessage } from "../../../data/shared/errorMessage.js";
|
|
4
4
|
import { ContainerMutationService, signedContainerMetadataDocumentId, signedContainerReferencedPrincipalHeads, } from "../../containers/index.js";
|
|
5
5
|
import { resolveDocumentCreateAuthor } from "../../documents/index.js";
|