@tearleads/client-sdk 0.1.219 → 0.1.221
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 +2 -2
- 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 +2 -2
- 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/sync/syncCoordinator.d.ts +1 -1
- package/data/sync/syncCoordinator.js +1 -1
- package/data/sync/syncCoordinator.js.map +1 -1
- package/data/trustedUserIdentity/apiAdapter.js +1 -1
- package/data/trustedUserIdentity/apiAdapter.js.map +1 -1
- package/data/trustedUserIdentity/pinnedResolution.js +1 -1
- package/data/trustedUserIdentity/pinnedResolution.js.map +1 -1
- package/data/trustedUserIdentity/service.js +1 -1
- package/data/trustedUserIdentity/service.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/documentLinks/index.js +1 -1
- package/workflows/container-contents/documentLinks/index.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/documents/writerKeys.js +1 -1
- package/workflows/documents/writerKeys.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/{sync → sqlite/availability}/databaseUnavailable.d.ts +0 -0
- /package/data/{sync → sqlite/availability}/databaseUnavailable.js +0 -0
- /package/data/{sync → sqlite/availability}/databaseUnavailable.js.map +0 -0
package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;AAC1G,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EACL,gDAAgD,EAChD,yCAAyC,GAC1C,MAAM,uEAAuE,CAAC;AAC/E,OAAO,EAAE,+BAA+B,EAAE,MAAM,mEAAmE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,iCAAiC,EAAE,MAAM,oDAAoD,CAAC;AACvG,OAAO,EACL,2BAA2B,GAE5B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/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AAC,CAAC;gBAClD,MAAM,2BAA2B,CAC/B;oBACE,GAAG,KAAK,CAAC,OAAO;oBAChB,QAAQ,EAAE,EAAE;oBACZ,iEAAiE;oBACjE,iEAAiE;oBACjE,qBAAqB,EAAE,EAAE;iBAC1B,EACD;oBACE,uBAAuB;oBACvB,OAAO;iBACR,CACF,CAAC;YACJ,CAAC;QACH,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACJ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC1B,IAAI,KAAK,YAAY,gDAAgD;YACnE,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,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;AAC1G,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EACL,gDAAgD,EAChD,yCAAyC,GAC1C,MAAM,uEAAuE,CAAC;AAC/E,OAAO,EAAE,+BAA+B,EAAE,MAAM,mEAAmE,CAAC;AACpH,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAC1F,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,iCAAiC,EAAE,MAAM,oDAAoD,CAAC;AACvG,OAAO,EACL,2BAA2B,GAE5B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AAWvF,iFAAiF;AACjF,KAAK,UAAU,qBAAqB,CAAC,KAA2B;IAC9D,MAAM,OAAO,GAA+C,EAAE,CAAC;I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AAE,EAAE;iBAC1B,EACD;oBACE,uBAAuB;oBACvB,OAAO;iBACR,CACF,CAAC;YACJ,CAAC;QACH,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACJ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC1B,IAAI,KAAK,YAAY,gDAAgD;YACnE,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,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 { 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,0CAA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KAAK,CAAC;IACvC,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 {\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,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,CAAC,eAAe,CAAC;IAC/D,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,MAAM,IAAI,oCAAoC,CAC5C,mEAAmE,CACpE,CAAC;IACJ,CAAC;IACD,IACE,eAAe,CAAC,KAAK,KAAK,QAAQ,CAAC,KAAK;QACxC,eAAe,CAAC,YAAY,KAAK,KAAK,CAAC,MAAM,CAAC,YAAY,EAC1D,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,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BAA4B,CAAC,MAAM,GAAG,CAAC;QACnD,CAAC,KAAK,CAAC,uBAAuB,IAAI,CAAC,YAAY,CAAC,EAChD,CAAC;QACD,OAAO,sCAAsC,CAAC,KAAK,CAAC,CAAC;IACvD,CAAC;IACD,MAAM,QAAQ,GAAG,MAAM,6BAA6B,CAAC;QACnD,GAAG,CAAC,sBAAsB,IAAI,EAAE,CAAC;QACjC,oBAAoB,EAAE,KAAK,CAAC,KAAK,CAAC,gBAAgB,CAAC,YAAY;QAC/D,QAAQ;QACR,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,gBAAgB,CAAC,KAAK;KAC1C,CAAC,CAAC;IACH,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,MAAM,QAAQ,CAAC,KAAK,CAAC;IACvC,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
|
-
import { isDatabaseUnavailableError } from "../
|
|
4
|
-
import { ProjectionDependencyUnavailableError } from "./dependencyUnavailable.js";
|
|
4
|
+
import { isDatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.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,E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BAA4B,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 \"../sqlite/availability/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,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAG1F;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAAC,KAI5D;IACC,MAAM,MAAM,GAAG,2BAA2B,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACzD,yEAAyE;IACzE,OAAO,mCAAmC,CACxC;QACE,aAAa,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,CAAC;QACxD,WAAW,EAAE;YACX,GAAG,KAAK,CAAC,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC;YAC/D,KAAK,CAAC,MAAM,CAAC,iBAAiB;SAC/B;QACD,0BAA0B,EAAE,KAAK,CAAC,cAAc;KACjD,EACD,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,MAAM,OAAO,GAAG,IAAI,GAAG,EAA0C,CAAC;QAClE,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YAC3B,MAAM,QAAQ,GAAG,GAAG,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,wBAAwB,EAAE,CAAC;YAC3E,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;gBAAE,SAAS;YACpC,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACpD,IAAI,CAAC,SAAS,EAAE,CAAC;gBACf,MAAM,IAAI,oCAAoC,CAC5C,GAAG,KAAK,CAAC,KAAK,yCAAyC,KAAK,CAAC,YAAY,EAAE,CAC5E,CAAC;YACJ,CAAC;YACD,MAAM,qBAAqB,GAAG,MAAM,aAAa,CAC/C,SAAS,CAAC,gBAAgB,CAC3B,CAAC;YACF,IAAI,qBAAqB,KAAK,KAAK,CAAC,wBAAwB,EAAE,CAAC;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,EAAE,QAAQ,CAAC,CAAC;IACzD,OAAO,QAAQ,CAAC,oBAAoB,CAClC;QACE,GAAG,IAAI,GAAG,CACR,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE,CACvC,UAAU,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAC1C,CACF;KACF,EACD,CAAC,OAAO,EAAE,EAAE,CAAC,kBAAkB,CAAC,KAAK,CAAC,WAAW,EAAE,OAAO,CAAC,EAC3D,EAAE,OAAO,EAAE,KAAK,CAAC,aAAa,EAAE,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE,CACrE,CAAC;AACJ,CAAC;AAQD,sEAAsE;AACtE,SAAS,oBAAoB,CAC3B,KAAuB,EACvB,cAAmE,EACnE,OAAkC;IAElC,MAAM,KAAK,GAAG,KAAK,EAAE,OAAmC,EAAE,EAAE;QAC1D,MAAM,OAAO,GAAG,MAAM,cAAc,CAAC,OAAO,CAAC,CAAC;QAC9C,MAAM,kBAAkB,CAAC,KAAK,CAAC,WAAW,EAAE,OAAO,CAA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AAM;wBACnC,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,8CAA8C,CAC/C,CAAC;oBACJ,OAAO,oCAAoC,CAAC,QAAQ,CAAC,CAAC;gBACxD,CAAC,CAAC,EAAE,CAAC;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 \"../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":"principalIdentityCommitments.js","sourceRoot":"","sources":["principalIdentityCommitments.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,iCAAiC,CAAC;AAOvF;;;;;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,EAAE,QAAQ,CAAC,CAAC;IACzD,OAAO,QAAQ,CAAC,oBAAoB,CAClC;QACE,GAAG,IAAI,GAAG,CACR,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE,CACvC,UAAU,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAC1C,CACF;KACF,EACD,CAAC,OAAO,EAAE,EAAE,CAAC,kBAAkB,CAAC,KAAK,CAAC,WAAW,E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,WAAW,GAAG,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAChD,IAAI,CAAC,WAAW,EAAE,CAAC;gBACjB,WAAW,GAAG,CAAC,KAAK,IAAI,EAAE;oBACxB,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;oBAC9C,IAAI,CAAC,QAAQ;wBACX,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,MAAM,CAAC,MAAM,EAAE,CAC7D,CAAC;oBACJ,IAAI,QAAQ,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM;wBACnC,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,8CAA8C,CAC/C,CAAC;oBACJ,OAAO,oCAAoC,CAAC,QAAQ,CAAC,CAAC;gBACxD,CAAC,CAAC,EAAE,CAAC;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"]}
|
|
@@ -3,8 +3,8 @@ import { type SyncIdleOptions } from "./coordinatorPump.js";
|
|
|
3
3
|
import type { SyncLane, SyncLaneConfig } from "./syncLaneConfig.js";
|
|
4
4
|
import type { DomainSyncSnapshot } from "./syncTelemetry.js";
|
|
5
5
|
import type { UploadSyncLane, UploadSyncLaneOptions } from "./uploadLane.js";
|
|
6
|
+
export { isDatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
|
|
6
7
|
export type { SyncIdleOptions } from "./coordinatorPump.js";
|
|
7
|
-
export { isDatabaseUnavailableError } from "./databaseUnavailable.js";
|
|
8
8
|
export type { SyncLane, SyncLaneConfig } from "./syncLaneConfig.js";
|
|
9
9
|
export { didRegainSyncPrerequisites, type SyncRuntimeStatus, } from "./syncPrerequisites.js";
|
|
10
10
|
export type { DomainSyncSnapshot, SyncLaneLastAction, SyncLanePhase, SyncLaneProgress, SyncLaneSnapshot, SyncLaneStatus, } from "./syncTelemetry.js";
|
|
@@ -6,7 +6,7 @@ import { beginUploadLane } from "./uploadLane.js";
|
|
|
6
6
|
// Re-exported here because lanes reach it as a shouldIgnoreError alongside the
|
|
7
7
|
// rest of the coordinator surface; it lives beside this coordinator with the
|
|
8
8
|
// error type it discriminates on.
|
|
9
|
-
export { isDatabaseUnavailableError } from "
|
|
9
|
+
export { isDatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
|
|
10
10
|
export { didRegainSyncPrerequisites, } from "./syncPrerequisites.js";
|
|
11
11
|
const coordinatorsByScope = new WeakMap();
|
|
12
12
|
function createSyncLaneHandle(coordinatorState, lane) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncCoordinator.js","sourceRoot":"","sources":["syncCoordinator.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,eAAe,EACf,oBAAoB,EAEpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,kBAAkB,EAClB,2BAA2B,EAC3B,8BAA8B,GAC/B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEhF,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAG/C,+EAA+E;AAC/E,6EAA6E;AAC7E,kCAAkC;AAClC,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAEnE,OAAO,EACL,0BAA0B,GAE3B,MAAM,qBAAqB,CAAC;AAgC7B,MA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AC,OAAO,CAAC;QAC1D,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CACtB,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../shared/domainScope\";\nimport {\n requestAllPumpDrivenLanes,\n requestLaneSync,\n requestLaneSyncAfter,\n type SyncIdleOptions,\n waitForIdleLanes,\n} from \"./coordinatorPump\";\nimport type {\n DomainSyncCoordinatorState,\n SyncLaneState,\n} from \"./coordinatorState\";\nimport {\n hasPendingLaneWork,\n INITIAL_SYNC_LANE_RUN_STATE,\n publishSyncCoordinatorSnapshot,\n} from \"./coordinatorState\";\nimport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nimport { transitionSyncLaneRequest } from \"./syncLaneMachine\";\nimport type { DomainSyncSnapshot } from \"./syncTelemetry\";\nimport { createDomainSyncSnapshot, createSyncTimestamp } from \"./syncTelemetry\";\nimport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\nimport { beginUploadLane } from \"./uploadLane\";\n\nexport type { SyncIdleOptions } from \"./coordinatorPump\";\n// Re-exported here because lanes reach it as a shouldIgnoreError alongside the\n// rest of the coordinator surface; it lives beside this coordinator with the\n// error type it discriminates on.\nexport { isDatabaseUnavailableError } from \"./databaseUnavailable\";\nexport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nexport {\n didRegainSyncPrerequisites,\n type SyncRuntimeStatus,\n} from \"./syncPrerequisites\";\nexport type {\n DomainSyncSnapshot,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./syncTelemetry\";\nexport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\n\nexport interface DomainSyncCoordinator {\n beginUploadLane: (\n key: string,\n options?: UploadSyncLaneOptions,\n ) => UploadSyncLane;\n // Drop queued work and refuse new runs; active callbacks retain ownership.\n dispose: () => void;\n getSnapshot: () => DomainSyncSnapshot;\n registerLane: (key: string, config: SyncLaneConfig) => SyncLane;\n // Re-request every pump-driven lane — a manual \"sync now\" that re-drives\n // durable owners stranded by a transient failure. Observational upload rows\n // are updated only by those owners' real attachment upload attempts.\n requestAllLanes: () => void;\n // Request one registered pump lane without re-driving unrelated owners.\n requestLane: (key: string) => void;\n hasPendingWork: () => boolean;\n isDisposed: () => boolean;\n subscribe: (listener: () => void) => () => void;\n waitForIdle: (options?: SyncIdleOptions) => Promise<boolean>;\n}\n\nconst coordinatorsByScope = new WeakMap<DomainScope, DomainSyncCoordinator>();\n\nfunction createSyncLaneHandle(\n coordinatorState: DomainSyncCoordinatorState,\n lane: SyncLaneState,\n): SyncLane {\n return {\n isDisposed: () => coordinatorState.disposed,\n requestSync: () => requestLaneSync(coordinatorState, lane),\n requestSyncAfter: (delayMs) =>\n requestLaneSyncAfter(coordinatorState, lane, delayMs),\n };\n}\n\nfunction createDomainSyncCoordinator(): DomainSyncCoordinator {\n const coordinatorState: DomainSyncCoordinatorState = {\n disposed: false,\n lanes: new Map<string, SyncLaneState>(),\n listeners: new Set(),\n nextRegistrationIndex: 0,\n nextRunOrder: 0,\n wakePump: null,\n pump: null,\n snapshot: createDomainSyncSnapshot({\n hasPendingWork: false,\n lanes: [],\n pumpActive: false,\n }),\n };\n\n return {\n beginUploadLane(key: string, options: UploadSyncLaneOptions = {}) {\n return beginUploadLane(coordinatorState, key, options);\n },\n dispose() {\n coordinatorState.disposed = true;\n // Drop queued work so waitForIdle reports settled immediately and a\n // lane left re-requested by an in-flight run does not survive teardown.\n for (const lane of coordinatorState.lanes.values()) {\n lane.request = transitionSyncLaneRequest(lane.request, {\n type: \"clear\",\n });\n }\n // Publish the final settled snapshot, then release listener closures:\n // the coordinator is dropped from the registry and a remount subscribes\n // to a fresh one.\n publishSyncCoordinatorSnapshot(coordinatorState);\n coordinatorState.listeners.clear();\n },\n getSnapshot() {\n return coordinatorState.snapshot;\n },\n hasPendingWork() {\n return (\n !!coordinatorState.pump ||\n hasPendingLaneWork(coordinatorState.lanes.values())\n );\n },\n isDisposed() {\n return coordinatorState.disposed;\n },\n registerLane(key: string, config: SyncLaneConfig): SyncLane {\n const existingLane = coordinatorState.lanes.get(key);\n if (existingLane) {\n existingLane.config = config;\n existingLane.blobStorageKey = null;\n existingLane.pumpDriven = true;\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, existingLane);\n }\n\n const registeredAt = createSyncTimestamp();\n const nextLane: SyncLaneState = {\n ...INITIAL_SYNC_LANE_RUN_STATE,\n blobStorageKey: null,\n config,\n errorCount: 0,\n key,\n lastAction: \"registered\",\n lastActionAt: registeredAt,\n lastCompletedAt: null,\n lastError: null,\n lastFailedAt: null,\n lastRequestedAt: null,\n lastStartedAt: null,\n progress: null,\n pumpDriven: true,\n registrationIndex: coordinatorState.nextRegistrationIndex,\n requestCount: 0,\n };\n coordinatorState.nextRegistrationIndex += 1;\n coordinatorState.lanes.set(key, nextLane);\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, nextLane);\n },\n requestAllLanes() {\n requestAllPumpDrivenLanes(coordinatorState);\n },\n requestLane(key: string) {\n const lane = coordinatorState.lanes.get(key);\n if (lane?.pumpDriven) {\n requestLaneSync(coordinatorState, lane);\n }\n },\n subscribe(listener: () => void) {\n coordinatorState.listeners.add(listener);\n return () => {\n coordinatorState.listeners.delete(listener);\n };\n },\n waitForIdle(options?: SyncIdleOptions) {\n return waitForIdleLanes(coordinatorState, options);\n },\n };\n}\n\nexport function getOrCreateDomainSyncCoordinator(\n domainScope: DomainScope,\n): DomainSyncCoordinator {\n const existingCoordinator = coordinatorsByScope.get(domainScope);\n if (existingCoordinator) {\n return existingCoordinator;\n }\n\n const nextCoordinator = createDomainSyncCoordinator();\n coordinatorsByScope.set(domainScope, nextCoordinator);\n return nextCoordinator;\n}\n\nexport function hasDomainSyncCoordinatorPendingWork(\n domainScope: DomainScope,\n): boolean {\n return coordinatorsByScope.get(domainScope)?.hasPendingWork() ?? false;\n}\n\n// Re-request every pump-driven lane for a scope: a user-driven \"sync now\" that\n// retries durable work stranded by a transient failure. Observational upload\n// telemetry is never directly pumped. A no-op when no coordinator exists yet\n// (nothing has been synced) or it has been disposed.\nexport function requestAllDomainSyncLanes(domainScope: DomainScope): void {\n coordinatorsByScope.get(domainScope)?.requestAllLanes();\n}\n\nexport function requestDomainSyncLane(\n domainScope: DomainScope,\n key: string,\n): void {\n coordinatorsByScope.get(domainScope)?.requestLane(key);\n}\n\n// Stop admitting work and remove this scope's coordinator. Active callbacks\n// drain under their existing watchdogs; getOrCreate builds a fresh coordinator.\nexport function disposeDomainSyncCoordinator(domainScope: DomainScope): void {\n const coordinator = coordinatorsByScope.get(domainScope);\n if (!coordinator) {\n return;\n }\n\n coordinator.dispose();\n coordinatorsByScope.delete(domainScope);\n}\n\nexport function getDomainSyncCoordinatorSnapshot(\n domainScope: DomainScope,\n): DomainSyncSnapshot {\n return getOrCreateDomainSyncCoordinator(domainScope).getSnapshot();\n}\n\nexport function subscribeToDomainSyncCoordinator(\n domainScope: DomainScope,\n listener: () => void,\n): () => void {\n return getOrCreateDomainSyncCoordinator(domainScope).subscribe(listener);\n}\n\nexport function beginDomainSyncUploadLane(\n domainScope: DomainScope,\n key: string,\n options?: UploadSyncLaneOptions,\n): UploadSyncLane {\n return getOrCreateDomainSyncCoordinator(domainScope).beginUploadLane(\n key,\n options,\n );\n}\n\nexport function waitForDomainSyncCoordinatorToSettle(\n domainScope: DomainScope,\n options?: SyncIdleOptions,\n): Promise<boolean> {\n return (\n coordinatorsByScope.get(domainScope)?.waitForIdle(options) ??\n Promise.resolve(true)\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncCoordinator.js","sourceRoot":"","sources":["syncCoordinator.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,eAAe,EACf,oBAAoB,EAEpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,kBAAkB,EAClB,2BAA2B,EAC3B,8B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EpB,OAAO,gCAAgC,CAAC,WAAW,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;AAC3E,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,WAAwB,EACxB,GAAW,EACX,OAA+B;IAE/B,OAAO,gCAAgC,CAAC,WAAW,CAAC,CAAC,eAAe,CAClE,GAAG,EACH,OAAO,CACR,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oCAAoC,CAClD,WAAwB,EACxB,OAAyB;IAEzB,OAAO,CACL,mBAAmB,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC,OAAO,CAAC;QAC1D,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CACtB,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../shared/domainScope\";\nimport {\n requestAllPumpDrivenLanes,\n requestLaneSync,\n requestLaneSyncAfter,\n type SyncIdleOptions,\n waitForIdleLanes,\n} from \"./coordinatorPump\";\nimport type {\n DomainSyncCoordinatorState,\n SyncLaneState,\n} from \"./coordinatorState\";\nimport {\n hasPendingLaneWork,\n INITIAL_SYNC_LANE_RUN_STATE,\n publishSyncCoordinatorSnapshot,\n} from \"./coordinatorState\";\nimport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nimport { transitionSyncLaneRequest } from \"./syncLaneMachine\";\nimport type { DomainSyncSnapshot } from \"./syncTelemetry\";\nimport { createDomainSyncSnapshot, createSyncTimestamp } from \"./syncTelemetry\";\nimport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\nimport { beginUploadLane } from \"./uploadLane\";\n\n// Re-exported here because lanes reach it as a shouldIgnoreError alongside the\n// rest of the coordinator surface; it lives beside this coordinator with the\n// error type it discriminates on.\nexport { isDatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nexport type { SyncIdleOptions } from \"./coordinatorPump\";\nexport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nexport {\n didRegainSyncPrerequisites,\n type SyncRuntimeStatus,\n} from \"./syncPrerequisites\";\nexport type {\n DomainSyncSnapshot,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./syncTelemetry\";\nexport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\n\nexport interface DomainSyncCoordinator {\n beginUploadLane: (\n key: string,\n options?: UploadSyncLaneOptions,\n ) => UploadSyncLane;\n // Drop queued work and refuse new runs; active callbacks retain ownership.\n dispose: () => void;\n getSnapshot: () => DomainSyncSnapshot;\n registerLane: (key: string, config: SyncLaneConfig) => SyncLane;\n // Re-request every pump-driven lane — a manual \"sync now\" that re-drives\n // durable owners stranded by a transient failure. Observational upload rows\n // are updated only by those owners' real attachment upload attempts.\n requestAllLanes: () => void;\n // Request one registered pump lane without re-driving unrelated owners.\n requestLane: (key: string) => void;\n hasPendingWork: () => boolean;\n isDisposed: () => boolean;\n subscribe: (listener: () => void) => () => void;\n waitForIdle: (options?: SyncIdleOptions) => Promise<boolean>;\n}\n\nconst coordinatorsByScope = new WeakMap<DomainScope, DomainSyncCoordinator>();\n\nfunction createSyncLaneHandle(\n coordinatorState: DomainSyncCoordinatorState,\n lane: SyncLaneState,\n): SyncLane {\n return {\n isDisposed: () => coordinatorState.disposed,\n requestSync: () => requestLaneSync(coordinatorState, lane),\n requestSyncAfter: (delayMs) =>\n requestLaneSyncAfter(coordinatorState, lane, delayMs),\n };\n}\n\nfunction createDomainSyncCoordinator(): DomainSyncCoordinator {\n const coordinatorState: DomainSyncCoordinatorState = {\n disposed: false,\n lanes: new Map<string, SyncLaneState>(),\n listeners: new Set(),\n nextRegistrationIndex: 0,\n nextRunOrder: 0,\n wakePump: null,\n pump: null,\n snapshot: createDomainSyncSnapshot({\n hasPendingWork: false,\n lanes: [],\n pumpActive: false,\n }),\n };\n\n return {\n beginUploadLane(key: string, options: UploadSyncLaneOptions = {}) {\n return beginUploadLane(coordinatorState, key, options);\n },\n dispose() {\n coordinatorState.disposed = true;\n // Drop queued work so waitForIdle reports settled immediately and a\n // lane left re-requested by an in-flight run does not survive teardown.\n for (const lane of coordinatorState.lanes.values()) {\n lane.request = transitionSyncLaneRequest(lane.request, {\n type: \"clear\",\n });\n }\n // Publish the final settled snapshot, then release listener closures:\n // the coordinator is dropped from the registry and a remount subscribes\n // to a fresh one.\n publishSyncCoordinatorSnapshot(coordinatorState);\n coordinatorState.listeners.clear();\n },\n getSnapshot() {\n return coordinatorState.snapshot;\n },\n hasPendingWork() {\n return (\n !!coordinatorState.pump ||\n hasPendingLaneWork(coordinatorState.lanes.values())\n );\n },\n isDisposed() {\n return coordinatorState.disposed;\n },\n registerLane(key: string, config: SyncLaneConfig): SyncLane {\n const existingLane = coordinatorState.lanes.get(key);\n if (existingLane) {\n existingLane.config = config;\n existingLane.blobStorageKey = null;\n existingLane.pumpDriven = true;\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, existingLane);\n }\n\n const registeredAt = createSyncTimestamp();\n const nextLane: SyncLaneState = {\n ...INITIAL_SYNC_LANE_RUN_STATE,\n blobStorageKey: null,\n config,\n errorCount: 0,\n key,\n lastAction: \"registered\",\n lastActionAt: registeredAt,\n lastCompletedAt: null,\n lastError: null,\n lastFailedAt: null,\n lastRequestedAt: null,\n lastStartedAt: null,\n progress: null,\n pumpDriven: true,\n registrationIndex: coordinatorState.nextRegistrationIndex,\n requestCount: 0,\n };\n coordinatorState.nextRegistrationIndex += 1;\n coordinatorState.lanes.set(key, nextLane);\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, nextLane);\n },\n requestAllLanes() {\n requestAllPumpDrivenLanes(coordinatorState);\n },\n requestLane(key: string) {\n const lane = coordinatorState.lanes.get(key);\n if (lane?.pumpDriven) {\n requestLaneSync(coordinatorState, lane);\n }\n },\n subscribe(listener: () => void) {\n coordinatorState.listeners.add(listener);\n return () => {\n coordinatorState.listeners.delete(listener);\n };\n },\n waitForIdle(options?: SyncIdleOptions) {\n return waitForIdleLanes(coordinatorState, options);\n },\n };\n}\n\nexport function getOrCreateDomainSyncCoordinator(\n domainScope: DomainScope,\n): DomainSyncCoordinator {\n const existingCoordinator = coordinatorsByScope.get(domainScope);\n if (existingCoordinator) {\n return existingCoordinator;\n }\n\n const nextCoordinator = createDomainSyncCoordinator();\n coordinatorsByScope.set(domainScope, nextCoordinator);\n return nextCoordinator;\n}\n\nexport function hasDomainSyncCoordinatorPendingWork(\n domainScope: DomainScope,\n): boolean {\n return coordinatorsByScope.get(domainScope)?.hasPendingWork() ?? false;\n}\n\n// Re-request every pump-driven lane for a scope: a user-driven \"sync now\" that\n// retries durable work stranded by a transient failure. Observational upload\n// telemetry is never directly pumped. A no-op when no coordinator exists yet\n// (nothing has been synced) or it has been disposed.\nexport function requestAllDomainSyncLanes(domainScope: DomainScope): void {\n coordinatorsByScope.get(domainScope)?.requestAllLanes();\n}\n\nexport function requestDomainSyncLane(\n domainScope: DomainScope,\n key: string,\n): void {\n coordinatorsByScope.get(domainScope)?.requestLane(key);\n}\n\n// Stop admitting work and remove this scope's coordinator. Active callbacks\n// drain under their existing watchdogs; getOrCreate builds a fresh coordinator.\nexport function disposeDomainSyncCoordinator(domainScope: DomainScope): void {\n const coordinator = coordinatorsByScope.get(domainScope);\n if (!coordinator) {\n return;\n }\n\n coordinator.dispose();\n coordinatorsByScope.delete(domainScope);\n}\n\nexport function getDomainSyncCoordinatorSnapshot(\n domainScope: DomainScope,\n): DomainSyncSnapshot {\n return getOrCreateDomainSyncCoordinator(domainScope).getSnapshot();\n}\n\nexport function subscribeToDomainSyncCoordinator(\n domainScope: DomainScope,\n listener: () => void,\n): () => void {\n return getOrCreateDomainSyncCoordinator(domainScope).subscribe(listener);\n}\n\nexport function beginDomainSyncUploadLane(\n domainScope: DomainScope,\n key: string,\n options?: UploadSyncLaneOptions,\n): UploadSyncLane {\n return getOrCreateDomainSyncCoordinator(domainScope).beginUploadLane(\n key,\n options,\n );\n}\n\nexport function waitForDomainSyncCoordinatorToSettle(\n domainScope: DomainScope,\n options?: SyncIdleOptions,\n): Promise<boolean> {\n return (\n coordinatorsByScope.get(domainScope)?.waitForIdle(options) ??\n Promise.resolve(true)\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"]}
|
|
@@ -2,7 +2,7 @@ import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
|
2
2
|
import { TrustedUserIdentityPinCorruptError, } from "../persistence/identity/trustedUserIdentityPinModel.js";
|
|
3
3
|
import { TrustedUserIdentityPinRepository } from "../persistence/identity/trustedUserIdentityPinRepository.js";
|
|
4
4
|
import { TrustedUserIdentityPinContentionError } from "../persistence/identity/trustedUserIdentityPinTransaction.js";
|
|
5
|
-
import { DatabaseUnavailableError } from "../
|
|
5
|
+
import { DatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
|
|
6
6
|
import { assertTrustedUserIdentityUserId, validateRemoteUserIdentity, } from "./validation.js";
|
|
7
7
|
/** The trust store, account, and runtime generation one operation runs in. */
|
|
8
8
|
function capturePinScope(dependencies) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pinnedResolution.js","sourceRoot":"","sources":["pinnedResolution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAEL,kCAAkC,GACnC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAAE,qCAAqC,EAAE,MAAM,2DAA2D,CAAC;AAElH,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAYvE,OAAO,EACL,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,cAAc,CAAC;AAyBtB,8EAA8E;AAC9E,SAAS,eAAe,CACtB,YAAoD;IAEpD,MAAM,mBAAmB,GAAG,YAAY,CAAC,mBAAmB,CAAC;IAC7D,IAAI,CAAC,mBAAmB;QACtB,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,qEAAqE,CACtE,CAAC;IACJ,MAAM,OAAO,GAAG,YAAY,CAAC,UAAU,EAAE,CAAC;IAC1C,IAAI,CAAC,OAAO;QACV,MAAM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;gBACF,IAAI,OAAO,CAAC,OAAO,IAAI,MAAM,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;oBACvC,KAAK,CAAC,aAAa,EAAE,CAAC;oBACtB,MAAM,UAAU,CAAC,WAAW,CAC1B,KAAK,CAAC,OAAO,EACb,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EACpB,KAAK,CAAC,aAAa,CACpB,CAAC;gBACJ,CAAC;gBACD,KAAK,CAAC,aAAa,EAAE,CAAC;gBACtB,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC;gBAC5B,SAAS,GAAG,IAAI,CAAC;gBACjB,OAAO,MAAM,CAAC;YAChB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;YAC7B,CAAC;oBAAS,CAAC;gBACT,WAAW,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;YACzE,CAAC;QACH,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n type TrustedUserIdentityPin,\n TrustedUserIdentityPinCorruptError,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport type {\n HandoffScope,\n StagedIdentityHandoff,\n} from \"./stagedIdentityHandoff\";\nimport type {\n StagedUserIdentityOptions,\n StagedUserIdentityResolver,\n TrustedUserIdentityResolver,\n TrustedUserIdentityServiceDependencies,\n ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\n/** The gateway's own first-sight steps, split so a structural check can stage. */\nexport interface FirstSightIdentitySteps {\n /** The endpoint's validated candidate for a user; never pinned here. */\n readonly loadCandidate: (\n userId: string,\n identityTrustDomain: string,\n ) => Promise<ValidatedUserIdentityCandidate | null>;\n /**\n * Compare-or-insert candidates as `observed` pins in one write transaction:\n * a conflict on any of them, or a failed `assertCurrent` at COMMIT, commits\n * none, so a refused scope leaves no partial publication.\n */\n readonly pinObserved: (\n execSql: ExecSql,\n identities: readonly ValidatedUserIdentityCandidate[],\n assertCurrent: () => void,\n ) => Promise<unknown>;\n}\n\ninterface PinScope extends HandoffScope {\n readonly assertCurrent: () => void;\n}\n\n/** The trust store, account, and runtime generation one operation runs in. */\nfunction capturePinScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n): PinScope {\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (!identityTrustDomain)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n const execSql = dependencies.getExecSql();\n if (!execSql)\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n const localUserId = dependencies.getLocalUserId();\n const generation = dependencies.getScopeGeneration?.();\n return {\n execSql,\n generation,\n identityTrustDomain,\n localUserId,\n assertCurrent() {\n if (\n dependencies.getExecSql() !== execSql ||\n dependencies.getLocalUserId() !== localUserId ||\n dependencies.getScopeGeneration?.() !== generation\n )\n throw new DatabaseUnavailableError(\n \"The active identity changed while verifying pinned users.\",\n );\n },\n };\n}\n\n/**\n * Existing pins, self through ordinary resolution, and first sights staged in\n * memory; a publishing scope first takes an earlier unpublished scope's\n * handed-off answer. `fetched` records every such read so a failure evicts it.\n */\nfunction stagedResolver(input: {\n readonly fetched: Set<string>;\n readonly firstSight: FirstSightIdentitySteps;\n readonly handoff: StagedIdentityHandoff;\n readonly pins: ReadonlyMap<string, TrustedUserIdentityPin>;\n readonly publish: boolean;\n readonly resolve: TrustedUserIdentityResolver;\n readonly scope: PinScope;\n readonly staged: Map<string, ValidatedUserIdentityCandidate>;\n}): StagedUserIdentityResolver {\n const { scope } = input;\n return async (userId) => {\n scope.assertCurrent();\n if (userId === scope.localUserId) {\n const self = await input.resolve(userId);\n scope.assertCurrent();\n return self;\n }\n const pin = input.pins.get(userId);\n if (pin)\n return validateRemoteUserIdentity({\n candidate: pin,\n identityTrustDomain: scope.identityTrustDomain,\n requestedUserId: userId,\n });\n const known = input.staged.get(userId);\n if (known) return known;\n input.fetched.add(userId);\n const handed = input.publish\n ? input.handoff.take(scope, userId)\n : undefined;\n if (handed) {\n input.staged.set(userId, handed);\n return handed;\n }\n const candidate = await input.firstSight.loadCandidate(\n userId,\n scope.identityTrustDomain,\n );\n scope.assertCurrent();\n if (candidate) input.staged.set(userId, candidate);\n return candidate;\n };\n}\n\nfunction pinStoreError(error: unknown): unknown {\n if (error instanceof TrustedUserIdentityPinCorruptError)\n return new KeyingVerificationError(\"invalid_shape\", error.message);\n if (error instanceof TrustedUserIdentityPinContentionError)\n return new DatabaseUnavailableError(\n \"Trusted user identity pin store is busy\",\n );\n return error;\n}\n\n/**\n * A refused scope's answers are evicted, so a corrected retry reads the\n * endpoint again. An unpublished answer is unauthenticated even when `verify`\n * succeeded, since the caller's signature check may still refuse it: it stays\n * pending, readable only by a publishing scope that rechecks it, and any\n * other lookup reads the endpoint.\n */\nfunction settleScope(input: {\n readonly completed: boolean;\n readonly published: boolean;\n readonly fetched: ReadonlySet<string>;\n readonly staged: ReadonlyMap<string, ValidatedUserIdentityCandidate>;\n readonly scope: PinScope;\n readonly handoff: StagedIdentityHandoff;\n}): void {\n if (!input.completed) input.handoff.evict(input.fetched);\n else if (input.published) input.handoff.published(input.staged.keys());\n else input.handoff.retain(input.scope, input.staged);\n}\n\n/** Keep direct resolution unchanged; only structural verifiers opt into pins. */\nexport function withPinnedIdentityResolution(\n dependencies: TrustedUserIdentityServiceDependencies,\n resolve: TrustedUserIdentityResolver,\n firstSight: FirstSightIdentitySteps,\n handoff: StagedIdentityHandoff,\n): TrustedUserIdentityResolver {\n return Object.assign(resolve, {\n async withPinnedIdentities<T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ): Promise<T> {\n const captured = capturePinScope(dependencies);\n const scope: PinScope = {\n ...captured,\n assertCurrent() {\n captured.assertCurrent();\n options.assertCurrent?.();\n },\n };\n for (const userId of userIds) assertTrustedUserIdentityUserId(userId);\n // First sights stay in memory until `verify` succeeds for a projection\n // the caller has authenticated: a refusal leaves no durable trace.\n const fetched = new Set<string>();\n const staged = new Map<string, ValidatedUserIdentityCandidate>();\n let published = false;\n let completed = false;\n try {\n const pins = await new TrustedUserIdentityPinRepository(\n scope.execSql,\n ).loadTrustedUserIdentityPins({\n identityTrustDomain: scope.identityTrustDomain,\n // Self always rechecks the authoritative local keys and provenance.\n userIds: userIds.filter((userId) => userId !== scope.localUserId),\n });\n scope.assertCurrent();\n const result = await verify(\n stagedResolver({\n fetched,\n firstSight,\n handoff,\n pins,\n publish: options.publish,\n resolve,\n scope,\n staged,\n }),\n );\n if (options.publish && staged.size > 0) {\n scope.assertCurrent();\n await firstSight.pinObserved(\n scope.execSql,\n [...staged.values()],\n scope.assertCurrent,\n );\n }\n scope.assertCurrent();\n published = options.publish;\n completed = true;\n return result;\n } catch (error) {\n throw pinStoreError(error);\n } finally {\n settleScope({ completed, published, fetched, staged, scope, handoff });\n }\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"pinnedResolution.js","sourceRoot":"","sources":["pinnedResolution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAEL,kCAAkC,GACnC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAAE,qCAAqC,EAAE,MAAM,2DAA2D,CAAC;AAClH,OAAO,EAAE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,mBAAmB;oBAC9C,oEAAoE;oBACpE,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,KAAK,KAAK,CAAC,WAAW,CAAC;iBAClE,CAAC,CAAC;gBACH,KAAK,CAAC,aAAa,EAAE,CAAC;gBACtB,MAAM,MAAM,GAAG,MAAM,MAAM,CACzB,cAAc,CAAC;oBACb,OAAO;oBACP,UAAU;oBACV,OAAO;oBACP,IAAI;oBACJ,OAAO,EAAE,OAAO,CAAC,OAAO;oBACxB,OAAO;oBACP,KAAK;oBACL,MAAM;iBACP,CAAC,CACH,CAAC;gBACF,IAAI,OAAO,CAAC,OAAO,IAAI,MAAM,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;oBACvC,KAAK,CAAC,aAAa,EAAE,CAAC;oBACtB,MAAM,UAAU,CAAC,WAAW,CAC1B,KAAK,CAAC,OAAO,EACb,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EACpB,KAAK,CAAC,aAAa,CACpB,CAAC;gBACJ,CAAC;gBACD,KAAK,CAAC,aAAa,EAAE,CAAC;gBACtB,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC;gBAC5B,SAAS,GAAG,IAAI,CAAC;gBACjB,OAAO,MAAM,CAAC;YAChB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;YAC7B,CAAC;oBAAS,CAAC;gBACT,WAAW,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;YACzE,CAAC;QACH,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n type TrustedUserIdentityPin,\n TrustedUserIdentityPinCorruptError,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport { DatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport type {\n HandoffScope,\n StagedIdentityHandoff,\n} from \"./stagedIdentityHandoff\";\nimport type {\n StagedUserIdentityOptions,\n StagedUserIdentityResolver,\n TrustedUserIdentityResolver,\n TrustedUserIdentityServiceDependencies,\n ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\n/** The gateway's own first-sight steps, split so a structural check can stage. */\nexport interface FirstSightIdentitySteps {\n /** The endpoint's validated candidate for a user; never pinned here. */\n readonly loadCandidate: (\n userId: string,\n identityTrustDomain: string,\n ) => Promise<ValidatedUserIdentityCandidate | null>;\n /**\n * Compare-or-insert candidates as `observed` pins in one write transaction:\n * a conflict on any of them, or a failed `assertCurrent` at COMMIT, commits\n * none, so a refused scope leaves no partial publication.\n */\n readonly pinObserved: (\n execSql: ExecSql,\n identities: readonly ValidatedUserIdentityCandidate[],\n assertCurrent: () => void,\n ) => Promise<unknown>;\n}\n\ninterface PinScope extends HandoffScope {\n readonly assertCurrent: () => void;\n}\n\n/** The trust store, account, and runtime generation one operation runs in. */\nfunction capturePinScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n): PinScope {\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (!identityTrustDomain)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n const execSql = dependencies.getExecSql();\n if (!execSql)\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n const localUserId = dependencies.getLocalUserId();\n const generation = dependencies.getScopeGeneration?.();\n return {\n execSql,\n generation,\n identityTrustDomain,\n localUserId,\n assertCurrent() {\n if (\n dependencies.getExecSql() !== execSql ||\n dependencies.getLocalUserId() !== localUserId ||\n dependencies.getScopeGeneration?.() !== generation\n )\n throw new DatabaseUnavailableError(\n \"The active identity changed while verifying pinned users.\",\n );\n },\n };\n}\n\n/**\n * Existing pins, self through ordinary resolution, and first sights staged in\n * memory; a publishing scope first takes an earlier unpublished scope's\n * handed-off answer. `fetched` records every such read so a failure evicts it.\n */\nfunction stagedResolver(input: {\n readonly fetched: Set<string>;\n readonly firstSight: FirstSightIdentitySteps;\n readonly handoff: StagedIdentityHandoff;\n readonly pins: ReadonlyMap<string, TrustedUserIdentityPin>;\n readonly publish: boolean;\n readonly resolve: TrustedUserIdentityResolver;\n readonly scope: PinScope;\n readonly staged: Map<string, ValidatedUserIdentityCandidate>;\n}): StagedUserIdentityResolver {\n const { scope } = input;\n return async (userId) => {\n scope.assertCurrent();\n if (userId === scope.localUserId) {\n const self = await input.resolve(userId);\n scope.assertCurrent();\n return self;\n }\n const pin = input.pins.get(userId);\n if (pin)\n return validateRemoteUserIdentity({\n candidate: pin,\n identityTrustDomain: scope.identityTrustDomain,\n requestedUserId: userId,\n });\n const known = input.staged.get(userId);\n if (known) return known;\n input.fetched.add(userId);\n const handed = input.publish\n ? input.handoff.take(scope, userId)\n : undefined;\n if (handed) {\n input.staged.set(userId, handed);\n return handed;\n }\n const candidate = await input.firstSight.loadCandidate(\n userId,\n scope.identityTrustDomain,\n );\n scope.assertCurrent();\n if (candidate) input.staged.set(userId, candidate);\n return candidate;\n };\n}\n\nfunction pinStoreError(error: unknown): unknown {\n if (error instanceof TrustedUserIdentityPinCorruptError)\n return new KeyingVerificationError(\"invalid_shape\", error.message);\n if (error instanceof TrustedUserIdentityPinContentionError)\n return new DatabaseUnavailableError(\n \"Trusted user identity pin store is busy\",\n );\n return error;\n}\n\n/**\n * A refused scope's answers are evicted, so a corrected retry reads the\n * endpoint again. An unpublished answer is unauthenticated even when `verify`\n * succeeded, since the caller's signature check may still refuse it: it stays\n * pending, readable only by a publishing scope that rechecks it, and any\n * other lookup reads the endpoint.\n */\nfunction settleScope(input: {\n readonly completed: boolean;\n readonly published: boolean;\n readonly fetched: ReadonlySet<string>;\n readonly staged: ReadonlyMap<string, ValidatedUserIdentityCandidate>;\n readonly scope: PinScope;\n readonly handoff: StagedIdentityHandoff;\n}): void {\n if (!input.completed) input.handoff.evict(input.fetched);\n else if (input.published) input.handoff.published(input.staged.keys());\n else input.handoff.retain(input.scope, input.staged);\n}\n\n/** Keep direct resolution unchanged; only structural verifiers opt into pins. */\nexport function withPinnedIdentityResolution(\n dependencies: TrustedUserIdentityServiceDependencies,\n resolve: TrustedUserIdentityResolver,\n firstSight: FirstSightIdentitySteps,\n handoff: StagedIdentityHandoff,\n): TrustedUserIdentityResolver {\n return Object.assign(resolve, {\n async withPinnedIdentities<T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ): Promise<T> {\n const captured = capturePinScope(dependencies);\n const scope: PinScope = {\n ...captured,\n assertCurrent() {\n captured.assertCurrent();\n options.assertCurrent?.();\n },\n };\n for (const userId of userIds) assertTrustedUserIdentityUserId(userId);\n // First sights stay in memory until `verify` succeeds for a projection\n // the caller has authenticated: a refusal leaves no durable trace.\n const fetched = new Set<string>();\n const staged = new Map<string, ValidatedUserIdentityCandidate>();\n let published = false;\n let completed = false;\n try {\n const pins = await new TrustedUserIdentityPinRepository(\n scope.execSql,\n ).loadTrustedUserIdentityPins({\n identityTrustDomain: scope.identityTrustDomain,\n // Self always rechecks the authoritative local keys and provenance.\n userIds: userIds.filter((userId) => userId !== scope.localUserId),\n });\n scope.assertCurrent();\n const result = await verify(\n stagedResolver({\n fetched,\n firstSight,\n handoff,\n pins,\n publish: options.publish,\n resolve,\n scope,\n staged,\n }),\n );\n if (options.publish && staged.size > 0) {\n scope.assertCurrent();\n await firstSight.pinObserved(\n scope.execSql,\n [...staged.values()],\n scope.assertCurrent,\n );\n }\n scope.assertCurrent();\n published = options.publish;\n completed = true;\n return result;\n } catch (error) {\n throw pinStoreError(error);\n } finally {\n settleScope({ completed, published, fetched, staged, scope, handoff });\n }\n },\n });\n}\n"]}
|
|
@@ -3,7 +3,7 @@ import { bytesToBase64 } from "../../internal/encoding/index.js";
|
|
|
3
3
|
import { TrustedUserIdentityPinCorruptError, TrustedUserIdentityPinMismatchError, } from "../persistence/identity/trustedUserIdentityPinModel.js";
|
|
4
4
|
import { TrustedUserIdentityPinRepository } from "../persistence/identity/trustedUserIdentityPinRepository.js";
|
|
5
5
|
import { TrustedUserIdentityPinContentionError } from "../persistence/identity/trustedUserIdentityPinTransaction.js";
|
|
6
|
-
import { DatabaseUnavailableError } from "../
|
|
6
|
+
import { DatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
|
|
7
7
|
import { UnverifiedUserIdentityError } from "./admission.js";
|
|
8
8
|
import { assertIdentityLinkMatches, createIdentityLink, parseIdentityLink, } from "./identityLink.js";
|
|
9
9
|
import { loadPin, loadPinnedUserIdentity } from "./pinnedIdentity.js";
|