@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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncFailureClassification.js","sourceRoot":"","sources":["syncFailureClassification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,+BAA+B,EAAE,MAAM,kEAAkE,CAAC;AACnH,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,GACrC,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,yBAAyB,EAAE,MAAM,kDAAkD,CAAC;AAqB7F;;;;;GAKG;AACH,MAAM,UAAU,mCAAmC,CACjD,OAA8D;IAE9D,MAAM,MAAM,GACV,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;QAC/B,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE;QACxB,CAAC,CAAC,6BAA6B,CAAC;IACpC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,MAAM,GAAG,CAAC;IACrE,OAAO,+BAA+B,MAAM,GAAG,MAAM,EAAE,CAAC;AAC1D,CAAC;AAED,iFAAi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vD;IACC,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,GAAG;QACtB,OAAO,CAAC,IAAI,KAAK,6BAA6B,CAAC,qBAAqB,CACrE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,KAI5C;IACC,OAAO,CACL,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,WAAW;QACjC,+BAA+B,CAAC,KAAK,CAAC,OAAO,CAAC,CAC/C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kCAAkC,CAAC,KAKlD;IACC,OAAO,CACL,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,WAAW;QACjC,KAAK,CAAC,kBAAkB,GAAG,CAAC;QAC5B,qCAAqC,CAAC,KAAK,CAAC,OAAO,CAAC,CACrD,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAAC,KAI9D;IACC,IAAI,CAAC,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IACxE,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DOCUMENT_MUTATION_ERROR_CODES,\n DOCUMENT_SYNC_ERROR_CODES,\n} from \"@tearleads/validators/response\";\nimport { ContainerKekRepairRequiredError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport {\n isRetryableDocumentSyncConflict,\n isUpstreamDeletedDocumentSyncFailure,\n} from \"../../../data/documents/shared/responses\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { isKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\nexport type RemoteDocumentDeletionHandler = (input: {\n /** Present only after the SDK has verified the signed terminal purge proof. */\n readonly commitPurgeProof?:\n | ((transactionExecSql: ExecSql) => Promise<void>)\n | undefined;\n readonly documentId: string;\n}) => Promise<void> | void;\n\n/**\n * Invoked when a submission fails terminally — the failure is neither a\n * retryable conflict nor a recoverable update-id conflict, so the sync pass\n * stops and the pending writes stay queued (e.g. a 403 after write access was\n * revoked). Callers persist the failure so the write queue can surface it.\n */\nexport type TerminalSubmitFailureHandler = (\n failure: DocumentSyncSubmitFailure,\n) => Promise<void> | void;\n\n/**\n * Read-only counterpart to describeDocumentSyncSubmitFailure: names a refused\n * revalidation without implying a blocked write. 403s never reach this — a\n * read-only 403 is deliberately suppressed (edge-case row 9) so unattempted\n * local edits are never flagged.\n */\nexport function describeDocumentRevalidationFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n const detail =\n failure.message.trim().length > 0\n ? failure.message.trim()\n : \"the server refused the read\";\n const suffix = failure.status === null ? \"\" : ` (${failure.status})`;\n return `Remote revalidation failed: ${detail}${suffix}`;\n}\n\n/** Human-readable description of a terminal submit failure for queue display. */\nexport function describeDocumentSyncSubmitFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n if (failure.status === 403) {\n return \"Write access denied by the server (403)\";\n }\n const message =\n failure.message.trim().length > 0 ? failure.message.trim() : \"Sync failed\";\n return failure.status === null ? message : `${message} (${failure.status})`;\n}\n\ntype ProjectionIntegrityErrorCode =\n | \"equivocation\"\n | \"rollback\"\n | \"stale_predecessor\";\n\nfunction keyingVerificationErrorCode(error: unknown): string | null {\n if (!isKeyingVerificationError(error) || !(error instanceof Error)) {\n return null;\n }\n const code = Reflect.get(error, \"code\");\n return typeof code === \"string\" ? code : null;\n}\n\nexport function projectionIntegrityErrorCode(\n error: unknown,\n): ProjectionIntegrityErrorCode | null {\n if (\n !(error instanceof KeyingVerificationError) &&\n !(error instanceof Error && error.name === \"KeyingVerificationError\")\n ) {\n return null;\n }\n\n const code = keyingVerificationErrorCode(error);\n return code === \"rollback\" ||\n code === \"equivocation\" ||\n code === \"stale_predecessor\"\n ? code\n : null;\n}\n\n/**\n * Shared shell for the stale-projection retry classifiers. A cached\n * projection older than a checkpoint we already recorded (\"rollback\") —\n * typical right after a peer shared/rotated a linked container — is resolved\n * by refetching the current projection. The refetch is safe: it cannot\n * bypass the anti-rollback check, because a genuinely rolled-back server\n * response re-throws on the rebuilt plan. Any other keying-verification\n * failure is terminal; anything else defers to the caller's message\n * predicate for its unwrap-failure shape.\n */\nexport function shouldRetryWithFreshProjection(\n error: unknown,\n messageMatches: (message: string) => boolean,\n): boolean {\n // A peer may already have repaired the chain. Refetch once; the same guard\n // rejects a still-stale response before any new ciphertext is produced.\n if (\n error instanceof ContainerKekRepairRequiredError ||\n error instanceof ProjectionDependencyUnavailableError\n )\n return true;\n const integrityErrorCode = projectionIntegrityErrorCode(error);\n if (integrityErrorCode) {\n return integrityErrorCode === \"rollback\";\n }\n if (keyingVerificationErrorCode(error) === \"invalid_shape\") {\n // Verification boundaries normalize malformed/stale projection data to a\n // terminal error. One cache eviction is still safe: a dishonest or broken\n // fresh response fails again outside this retry boundary.\n return true;\n }\n if (isKeyingVerificationError(error)) {\n return false;\n }\n\n return error instanceof Error && messageMatches(error.message);\n}\n\nexport function shouldRetrySyncWithFreshWriterProjection(\n error: unknown,\n): boolean {\n return shouldRetryWithFreshProjection(\n error,\n (message) =>\n message.startsWith(\n \"Document authorizing container KEK path could not be unwrapped\",\n ) && message.includes(\"Container writer projection KEK\"),\n );\n}\n\nexport function isRecoverableDocumentUpdateIdConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.updateIdConflict\n );\n}\n\n/**\n * The server's covering-baseline gate refused a queued rotation checkpoint\n * (e.g. a leftover from an interrupted recovery or a lost heal ack) because\n * it no longer covers the committed frontier. The pass can repair itself by\n * regenerating a fresh covering baseline from the live document instead of\n * resubmitting the stale payload — which would fail terminally forever.\n */\nexport function isCheckpointCoverageConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.checkpointCoverageConflict\n );\n}\n\n/**\n * A create submitted with a stable documentId whose first attempt already\n * committed server-side comes back as this 409 (see the server's\n * `assertCreateCanAdvanceDocumentHead`). It is not a failure — the caller adopts\n * the existing remote document instead of creating a duplicate.\n */\nexport function isDocumentManifestAlreadyExistsConflict(failure: {\n readonly code?: string | undefined;\n readonly message: string;\n readonly status: number | null;\n}): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_MUTATION_ERROR_CODES.manifestAlreadyExists\n );\n}\n\nexport function canRetryDocumentSyncConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n isRetryableDocumentSyncConflict(input.failure)\n );\n}\n\nexport function canRecoverDocumentUpdateIdConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n pendingUpdateCount: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n input.pendingUpdateCount > 0 &&\n isRecoverableDocumentUpdateIdConflict(input.failure)\n );\n}\n\nexport async function handleUpstreamDeletedDocumentSyncFailure(input: {\n documentId: string;\n failure: DocumentSyncSubmitFailure;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n}): Promise<boolean> {\n if (!isUpstreamDeletedDocumentSyncFailure(input.failure)) {\n return false;\n }\n\n await input.onRemoteDocumentDeleted?.({ documentId: input.documentId });\n return true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncFailureClassification.js","sourceRoot":"","sources":["syncFailureClassification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;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AED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAAC,KAI9D;IACC,IAAI,CAAC,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IACxE,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DOCUMENT_MUTATION_ERROR_CODES,\n DOCUMENT_SYNC_ERROR_CODES,\n} from \"@tearleads/validators/response\";\nimport { ContainerKekRepairRequiredError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport {\n isRetryableDocumentSyncConflict,\n isUpstreamDeletedDocumentSyncFailure,\n} from \"../../../data/documents/shared/responses\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport { isKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\nexport type RemoteDocumentDeletionHandler = (input: {\n /** Present only after the SDK has verified the signed terminal purge proof. */\n readonly commitPurgeProof?:\n | ((transactionExecSql: ExecSql) => Promise<void>)\n | undefined;\n readonly documentId: string;\n}) => Promise<void> | void;\n\n/**\n * Invoked when a submission fails terminally — the failure is neither a\n * retryable conflict nor a recoverable update-id conflict, so the sync pass\n * stops and the pending writes stay queued (e.g. a 403 after write access was\n * revoked). Callers persist the failure so the write queue can surface it.\n */\nexport type TerminalSubmitFailureHandler = (\n failure: DocumentSyncSubmitFailure,\n) => Promise<void> | void;\n\n/**\n * Read-only counterpart to describeDocumentSyncSubmitFailure: names a refused\n * revalidation without implying a blocked write. 403s never reach this — a\n * read-only 403 is deliberately suppressed (edge-case row 9) so unattempted\n * local edits are never flagged.\n */\nexport function describeDocumentRevalidationFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n const detail =\n failure.message.trim().length > 0\n ? failure.message.trim()\n : \"the server refused the read\";\n const suffix = failure.status === null ? \"\" : ` (${failure.status})`;\n return `Remote revalidation failed: ${detail}${suffix}`;\n}\n\n/** Human-readable description of a terminal submit failure for queue display. */\nexport function describeDocumentSyncSubmitFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n if (failure.status === 403) {\n return \"Write access denied by the server (403)\";\n }\n const message =\n failure.message.trim().length > 0 ? failure.message.trim() : \"Sync failed\";\n return failure.status === null ? message : `${message} (${failure.status})`;\n}\n\ntype ProjectionIntegrityErrorCode =\n | \"equivocation\"\n | \"rollback\"\n | \"stale_predecessor\";\n\nfunction keyingVerificationErrorCode(error: unknown): string | null {\n if (!isKeyingVerificationError(error) || !(error instanceof Error)) {\n return null;\n }\n const code = Reflect.get(error, \"code\");\n return typeof code === \"string\" ? code : null;\n}\n\nexport function projectionIntegrityErrorCode(\n error: unknown,\n): ProjectionIntegrityErrorCode | null {\n if (\n !(error instanceof KeyingVerificationError) &&\n !(error instanceof Error && error.name === \"KeyingVerificationError\")\n ) {\n return null;\n }\n\n const code = keyingVerificationErrorCode(error);\n return code === \"rollback\" ||\n code === \"equivocation\" ||\n code === \"stale_predecessor\"\n ? code\n : null;\n}\n\n/**\n * Shared shell for the stale-projection retry classifiers. A cached\n * projection older than a checkpoint we already recorded (\"rollback\") —\n * typical right after a peer shared/rotated a linked container — is resolved\n * by refetching the current projection. The refetch is safe: it cannot\n * bypass the anti-rollback check, because a genuinely rolled-back server\n * response re-throws on the rebuilt plan. Any other keying-verification\n * failure is terminal; anything else defers to the caller's message\n * predicate for its unwrap-failure shape.\n */\nexport function shouldRetryWithFreshProjection(\n error: unknown,\n messageMatches: (message: string) => boolean,\n): boolean {\n // A peer may already have repaired the chain. Refetch once; the same guard\n // rejects a still-stale response before any new ciphertext is produced.\n if (\n error instanceof ContainerKekRepairRequiredError ||\n error instanceof ProjectionDependencyUnavailableError\n )\n return true;\n const integrityErrorCode = projectionIntegrityErrorCode(error);\n if (integrityErrorCode) {\n return integrityErrorCode === \"rollback\";\n }\n if (keyingVerificationErrorCode(error) === \"invalid_shape\") {\n // Verification boundaries normalize malformed/stale projection data to a\n // terminal error. One cache eviction is still safe: a dishonest or broken\n // fresh response fails again outside this retry boundary.\n return true;\n }\n if (isKeyingVerificationError(error)) {\n return false;\n }\n\n return error instanceof Error && messageMatches(error.message);\n}\n\nexport function shouldRetrySyncWithFreshWriterProjection(\n error: unknown,\n): boolean {\n return shouldRetryWithFreshProjection(\n error,\n (message) =>\n message.startsWith(\n \"Document authorizing container KEK path could not be unwrapped\",\n ) && message.includes(\"Container writer projection KEK\"),\n );\n}\n\nexport function isRecoverableDocumentUpdateIdConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.updateIdConflict\n );\n}\n\n/**\n * The server's covering-baseline gate refused a queued rotation checkpoint\n * (e.g. a leftover from an interrupted recovery or a lost heal ack) because\n * it no longer covers the committed frontier. The pass can repair itself by\n * regenerating a fresh covering baseline from the live document instead of\n * resubmitting the stale payload — which would fail terminally forever.\n */\nexport function isCheckpointCoverageConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.checkpointCoverageConflict\n );\n}\n\n/**\n * A create submitted with a stable documentId whose first attempt already\n * committed server-side comes back as this 409 (see the server's\n * `assertCreateCanAdvanceDocumentHead`). It is not a failure — the caller adopts\n * the existing remote document instead of creating a duplicate.\n */\nexport function isDocumentManifestAlreadyExistsConflict(failure: {\n readonly code?: string | undefined;\n readonly message: string;\n readonly status: number | null;\n}): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_MUTATION_ERROR_CODES.manifestAlreadyExists\n );\n}\n\nexport function canRetryDocumentSyncConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n isRetryableDocumentSyncConflict(input.failure)\n );\n}\n\nexport function canRecoverDocumentUpdateIdConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n pendingUpdateCount: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n input.pendingUpdateCount > 0 &&\n isRecoverableDocumentUpdateIdConflict(input.failure)\n );\n}\n\nexport async function handleUpstreamDeletedDocumentSyncFailure(input: {\n documentId: string;\n failure: DocumentSyncSubmitFailure;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n}): Promise<boolean> {\n if (!isUpstreamDeletedDocumentSyncFailure(input.failure)) {\n return false;\n }\n\n await input.onRemoteDocumentDeleted?.({ documentId: input.documentId });\n return true;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
2
|
-
import { isDatabaseUnavailableError } from "../../data/
|
|
2
|
+
import { isDatabaseUnavailableError } from "../../data/sqlite/availability/databaseUnavailable.js";
|
|
3
3
|
import { requireTrustedUserIdentityResolver, } from "../../data/trustedUserIdentity/index.js";
|
|
4
4
|
export function createDocumentWriterPublicKeyResolver(input) {
|
|
5
5
|
const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(input.runtime.resolveTrustedUserIdentity);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writerKeys.js","sourceRoot":"","sources":["writerKeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"writerKeys.js","sourceRoot":"","sources":["writerKeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAA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AAI,CAAC;QACd,CAAC;QAED,IAAI,QAAQ,CAAC,qBAAqB,KAAK,KAAK,CAAC,iBAAiB,EAAE,CAAC;YAC/D,KAAK,CAAC,IAAI,CAAC,GAAG,CACZ,GAAG,KAAK,CAAC,SAAS,aAAa,KAAK,CAAC,cAAc,QAAQ,KAAK,CAAC,YAAY,6DAA6D,CAC3I,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,QAAQ,CAAC,gBAAgB,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC7C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,0EAA0E;QAC1E,2EAA2E;QAC3E,0EAA0E;QAC1E,0EAA0E;QAC1E,wEAAwE;QACxE,IAAI,0BAA0B,CAAC,KAAK,CAAC,EAAE,CAAC;YACtC,MAAM,KAAK,CAAC;QACd,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,GAAG,CACZ,GAAG,KAAK,CAAC,SAAS,aAAa,KAAK,CAAC,cAAc,QAAQ,KAAK,CAAC,YAAY,kCAAkC,CAChH,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterPublicKeyResolver } from \"../../data/documents/shared/types\";\nimport { isDatabaseUnavailableError } from \"../../data/sqlite/availability/databaseUnavailable\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\n\ninterface DocumentWriterPublicKeyRuntime {\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: {\n readonly log: (message: string) => void;\n };\n}\n\nexport function createDocumentWriterPublicKeyResolver(input: {\n readonly logPrefix: string;\n readonly runtime: DocumentWriterPublicKeyRuntime;\n readonly writerKeyLabel: string;\n}): DocumentWriterPublicKeyResolver {\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.runtime.resolveTrustedUserIdentity,\n );\n const cache = new Map<string, Promise<Uint8Array | null>>();\n\n return async ({ writerSigningKeyFingerprint, writerUserId }) => {\n const cacheKey = `${writerUserId}:${writerSigningKeyFingerprint}`;\n let cached = cache.get(cacheKey);\n if (!cached) {\n cached = resolveWriterPublicKey({\n authorFingerprint: writerSigningKeyFingerprint,\n logPrefix: input.logPrefix,\n resolveTrustedUserIdentity,\n util: input.runtime.util,\n writerKeyLabel: input.writerKeyLabel,\n writerUserId,\n }).catch((error: unknown) => {\n cache.delete(cacheKey);\n throw error;\n });\n cache.set(cacheKey, cached);\n }\n\n return cached;\n };\n}\n\nasync function resolveWriterPublicKey(input: {\n readonly authorFingerprint: string;\n readonly logPrefix: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: DocumentWriterPublicKeyRuntime[\"util\"];\n readonly writerKeyLabel: string;\n readonly writerUserId: string;\n}): Promise<Uint8Array | null> {\n try {\n const identity = await input.resolveTrustedUserIdentity(input.writerUserId);\n if (!identity) {\n return null;\n }\n\n if (identity.signingKeyFingerprint !== input.authorFingerprint) {\n input.util.log(\n `${input.logPrefix}: skipped ${input.writerKeyLabel} for ${input.writerUserId} because the signing fingerprint does not match the writer.`,\n );\n return null;\n }\n\n return identity.signingPublicKey;\n } catch (error) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n // A vanished database is infrastructure loss, not an unresolvable writer.\n // Returning null here would surface downstream as a generic \"writer public\n // key missing\" verification error that sync lanes cannot classify, so the\n // lane would count a real failure for a routine runtime swap. Rethrow and\n // let the lanes' shouldIgnoreError treat it as the benign signal it is.\n if (isDatabaseUnavailableError(error)) {\n throw error;\n }\n input.util.log(\n `${input.logPrefix}: skipped ${input.writerKeyLabel} for ${input.writerUserId} because it could not be loaded.`,\n );\n return null;\n }\n}\n"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../internal/crypto/index.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
3
2
|
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
4
3
|
import { KeyingCheckpointRepository } from "../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
5
4
|
import { assertCurrentMatchesVerifiedPolicy } from "../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js";
|
|
6
5
|
import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../data/principals/organizationAuthorityDescriptor.js";
|
|
6
|
+
import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
|
|
7
7
|
/** One directory view with bounded, authenticated current artifacts for its groups. */
|
|
8
8
|
export async function loadCurrentOrganizationAuthority(input) {
|
|
9
9
|
if (input.organizationReference)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currentOrganizationAuthority.js","sourceRoot":"","sources":["currentOrganizationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,uEAAuE,CAAC;AAC3H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAgB/D,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAwC;IAExC,IAAI,KAAK,CAAC,qBAAqB;QAC7B,oBAAoB,CAClB,KAAK,CAAC,qBAAqB,EAC3B,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,MAAM,aAAa,GAAG,KAAK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,EAAE,QAAQ,CAAC;QACzE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,wDAAwD,CACzD,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type {\n PrincipalPolicyCurrentResolver as CurrentPolicyResolver,\n ResolvedPrincipalPolicyCurrent,\n} from \"../principals/runtimePolicyRecovery\";\n\ninterface CurrentOrganizationAuthorityInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly organizationReference?: ReferencedPrincipalHead | null | undefined;\n readonly resolveCurrentPolicy: CurrentPolicyResolver;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/** One directory view with bounded, authenticated current artifacts for its groups. */\nexport async function loadCurrentOrganizationAuthority(\n input: CurrentOrganizationAuthorityInput,\n) {\n if (input.organizationReference)\n assertReferenceScope(\n input.organizationReference,\n \"organization\",\n input.organizationId,\n );\n const recoveryBatch = input.recoveryBatch ?? {};\n const resolve = (reference?: ReferencedPrincipalHead | null) =>\n input.resolveCurrentPolicy({\n organizationId: input.organizationId,\n reference: reference ?? undefined,\n preferLocalCurrent: true,\n recoveryBatch,\n stillCurrent: input.stillCurrent,\n });\n const directory = await resolve(input.organizationReference);\n await assertExactCurrent(\n directory,\n input.organizationReference ?? directory.policy.state,\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.current.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization current policy payload is outside its scope\",\n );\n const adminHead = requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n );\n const admins = await resolve(adminHead);\n await assertExactCurrent(admins, adminHead);\n assertDirectoryDependency(admins, directory);\n const stillCurrent = () =>\n input.stillCurrent() && directory.stillCurrent() && admins.stillCurrent();\n const validate = async (value: ResolvedPrincipalPolicyCurrent) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: [],\n policies: [...value.dependencies, value.policy],\n stillCurrent: () => stillCurrent() && value.stillCurrent(),\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && value.stillCurrent(),\n );\n };\n await validate(admins);\n return {\n admins,\n descriptor,\n directory,\n stillCurrent,\n async readGroup(groupId: string, reference?: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const head = requireOrganizationGroupHead(descriptor, groupId);\n const selected = reference ?? head;\n assertReferenceScope(selected, \"group\", groupId);\n const result =\n groupId === descriptor.adminGroupId &&\n principalHeadMatchesReference(admins.policy.state, selected)\n ? admins\n : await resolve(selected);\n await assertExactCurrent(result, head);\n assertDirectoryDependency(result, directory);\n if (groupId !== descriptor.adminGroupId)\n assertAdminsDependency(result, adminHead);\n await validate(result);\n return result;\n },\n };\n}\n\nfunction assertReferenceScope(\n reference: ReferencedPrincipalHead,\n principalType: ReferencedPrincipalHead[\"principalType\"],\n principalId: string,\n) {\n if (\n reference.principalType !== principalType ||\n reference.principalId !== principalId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n}\n\nasync function assertExactCurrent(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n assertProjectionVerificationCurrent(value.stillCurrent);\n await assertCurrentMatchesVerifiedPolicy(value);\n if (!principalHeadMatchesReference(value.policy.state, expected))\n throw new ProjectionDependencyUnavailableError(\n \"Current policy changed from the selected organization directory\",\n );\n assertProjectionVerificationCurrent(value.stillCurrent);\n}\n\nfunction assertDirectoryDependency(\n value: ResolvedPrincipalPolicyCurrent,\n directory: ResolvedPrincipalPolicyCurrent,\n) {\n const dependency = value.dependencies.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === directory.policy.principalId,\n );\n if (\n !dependency ||\n !principalHeadMatchesReference(dependency.state, directory.policy.state)\n )\n throw new ProjectionDependencyUnavailableError(\n \"Current policy belongs to a changed organization directory\",\n );\n}\n\nfunction assertAdminsDependency(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n const authority = value.dependencies.find(\n (policy) =>\n policy.principalType === \"group\" &&\n policy.principalId === expected.principalId,\n );\n if (!authority || !principalHeadMatchesReference(authority.state, expected))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Current group policy omits its exact Admins dependency\",\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"currentOrganizationAuthority.js","sourceRoot":"","sources":["currentOrganizationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,uEAAuE,CAAC;AAC3H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAgB/F,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAwC;IAExC,IAAI,KAAK,CAAC,qBAAqB;QAC7B,o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WAAW,KAAK,QAAQ,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,SAAS,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC;QACzE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,wDAAwD,CACzD,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type {\n PrincipalPolicyCurrentResolver as CurrentPolicyResolver,\n ResolvedPrincipalPolicyCurrent,\n} from \"../principals/runtimePolicyRecovery\";\n\ninterface CurrentOrganizationAuthorityInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly organizationReference?: ReferencedPrincipalHead | null | undefined;\n readonly resolveCurrentPolicy: CurrentPolicyResolver;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/** One directory view with bounded, authenticated current artifacts for its groups. */\nexport async function loadCurrentOrganizationAuthority(\n input: CurrentOrganizationAuthorityInput,\n) {\n if (input.organizationReference)\n assertReferenceScope(\n input.organizationReference,\n \"organization\",\n input.organizationId,\n );\n const recoveryBatch = input.recoveryBatch ?? {};\n const resolve = (reference?: ReferencedPrincipalHead | null) =>\n input.resolveCurrentPolicy({\n organizationId: input.organizationId,\n reference: reference ?? undefined,\n preferLocalCurrent: true,\n recoveryBatch,\n stillCurrent: input.stillCurrent,\n });\n const directory = await resolve(input.organizationReference);\n await assertExactCurrent(\n directory,\n input.organizationReference ?? directory.policy.state,\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.current.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization current policy payload is outside its scope\",\n );\n const adminHead = requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n );\n const admins = await resolve(adminHead);\n await assertExactCurrent(admins, adminHead);\n assertDirectoryDependency(admins, directory);\n const stillCurrent = () =>\n input.stillCurrent() && directory.stillCurrent() && admins.stillCurrent();\n const validate = async (value: ResolvedPrincipalPolicyCurrent) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: [],\n policies: [...value.dependencies, value.policy],\n stillCurrent: () => stillCurrent() && value.stillCurrent(),\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && value.stillCurrent(),\n );\n };\n await validate(admins);\n return {\n admins,\n descriptor,\n directory,\n stillCurrent,\n async readGroup(groupId: string, reference?: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const head = requireOrganizationGroupHead(descriptor, groupId);\n const selected = reference ?? head;\n assertReferenceScope(selected, \"group\", groupId);\n const result =\n groupId === descriptor.adminGroupId &&\n principalHeadMatchesReference(admins.policy.state, selected)\n ? admins\n : await resolve(selected);\n await assertExactCurrent(result, head);\n assertDirectoryDependency(result, directory);\n if (groupId !== descriptor.adminGroupId)\n assertAdminsDependency(result, adminHead);\n await validate(result);\n return result;\n },\n };\n}\n\nfunction assertReferenceScope(\n reference: ReferencedPrincipalHead,\n principalType: ReferencedPrincipalHead[\"principalType\"],\n principalId: string,\n) {\n if (\n reference.principalType !== principalType ||\n reference.principalId !== principalId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n}\n\nasync function assertExactCurrent(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n assertProjectionVerificationCurrent(value.stillCurrent);\n await assertCurrentMatchesVerifiedPolicy(value);\n if (!principalHeadMatchesReference(value.policy.state, expected))\n throw new ProjectionDependencyUnavailableError(\n \"Current policy changed from the selected organization directory\",\n );\n assertProjectionVerificationCurrent(value.stillCurrent);\n}\n\nfunction assertDirectoryDependency(\n value: ResolvedPrincipalPolicyCurrent,\n directory: ResolvedPrincipalPolicyCurrent,\n) {\n const dependency = value.dependencies.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === directory.policy.principalId,\n );\n if (\n !dependency ||\n !principalHeadMatchesReference(dependency.state, directory.policy.state)\n )\n throw new ProjectionDependencyUnavailableError(\n \"Current policy belongs to a changed organization directory\",\n );\n}\n\nfunction assertAdminsDependency(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n const authority = value.dependencies.find(\n (policy) =>\n policy.principalType === \"group\" &&\n policy.principalId === expected.principalId,\n );\n if (!authority || !principalHeadMatchesReference(authority.state, expected))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Current group policy omits its exact Admins dependency\",\n );\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
3
2
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
4
3
|
import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
|
|
4
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
5
5
|
import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
|
|
6
6
|
import { assertMetadataRootBinding } from "./groupMetadataRootBinding.js";
|
|
7
7
|
/** Authenticate metadata-root grants with current policies and only its cited predecessors. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currentGroupMetadataAuthority.js","sourceRoot":"","sources":["currentGroupMetadataAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"currentGroupMetadataAuthority.js","sourceRoot":"","sources":["currentGroupMetadataAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAClG,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAEvE,+FAA+F;AAC/F,MAAM,UAAU,2CAA2C,CACzD,KAGC;IAED,OAAO,KAAK,EACV,KAAmC,EACnC,qBAA+C,EAChC,EAAE;QACjB,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC;YACvD,GAAG,KAAK;YACR,qBAAqB;SACtB,CAAC,CAAC;QACH,MAAM,mDAAmD,CAAC;YACxD,SAAS;YACT,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC,KAAK,EAAE,qBAAqB,CAAC,CAAC;IACnC,CAAC,CAAC;AACJ,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,mDAAmD,CAAC,KAMnE;IACC,OAAO,KAAK,EACV,KAAmC,EACnC,qBAA+C,EAChC,EAAE;QACjB,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,C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AE,CAAC,YAAY,EAAE,IAAI,MAAM,CAAC,YAAY,EAAE,IAAI,OAAO,CAAC,YAAY,EAAE,CACxE,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { assertMetadataRootBinding } from \"./groupMetadataRootBinding\";\n\n/** Authenticate metadata-root grants with current policies and only its cited predecessors. */\nexport function createCurrentGroupMetadataContainerVerifier(\n input: Omit<\n Parameters<typeof loadCurrentOrganizationAuthority>[0],\n \"organizationReference\"\n >,\n) {\n return async (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const authority = await loadCurrentOrganizationAuthority({\n ...input,\n organizationReference,\n });\n await createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n })(state, organizationReference);\n };\n}\n\n/** Reuse one mutation's verified authority without broadening its lease or scope. */\nexport function createSelectedCurrentGroupMetadataContainerVerifier(input: {\n readonly authority: Awaited<\n ReturnType<typeof loadCurrentOrganizationAuthority>\n >;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n}) {\n return async (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead,\n ): Promise<void> => {\n const { authority } = input;\n const stillCurrent = () => input.stillCurrent() && authority.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n if (organizationReference) {\n if (\n organizationReference.principalType !== \"organization\" ||\n organizationReference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n if (\n !principalHeadMatchesReference(\n authority.directory.policy.state,\n organizationReference,\n )\n )\n throw new ProjectionDependencyUnavailableError(\n \"Metadata root belongs to a changed organization directory\",\n );\n }\n const { adminGroupId, memberGroupId } = authority.descriptor;\n const citation = (groupId: string) =>\n state.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === groupId,\n );\n const admins = await authority.readGroup(\n adminGroupId,\n citation(adminGroupId),\n );\n const members = await authority.readGroup(\n memberGroupId,\n citation(memberGroupId),\n );\n assertMetadataRootBinding({\n organizationId: input.organizationId,\n authority: {\n descriptor: authority.descriptor,\n adminGroupId,\n memberGroupId,\n adminPolicy: admins.policy,\n },\n members,\n state,\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && admins.stillCurrent() && members.stillCurrent(),\n );\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
2
1
|
import { createProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/userKeyResolver.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
3
3
|
import { createCurrentGroupMetadataContainerVerifier } from "./currentGroupMetadataAuthority.js";
|
|
4
4
|
import { createGroupMetadataAccess, } from "./groupMetadataAccess.js";
|
|
5
5
|
export function createRuntimeGroupMetadataAccess(runtime, organizationId, stillCurrent, verifyMetadataContainer, currentRecovery) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupMetadataRuntime.js","sourceRoot":"","sources":["groupMetadataRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"groupMetadataRuntime.js","sourceRoot":"","sources":["groupMetadataRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CA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QAC9B,cAAc;QACd,wBAAwB,EAAE,+BAA+B,CAAC,OAAO,CAAC;QAClE,eAAe;QACf,YAAY;QACZ,+BAA+B,EAAE,MAAM;KACxC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,sBAAsB,CAC7B,OAAmD;IAEnD,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { EncapsulationKeyPair } from \"@tearleads/crypto\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { PrincipalPolicyService } from \"../../principals/principalPolicyService\";\nimport type { PrincipalPolicyCurrentResolver } from \"../../principals/runtimePolicyRecovery\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\nimport {\n createGroupMetadataAccess,\n type GroupMetadataAccessInput,\n} from \"./groupMetadataAccess\";\n\ninterface GroupMetadataRuntime {\n readonly apiClient: GroupMetadataAccessInput[\"apiClient\"] &\n PrincipalPolicyReadApi;\n readonly crypto: {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n };\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: {\n readonly log: (message: string) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n };\n}\n\nexport function createRuntimeGroupMetadataAccess(\n runtime: GroupMetadataRuntime,\n organizationId: string,\n stillCurrent?: () => boolean,\n verifyMetadataContainer?: GroupMetadataAccessInput[\"verifyMetadataContainer\"],\n currentRecovery?: {\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver | undefined;\n readonly recoveryBatch: object;\n },\n) {\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!targetSecretKey) throw new Error(\"Group metadata identity is locked\");\n // The signed metadata projection selects exact citations. Reuse matching\n // private evidence with its dependencies and pins before bounded online reads.\n const warmer = runtime.principalPolicies.createWarmer({\n preferLocalCurrent: true,\n });\n const resolveCurrentPolicy =\n currentRecovery?.resolveCurrentPolicy ??\n runtime.principalPolicies.createCurrentPolicyResolver();\n const authorityInput = {\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: stillCurrent ?? (() => true),\n };\n return createGroupMetadataAccess({\n verifyMetadataContainer:\n verifyMetadataContainer ??\n createCurrentGroupMetadataContainerVerifier({\n ...authorityInput,\n resolveCurrentPolicy: requireCurrentResolver(resolveCurrentPolicy),\n recoveryBatch: currentRecovery?.recoveryBatch,\n }),\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: warmer,\n });\n}\n\nfunction requireCurrentResolver(\n resolve: PrincipalPolicyCurrentResolver | undefined,\n) {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n return resolve;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/
|
|
1
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
2
2
|
import { createCurrentGroupMetadataContainerVerifier } from "./currentGroupMetadataAuthority.js";
|
|
3
3
|
/** Remote metadata destinations require the same private authority as name reads. */
|
|
4
4
|
export async function verifyRuntimeGroupMetadataAuthority(input) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtimeGroupMetadataAuthority.js","sourceRoot":"","sources":["runtimeGroupMetadataAuthority.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"runtimeGroupMetadataAuthority.js","sourceRoot":"","sources":["runtimeGroupMetadataAuthority.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAE9F,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAMzD;IACC,MAAM,oBAAoB,GACxB,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IAChE,IAAI,CAAC,oBAAoB;QACvB,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,MAAM,2CAA2C,CAAC;QAChD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB;QACpB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\n\n/** Remote metadata destinations require the same private authority as name reads. */\nexport async function verifyRuntimeGroupMetadataAuthority(input: {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n readonly organizationReference?: ReferencedPrincipalHead | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const resolveCurrentPolicy =\n input.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n await createCurrentGroupMetadataContainerVerifier({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n })(input.state, input.organizationReference);\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/
|
|
1
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
2
2
|
import { hydrateCurrentOrganizationGroupNames } from "./currentOrganizationGroupNames.js";
|
|
3
3
|
/** Verify names against the signed directory before projecting decrypted labels. */
|
|
4
4
|
export async function hydrateOrganizationGroupNames(input) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationGroupNames.js","sourceRoot":"","sources":["organizationGroupNames.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"organizationGroupNames.js","sourceRoot":"","sources":["organizationGroupNames.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,oCAAoC,EAAE,MAAM,iCAAiC,CAAC;AAGvF,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,KAaC;IAED,IAAI,CAAC,KAAK,CAAC,oBAAoB;QAC7B,MAAM,IAAI,oCAAoC,CAC5C,4CAA4C,CAC7C,CAAC;IACJ,OAAO,oCAAoC,CAAC;QAC1C,GAAG,KAAK;QACR,qBAAqB,EAAE,KAAK,CAAC,2BAA2B;QACxD,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { OrganizationDirectoryAndGroups } from \"../readModel\";\nimport { hydrateCurrentOrganizationGroupNames } from \"./currentOrganizationGroupNames\";\nimport type { DirectoryGroupWalkInput } from \"./groupNameUniqueness\";\n\n/** Verify names against the signed directory before projecting decrypted labels. */\nexport async function hydrateOrganizationGroupNames(\n input: Omit<DirectoryGroupWalkInput, \"descriptor\" | \"externalAuthority\"> & {\n readonly directory: OrganizationDirectoryAndGroups;\n readonly organizationPolicyReference?: ReferencedPrincipalHead | null;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n readonly createCurrentNameReader?: Parameters<\n typeof hydrateCurrentOrganizationGroupNames\n >[0][\"createCurrentNameReader\"];\n readonly resolveCurrentPolicy?:\n | Parameters<\n typeof hydrateCurrentOrganizationGroupNames\n >[0][\"resolveCurrentPolicy\"]\n | undefined;\n },\n): Promise<OrganizationDirectoryAndGroups> {\n if (!input.resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group names require private paged recovery\",\n );\n return hydrateCurrentOrganizationGroupNames({\n ...input,\n organizationReference: input.organizationPolicyReference,\n resolveCurrentPolicy: input.resolveCurrentPolicy,\n });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
3
3
|
/**
|
|
4
4
|
* Client calls that leave the server unchanged. Every other call counts as a
|
|
5
5
|
* write (the group policy commit in either form, the share, a recitation), so
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupShareReplan.js","sourceRoot":"","sources":["groupShareReplan.ts"],"names":[],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AC,CAAC;YACxB,CAAC,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAKhD,KAAY,EACZ,OAAiD;IAEjD,IAAI,KAAK,GAAG,KAAK,CAAC;IAClB,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC;YACnB,GAAG,KAAK;YACR,SAAS,EAAE,YAAY,CAAC,KAAK,CAAC,SAAS,EAAE,GAAG,EAAE;gBAC5C,KAAK,GAAG,IAAI,CAAC;YACf,CAAC,CAAC;SACH,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,IAAI,CAAC,oBAAoB,CAAC,KAAK,CAAC;YAAE,MAAM,KAAK,CAAC;IACzD,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClD,KAAK,CAAC,SAAS,CAAC,8BAA8B,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAClE,OAAO,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,kBAAkB,EAAE,SAAS,EAAE,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\n\n/**\n * Client calls that leave the server unchanged. Every other call counts as a\n * write (the group policy commit in either form, the share, a recitation), so\n * a write method added later blocks the replan rather than slipping past it.\n * Recovery settles an earlier journaled mutation, never this share's.\n */\nfunction isReadOnlyCall(method: string): boolean {\n return (\n /^(evict|get|list)[A-Z]/u.test(method) ||\n method === \"recoverPendingPrincipalMutation\"\n );\n}\n\ninterface ReplannableGroupShareInput<Api extends object> {\n readonly apiClient: Api & {\n evictContainerWriterProjection(containerId: string): void;\n };\n readonly containerId: string;\n readonly previousProjection?: ContainerWriterProjectionResponse | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/**\n * A cached path can trail a pin this device advanced (a rollback), or its\n * history a checkpoint another workflow pinned meanwhile (a retryable missing\n * dependency). A fresh projection resolves both and is held to the same pins.\n */\nfunction isStaleShareEvidence(error: unknown): boolean {\n return (\n error instanceof ProjectionDependencyUnavailableError ||\n (error instanceof KeyingVerificationError && error.code === \"rollback\")\n );\n}\n\nfunction recordWrites<Api extends object>(api: Api, onWrite: () => void): Api {\n return new Proxy(api, {\n get(target, property) {\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const bound = (...args: unknown[]): unknown =>\n Reflect.apply(value, target, args);\n if (typeof property === \"string\" && isReadOnlyCall(property))\n return bound;\n return (...args: unknown[]): unknown => {\n onWrite();\n return bound(...args);\n };\n },\n });\n}\n\n/**\n * Plan a group share once more from a fresh projection when its evidence was\n * stale, as a user share and a create do, but only while no remote write (the\n * group grant policy or the share itself) has been submitted: a write may have\n * landed, and replaying it is not this retry's call. A second stale plan fails.\n */\nexport async function shareWithGroupReplanningOnce<\n Api extends object,\n Input extends ReplannableGroupShareInput<Api>,\n Result,\n>(\n input: Input,\n attempt: (input: Input) => Promise<Result | null>,\n): Promise<Result | null> {\n let wrote = false;\n try {\n return await attempt({\n ...input,\n apiClient: recordWrites(input.apiClient, () => {\n wrote = true;\n }),\n });\n } catch (error) {\n if (wrote || !isStaleShareEvidence(error)) throw error;\n }\n if (input.stillCurrent?.() === false) return null;\n input.apiClient.evictContainerWriterProjection(input.containerId);\n return attempt({ ...input, previousProjection: undefined });\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
2
1
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
3
2
|
import { requireOrganizationGroupHead } from "../../../data/principals/organizationAuthorityDescriptor.js";
|
|
3
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
4
4
|
import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
|
|
5
5
|
import { loadLocalOrganizationPolicyReference } from "../readModel/localReadModelDetails.js";
|
|
6
6
|
import { createLeaveRequestMembershipCheck, } from "./leaveRequestMembership.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"leaveRequestMembersEvidence.js","sourceRoot":"","sources":["leaveRequestMembersEvidence.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"leaveRequestMembersEvidence.js","sourceRoot":"","sources":["leaveRequestMembersEvidence.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AACxG,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAC1F,OAAO,EACL,iCAAiC,GAElC,MAAM,0BAA0B,CAAC;AAQlC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAA2B;IAE3B,MAAM,oBAAoB,GACxB,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IAChE,IAAI,CAAC,oBAAoB;QACvB,MAAM,IAAI,oCAAoC,CAC5C,iDAAiD,CAClD,CAAC;IACJ,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC;QACvD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB;QACpB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,mCAAmC,CAAC,S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S,CAAC,UAAU,EACpB,SAAS,CAAC,UAAU,CAAC,aAAa,CACnC,CAAC;QACJ,CAAC;QACD,eAAe,EAAE,OAAO;YACtB,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,EAAE;gBAC5B,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC;oBAC7B,cAAc,EAAE,KAAK,CAAC,cAAc;oBACpC,SAAS,EAAE,IAAI;oBACf,kBAAkB,EAAE,IAAI;oBACxB,YAAY,EAAE,KAAK,CAAC,YAAY;oBAChC,WAAW,EAAE,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE;iBAClE,CAAC,CAAC;gBACH,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;gBAC3D,IAAI,CAAC,QAAQ,CAAC,WAAW;oBACvB,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;gBAC9D,OAAO,QAAQ,CAAC,WAAW,CAAC;YAC9B,CAAC;YACH,CAAC,CAAC,SAAS;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { OrganizationLeaveRequestMembersHead } from \"@tearleads/validators/util\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { requireOrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { loadLocalOrganizationPolicyReference } from \"../readModel/localReadModelDetails\";\nimport {\n createLeaveRequestMembershipCheck,\n type LeaveRequestMembershipCheck,\n} from \"./leaveRequestMembership\";\n\ninterface MembersEvidenceInput {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * The organization's current Members head as the member's own device\n * discovers and verifies it now, for a leave request to cite.\n */\nexport async function loadCurrentMembersHead(\n input: MembersEvidenceInput,\n): Promise<OrganizationLeaveRequestMembersHead> {\n const resolveCurrentPolicy =\n input.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Asking to leave requires private paged recovery\",\n );\n const authority = await loadCurrentOrganizationAuthority({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(authority.stillCurrent);\n const head = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.memberGroupId,\n );\n return {\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n };\n}\n\n/**\n * Checks leave requests against the Members head in the organization policy\n * this device's read model selected, verified exactly through the private\n * paged verifier (from local evidence when it has it), and walks verified\n * Members history the same way when a request cites an earlier key epoch.\n */\nexport function createRuntimeLeaveRequestMembershipCheck(\n input: MembersEvidenceInput & { readonly currentUserId: string },\n): LeaveRequestMembershipCheck {\n const resolve = input.runtime.principalPolicies.createCurrentPolicyResolver();\n return createLeaveRequestMembershipCheck({\n async loadMembersHead() {\n if (!resolve) return null;\n const organizationReference = await loadLocalOrganizationPolicyReference({\n currentUserId: input.currentUserId,\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n principalId: input.organizationId,\n principalType: \"organization\",\n });\n if (!organizationReference) return null;\n const authority = await loadCurrentOrganizationAuthority({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n organizationReference,\n resolveCurrentPolicy: resolve,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(authority.stillCurrent);\n return requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.memberGroupId,\n );\n },\n loadHistoryPage: resolve\n ? async (head, beforeVersion) => {\n const resolved = await resolve({\n organizationId: input.organizationId,\n reference: head,\n preferLocalCurrent: true,\n stillCurrent: input.stillCurrent,\n historyPage: beforeVersion === undefined ? {} : { beforeVersion },\n });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n if (!resolved.historyPage)\n throw new Error(\"Verified Members history page is missing\");\n return resolved.historyPage;\n }\n : undefined,\n });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
2
1
|
import { reportKeyingVerificationErrorInCauseChain } from "../../../data/keyingProjectionVerification/error.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
3
3
|
import { loadLocalOrganizationPolicyReference } from "../readModel/localReadModelDetails.js";
|
|
4
4
|
import { captureOrganizationPresentationAccessAttempt, isOrganizationPresentationAccessAttemptCurrent, isOrganizationPresentationAccessReadable, } from "../readModel/organizationPresentationAccessState.js";
|
|
5
5
|
import { isOrganizationPresentationAccessDeniedFailure } from "../readModel/organizationPresentationFailures.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadPolicyHistoryDetails.js","sourceRoot":"","sources":["loadPolicyHistoryDetails.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"loadPolicyHistoryDetails.js","sourceRoot":"","sources":["loadPolicyHistoryDetails.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yCAAyC,EAAE,MAAM,kDAAkD,CAAC;AAE7G,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAKlG,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAC1F,OAAO,EACL,4CAA4C,EAC5C,8CAA8C,EAC9C,wCAAwC,GACzC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,6CAA6C,EAAE,MAAM,+CAA+C,CAAC;AAC9G,OAAO,EAAE,sCAAsC,EAAE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AAE,CAAC,CAAC;QACrD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IACE,CAAC,KAAK,CAAC,SAAS;YAChB,KAAK,YAAY,oCAAoC;YAErD,OAAO,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC/B,MAAM,yCAAyC,CAC7C,KAAK,EACL,KAAK,CAAC,sBAAsB,EAC5B;YACE,QAAQ,EAAE,KAAK,CAAC,cAAc;YAC9B,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,kCAAkC;YAC7C,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CACF,CAAC;QACF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/keyingProjectionVerification/error\";\nimport type { ReferencedPrincipalPolicyWarmer } from \"../../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { RecoveredPrincipalHistoryPage } from \"../../principals/historyRecovery/loadRecoveredPrincipalHistoryPage\";\nimport { loadLocalOrganizationPolicyReference } from \"../readModel/localReadModelDetails\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n} from \"../readModel/organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"../readModel/organizationPresentationFailures\";\nimport { buildDetailedOrganizationPolicyHistory } from \"./organizationPolicyHistoryDetails\";\nimport { denyPolicyHistoryAccess } from \"./policyHistoryAccessDenial\";\nimport {\n cachePolicyHistory,\n loadCachedPolicyHistory,\n} from \"./policyHistoryCache\";\nimport type { OrganizationPolicyHistory } from \"./policyHistoryTypes\";\n\nexport async function loadPolicyHistoryDetails(input: {\n apiClient: Pick<ApiClient, \"getOrganizationPolicyHistoryResult\">;\n currentUserId: string;\n domainScope: DomainScope;\n execSql: ExecSql;\n organizationId: string;\n head: ReferencedPrincipalHead;\n page: RecoveredPrincipalHistoryPage;\n history: OrganizationPolicyHistory;\n resolveHistory: NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"]\n >;\n stillCurrent: () => boolean;\n online: boolean;\n olderPage: boolean;\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n // Forwarded to denyPolicyHistoryAccess to report failed durable cleanup.\n logError: (message: string | Error, cause?: unknown) => void;\n}): Promise<OrganizationPolicyHistory | null> {\n const access = { ...input, requesterUserId: input.currentUserId };\n const attempt = captureOrganizationPresentationAccessAttempt(\n access,\n \"readModel\",\n );\n const current = () =>\n input.stillCurrent() &&\n isOrganizationPresentationAccessAttemptCurrent(access, attempt) &&\n isOrganizationPresentationAccessReadable(access, \"readModel\");\n if (!current()) return null;\n const beforeVersion = (input.page.entries.at(-1)?.state.version ?? 0) + 1;\n const cache = {\n domainScope: input.domainScope,\n access,\n stateHash: input.head.stateHash,\n beforeVersion,\n };\n const retain = async (history: OrganizationPolicyHistory) => {\n const latest = await loadLocalOrganizationPolicyReference({\n ...input,\n principalType: \"organization\",\n principalId: input.organizationId,\n });\n return current() && latest?.stateHash === input.head.stateHash\n ? history\n : null;\n };\n const cached = loadCachedPolicyHistory(cache);\n if (cached) return retain(cached);\n if (!input.online) return retain(input.history);\n try {\n const response = await input.apiClient.getOrganizationPolicyHistoryResult(\n input.organizationId,\n input.head.stateHash,\n { beforeVersion, reportErrors: false },\n );\n if (!input.stillCurrent()) return null;\n if (!response.ok) {\n if (isOrganizationPresentationAccessDeniedFailure(response)) {\n await denyPolicyHistoryAccess(access);\n return null;\n }\n response.report();\n if (input.olderPage) throw new Error(response.message);\n return retain(input.history);\n }\n const history = await buildDetailedOrganizationPolicyHistory({\n head: input.head,\n page: input.page,\n evidence: response.data,\n resolveHistory: input.resolveHistory,\n stillCurrent: current,\n });\n const retained = await retain(history);\n if (retained === history)\n cachePolicyHistory({ ...cache, attempt, history });\n return retained;\n } catch (error) {\n if (\n !input.olderPage &&\n error instanceof ProjectionDependencyUnavailableError\n )\n return retain(input.history);\n await reportKeyingVerificationErrorInCauseChain(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.organizationId,\n objectKind: \"principal\",\n operation: \"organization.policy_history.load\",\n organizationId: input.organizationId,\n },\n );\n throw error;\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
3
2
|
import { externalAuthorityCouldAuthorize, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../../data/principals/principalPolicyAdminSigners.js";
|
|
3
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
4
4
|
import { collectPrincipalPolicySignerPublicKeys, principalPolicyStates, } from "../policyVerification.js";
|
|
5
5
|
function getBundleReferenceFailure(reference, bundle) {
|
|
6
6
|
const states = principalPolicyStates(bundle);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,GAC1D,MAAM,sDAAsD,CAAC;AAG9D,OAAO,EACL,sCAAsC,EAEtC,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAO/B,SAAS,yBAAyB,CAChC,SA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AAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../policyVerification\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,GAC1D,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAGlG,OAAO,EACL,sCAAsC,EAEtC,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAO/B,SAAS,yBAAyB,CAChC,SAA2C,EAC3C,MAAqC;IAErC,MAAM,MA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,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../policyVerification\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
2
1
|
import { rethrowKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
|
|
3
2
|
import { assertProjectionVerificationCurrent, isProjectionVerificationCancelledError, } from "../../data/keyingProjectionVerification/types.js";
|
|
4
3
|
import { directoryHistoryProtection } from "../../data/principals/principalHistoryScopeProtection.js";
|
|
5
4
|
import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
|
|
5
|
+
import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
|
|
6
6
|
import { errorMessage } from "../../data/shared/errorMessage.js";
|
|
7
7
|
import { apiPrincipalPolicyPageReader, } from "./principalPolicyHistoryReader.js";
|
|
8
8
|
import { createPrincipalPolicyCurrentResolver, } from "./runtimePolicyRecovery.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyService.js","sourceRoot":"","sources":["principalPolicyService.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GAEvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAG9D,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,oCAAoC,GAGrC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAc1F,MAAM,UAAU,8BAA8B;IAC5C,OAAO,EAAE,CAAC;AACZ,CAAC;AAaD,IAAI,eAE6B,CAAC;AAElC;;;;;;;GAOG;AACH,MAAM,OAAO,sBAAsB;IACxB,SAAS,CAA+B;IAEjD;QACE,eAAe,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC;IACnD,CAAC;IAED,YAAY,aAA2C;QACrD,IAAI,CAAC,SAAS,GAAG,aAAa,CAAC;IACjC,CAAC;IAED,mEAAmE;IACnE,2BAA2B;QACzB,OAAO,oCAAoC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC9D,CAAC;IAED,wEAAwE;IACxE,+BAA+B;QAC7B,OAAO,qCAAqC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC/D,CAAC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;YAClD,OAAO,MAAM,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,MAAM,GAAG,KAAK,CAAC;QACjB,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { rethrowKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n isProjectionVerificationCancelledError,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { directoryHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport { errorMessage } from \"../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalCurrentInput } from \"./acknowledgements/acknowledgedPrincipalCurrents\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyPageReader,\n} from \"./principalPolicyHistoryReader\";\nimport {\n createPrincipalPolicyCurrentResolver,\n type PrincipalPolicyCollaborators,\n type PrincipalPolicyCurrentResolver,\n} from \"./runtimePolicyRecovery\";\nimport { createProjectionPolicyHistoryResolver } from \"./runtimeProjectionPolicyRecovery\";\n\ntype PolicyResolver = NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveReference\"]\n>;\n\n/**\n * The token of one reconciliation pass or user workflow. Every warmer created\n * with it shares one authenticated directory view, discovered once; the view\n * dies with the token, an organization hint, a durable pin past it, or the end\n * of its producing lease. Mint one at the pass or workflow root.\n */\nexport type PrincipalPolicyOperation = object;\n\nexport function createPrincipalPolicyOperation(): PrincipalPolicyOperation {\n return {};\n}\n\nexport interface PrincipalPolicyWarmerOptions {\n readonly preferLocalCurrent?: boolean;\n readonly operation?: PrincipalPolicyOperation | undefined;\n}\n\n/** A runtime snapshot carrying the policy service its producer bound, and its executor. */\nexport interface PrincipalPolicyRuntime {\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nlet collaboratorsOf: (\n service: PrincipalPolicyService,\n) => PrincipalPolicyCollaborators;\n\n/**\n * Principal Policy: recovers, verifies, and prefetches the principal policy\n * evidence that projections cite. One instance binds one runtime snapshot's\n * API client, executor, online state, reporter, logger, trusted-identity\n * resolver, and the history-protection lease that snapshot bound; every view\n * derived from the snapshot shares it. The collaborators sit in a private\n * field, so a public runtime view carrying the service exposes no custody.\n */\nexport class PrincipalPolicyService {\n readonly #policies: PrincipalPolicyCollaborators;\n\n static {\n collaboratorsOf = (service) => service.#policies;\n }\n\n constructor(collaborators: PrincipalPolicyCollaborators) {\n this.#policies = collaborators;\n }\n\n /** Undefined without history custody or a paged history reader. */\n createCurrentPolicyResolver(): PrincipalPolicyCurrentResolver | undefined {\n return createPrincipalPolicyCurrentResolver(this.#policies);\n }\n\n /** Undefined without history custody or a projection history reader. */\n createProjectionHistoryResolver(): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n return createProjectionPolicyHistoryResolver(this.#policies);\n }\n\n /**\n * One warmer serves one workflow operation: either the `operation` its root\n * minted, or a fresh one of its own. Its projection collections share one\n * authenticated directory view per operation. Prefetch is best-effort; exact\n * resolution still rejects unavailable evidence.\n */\n createWarmer(\n options: PrincipalPolicyWarmerOptions = {},\n ): ReferencedPrincipalPolicyWarmer {\n const resolve = this.createCurrentPolicyResolver();\n const operation = options.operation ?? createPrincipalPolicyOperation();\n const resolveReference: PolicyResolver = async (input) => {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Principal policies require private paged recovery\",\n );\n return resolve({\n ...input,\n recoveryBatch: input.recoveryBatch ?? operation,\n preferLocalCurrent: options.preferLocalCurrent,\n });\n };\n const policies = this.#policies;\n return Object.assign(\n (input: Parameters<ReferencedPrincipalPolicyWarmer>[0]) =>\n prefetchReferences(policies, resolveReference, input),\n {\n resolveReference,\n resolveProjectionHistory: this.createProjectionHistoryResolver(),\n },\n );\n }\n}\n\nasync function prefetchReferences(\n policies: PrincipalPolicyCollaborators,\n resolve: PolicyResolver,\n input: Parameters<ReferencedPrincipalPolicyWarmer>[0],\n): Promise<void> {\n for (const reference of input.references) {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await resolve({ ...input, reference });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return;\n // Recovery already reports signature/authority failures. Keep them fatal.\n rethrowKeyingVerificationError(error);\n policies.util.log?.(\n `Principal policy prefetch: ${reference.principalId}: ${errorMessage(error)}`,\n );\n }\n }\n}\n\nexport interface CurrentPrincipalMutationLeaseContext {\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly stillCurrent: () => boolean;\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly directoryRecovery: (\n current: PrincipalPolicyPageCurrent,\n ) => AcknowledgedPrincipalCurrentInput[\"recovery\"];\n}\n\nexport type CurrentPrincipalMutationLease = <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n) => Promise<T>;\n\n/**\n * One lifetime fence and private custody boundary for every current-policy\n * mutation. It hands the snapshot's private history protection to `work`, so\n * it stays off the class and out of the package root: a public runtime view\n * carrying the service cannot reach it.\n */\nexport function createCurrentPrincipalMutationLease(\n service: PrincipalPolicyService,\n): CurrentPrincipalMutationLease | undefined {\n const policies = collaboratorsOf(service);\n const lease = policies.withPrincipalHistoryProtection;\n const resolveCurrentPolicy = createPrincipalPolicyCurrentResolver(policies);\n const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);\n if (!lease || !resolveCurrentPolicy || !historyReader) return undefined;\n return async <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n ): Promise<T> =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n let active = true;\n const stillCurrent = () => active && leaseCurrent() && callerCurrent();\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery: (current) => ({\n historyReader,\n expectedHead: principalPolicyReferenceFromBundle(current),\n protection: directoryHistoryProtection(protection),\n resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,\n }),\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n active = false;\n }\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyService.js","sourceRoot":"","sources":["principalPolicyService.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GAEvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAG9D,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,oCAAoC,GAGrC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAc1F,MAAM,UAAU,8BAA8B;IAC5C,OAAO,EAAE,CAAC;AACZ,CAAC;AAaD,IAAI,eAE6B,CAAC;AAElC;;;;;;;GAOG;AACH,MAAM,OAAO,sBAAsB;IACxB,SAAS,CAA+B;IAEjD;QACE,eAAe,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC;IACnD,CAAC;IAED,YAAY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,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;oBAC/B,aAAa;oBACb,YAAY,EAAE,kCAAkC,CAAC,OAAO,CAAC;oBACzD,UAAU,EAAE,0BAA0B,CAAC,UAAU,CAAC;oBAClD,0BAA0B,EAAE,QAAQ,CAAC,0BAA0B;iBAChE,CAAC;aACH,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,OAAO,MAAM,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,MAAM,GAAG,KAAK,CAAC;QACjB,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport { rethrowKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n isProjectionVerificationCancelledError,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { directoryHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { errorMessage } from \"../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalCurrentInput } from \"./acknowledgements/acknowledgedPrincipalCurrents\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyPageReader,\n} from \"./principalPolicyHistoryReader\";\nimport {\n createPrincipalPolicyCurrentResolver,\n type PrincipalPolicyCollaborators,\n type PrincipalPolicyCurrentResolver,\n} from \"./runtimePolicyRecovery\";\nimport { createProjectionPolicyHistoryResolver } from \"./runtimeProjectionPolicyRecovery\";\n\ntype PolicyResolver = NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveReference\"]\n>;\n\n/**\n * The token of one reconciliation pass or user workflow. Every warmer created\n * with it shares one authenticated directory view, discovered once; the view\n * dies with the token, an organization hint, a durable pin past it, or the end\n * of its producing lease. Mint one at the pass or workflow root.\n */\nexport type PrincipalPolicyOperation = object;\n\nexport function createPrincipalPolicyOperation(): PrincipalPolicyOperation {\n return {};\n}\n\nexport interface PrincipalPolicyWarmerOptions {\n readonly preferLocalCurrent?: boolean;\n readonly operation?: PrincipalPolicyOperation | undefined;\n}\n\n/** A runtime snapshot carrying the policy service its producer bound, and its executor. */\nexport interface PrincipalPolicyRuntime {\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nlet collaboratorsOf: (\n service: PrincipalPolicyService,\n) => PrincipalPolicyCollaborators;\n\n/**\n * Principal Policy: recovers, verifies, and prefetches the principal policy\n * evidence that projections cite. One instance binds one runtime snapshot's\n * API client, executor, online state, reporter, logger, trusted-identity\n * resolver, and the history-protection lease that snapshot bound; every view\n * derived from the snapshot shares it. The collaborators sit in a private\n * field, so a public runtime view carrying the service exposes no custody.\n */\nexport class PrincipalPolicyService {\n readonly #policies: PrincipalPolicyCollaborators;\n\n static {\n collaboratorsOf = (service) => service.#policies;\n }\n\n constructor(collaborators: PrincipalPolicyCollaborators) {\n this.#policies = collaborators;\n }\n\n /** Undefined without history custody or a paged history reader. */\n createCurrentPolicyResolver(): PrincipalPolicyCurrentResolver | undefined {\n return createPrincipalPolicyCurrentResolver(this.#policies);\n }\n\n /** Undefined without history custody or a projection history reader. */\n createProjectionHistoryResolver(): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n return createProjectionPolicyHistoryResolver(this.#policies);\n }\n\n /**\n * One warmer serves one workflow operation: either the `operation` its root\n * minted, or a fresh one of its own. Its projection collections share one\n * authenticated directory view per operation. Prefetch is best-effort; exact\n * resolution still rejects unavailable evidence.\n */\n createWarmer(\n options: PrincipalPolicyWarmerOptions = {},\n ): ReferencedPrincipalPolicyWarmer {\n const resolve = this.createCurrentPolicyResolver();\n const operation = options.operation ?? createPrincipalPolicyOperation();\n const resolveReference: PolicyResolver = async (input) => {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Principal policies require private paged recovery\",\n );\n return resolve({\n ...input,\n recoveryBatch: input.recoveryBatch ?? operation,\n preferLocalCurrent: options.preferLocalCurrent,\n });\n };\n const policies = this.#policies;\n return Object.assign(\n (input: Parameters<ReferencedPrincipalPolicyWarmer>[0]) =>\n prefetchReferences(policies, resolveReference, input),\n {\n resolveReference,\n resolveProjectionHistory: this.createProjectionHistoryResolver(),\n },\n );\n }\n}\n\nasync function prefetchReferences(\n policies: PrincipalPolicyCollaborators,\n resolve: PolicyResolver,\n input: Parameters<ReferencedPrincipalPolicyWarmer>[0],\n): Promise<void> {\n for (const reference of input.references) {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await resolve({ ...input, reference });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return;\n // Recovery already reports signature/authority failures. Keep them fatal.\n rethrowKeyingVerificationError(error);\n policies.util.log?.(\n `Principal policy prefetch: ${reference.principalId}: ${errorMessage(error)}`,\n );\n }\n }\n}\n\nexport interface CurrentPrincipalMutationLeaseContext {\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly stillCurrent: () => boolean;\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly directoryRecovery: (\n current: PrincipalPolicyPageCurrent,\n ) => AcknowledgedPrincipalCurrentInput[\"recovery\"];\n}\n\nexport type CurrentPrincipalMutationLease = <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n) => Promise<T>;\n\n/**\n * One lifetime fence and private custody boundary for every current-policy\n * mutation. It hands the snapshot's private history protection to `work`, so\n * it stays off the class and out of the package root: a public runtime view\n * carrying the service cannot reach it.\n */\nexport function createCurrentPrincipalMutationLease(\n service: PrincipalPolicyService,\n): CurrentPrincipalMutationLease | undefined {\n const policies = collaboratorsOf(service);\n const lease = policies.withPrincipalHistoryProtection;\n const resolveCurrentPolicy = createPrincipalPolicyCurrentResolver(policies);\n const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);\n if (!lease || !resolveCurrentPolicy || !historyReader) return undefined;\n return async <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n ): Promise<T> =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n let active = true;\n const stillCurrent = () => active && leaseCurrent() && callerCurrent();\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery: (current) => ({\n historyReader,\n expectedHead: principalPolicyReferenceFromBundle(current),\n protection: directoryHistoryProtection(protection),\n resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,\n }),\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n active = false;\n }\n });\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
3
2
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
3
|
+
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
4
4
|
import { PrincipalPolicyHistoryReadError } from "../historyRecovery/principalHistoryRecoveryTypes.js";
|
|
5
5
|
import { recoverLeasedScopedPrincipalPolicyHistory, } from "../historyRecovery/recoverScopedPrincipalPolicyHistory.js";
|
|
6
6
|
/** Refusals and invalid evidence must never silently select a cached policy. */
|