@tearleads/client-sdk 0.1.226 → 0.1.231
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/Tearleads.js +1 -1
- package/Tearleads.js.map +1 -1
- package/client/containerContents/documentDiscovery.js +4 -1
- package/client/containerContents/documentDiscovery.js.map +1 -1
- package/client/containerContents/index.d.ts +1 -1
- package/client/containerContents/index.js +4 -2
- package/client/containerContents/index.js.map +1 -1
- package/client/deviceFirst/index.js +1 -1
- package/client/deviceFirst/index.js.map +1 -1
- package/client/documents/index.js +6 -2
- package/client/documents/index.js.map +1 -1
- package/client/identity/index.js +1 -1
- package/client/identity/index.js.map +1 -1
- package/client/identity/userIdentities.d.ts +1 -1
- package/client/identity/userIdentities.js +1 -1
- package/client/identity/userIdentities.js.map +1 -1
- package/client/index.d.ts +2 -0
- package/client/index.js +2 -0
- package/client/index.js.map +1 -1
- package/client/organizations/index.js +1 -1
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/organizationMemberships.d.ts +1 -1
- package/client/organizations/organizationMemberships.js +1 -1
- package/client/organizations/organizationMemberships.js.map +1 -1
- package/client/organizations/principalMutations.js +1 -1
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/organizations/recipientAdmission.d.ts +1 -1
- package/client/organizations/recipientAdmission.js +1 -1
- package/client/organizations/recipientAdmission.js.map +1 -1
- package/client/runtime/apiVersion.js +1 -1
- package/client/runtime/apiVersion.js.map +1 -1
- package/client/runtime/containerContentsRuntime.d.ts +8 -0
- package/client/runtime/containerContentsRuntime.js +14 -0
- package/client/runtime/containerContentsRuntime.js.map +1 -0
- package/client/runtime/database.js +1 -1
- package/client/runtime/database.js.map +1 -1
- package/client/runtime/documentsRuntime.d.ts +5 -0
- package/client/runtime/documentsRuntime.js +10 -0
- package/client/runtime/documentsRuntime.js.map +1 -0
- package/client/runtime/events.js +1 -1
- package/client/runtime/events.js.map +1 -1
- package/client/runtime/network.js +1 -1
- package/client/runtime/network.js.map +1 -1
- package/client/runtime/runtimeIdentityResolution.js +1 -1
- package/client/runtime/runtimeIdentityResolution.js.map +1 -1
- package/client/runtime/syncBillingGate.js +1 -1
- package/client/runtime/syncBillingGate.js.map +1 -1
- package/client/runtime/workflowRuntime.d.ts +5 -2
- package/client/runtime/workflowRuntime.js +6 -2
- package/client/runtime/workflowRuntime.js.map +1 -1
- package/client/securityIncidents/index.d.ts +1 -1
- package/client/securityIncidents/index.js +2 -2
- package/client/securityIncidents/index.js.map +1 -1
- package/client/session/index.js +1 -1
- package/client/session/index.js.map +1 -1
- package/client/session/sessionLoginRefusal.js +1 -1
- package/client/session/sessionLoginRefusal.js.map +1 -1
- package/client/session/sessionRootAuthority.js +1 -1
- package/client/session/sessionRootAuthority.js.map +1 -1
- package/data/documents/shared/projection/freshProjectionRetry.js +1 -1
- package/data/documents/shared/projection/freshProjectionRetry.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/heldContainerHeads.js.map +1 -0
- package/data/keyingProjectionVerification/error.js +1 -57
- package/data/keyingProjectionVerification/error.js.map +1 -1
- package/data/persistence/container-contents/documentContainerProjectionPersistence.d.ts +6 -2
- package/data/persistence/container-contents/documentContainerProjectionPersistence.js +10 -1
- package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
- package/data/persistence/documents/documentDeletionPort.d.ts +28 -0
- package/data/persistence/documents/documentDeletionPort.js +2 -0
- package/data/persistence/documents/documentDeletionPort.js.map +1 -0
- package/data/persistence/documents/documentsPersistence.d.ts +1 -0
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentDeletionPersistence.js +7 -7
- package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
- package/data/persistence/documents/types.d.ts +2 -15
- package/data/persistence/documents/types.js.map +1 -1
- package/data/principals/organizationPolicyRequest.d.ts +12 -0
- package/data/principals/organizationPolicyRequest.js +71 -0
- package/data/principals/organizationPolicyRequest.js.map +1 -0
- package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.d.ts +3 -3
- package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.js +3 -3
- package/data/principals/principalPolicyRequest.js.map +1 -0
- package/{workflows/principals/policyVerification.js → data/principals/principalPolicyVerification.js} +4 -4
- package/data/principals/principalPolicyVerification.js.map +1 -0
- package/data/shared/securityIncidents.d.ts +18 -1
- package/data/shared/securityIncidents.js +58 -1
- package/data/shared/securityIncidents.js.map +1 -1
- package/index.d.ts +5 -5
- package/index.js +3 -3
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/container-contents/hydration/backgroundHydration.js +1 -1
- package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
- package/stores/container-contents/operations/reportShareFailure.js +1 -1
- package/stores/container-contents/operations/reportShareFailure.js.map +1 -1
- package/stores/container-contents/operations/shareOperations.js +1 -1
- package/stores/container-contents/operations/shareOperations.js.map +1 -1
- package/stores/container-contents/systemContainers/systemContainerHydration.js +1 -1
- package/stores/container-contents/systemContainers/systemContainerHydration.js.map +1 -1
- package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js +1 -1
- package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js.map +1 -1
- package/stores/documents/documentStore/persistence.js +1 -0
- package/stores/documents/documentStore/persistence.js.map +1 -1
- package/stores/documents/documentStore/sync/index.js +1 -1
- package/stores/documents/documentStore/sync/index.js.map +1 -1
- package/stores/documents/documentStore/sync/syncRequest.js +1 -0
- package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
- package/workflows/blobs/hydration/hydrationResults.js +2 -1
- package/workflows/blobs/hydration/hydrationResults.js.map +1 -1
- package/workflows/blobs/verification/attachmentDecryptor.js +1 -1
- package/workflows/blobs/verification/attachmentDecryptor.js.map +1 -1
- package/workflows/container-contents/container-state/create/createAdoption.js +1 -1
- package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
- package/workflows/container-contents/container-state/create/createIntentSync.js +1 -1
- package/workflows/container-contents/container-state/create/createIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -1
- package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/organizationHost.d.ts +54 -0
- package/workflows/container-contents/container-state/organizationHost.js +2 -0
- package/workflows/container-contents/container-state/organizationHost.js.map +1 -0
- package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -1
- package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +2 -4
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
- package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
- package/workflows/container-contents/container-state/share/groupShareEpoch.js +1 -2
- package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -1
- package/workflows/container-contents/container-state/types.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/documentMove/documentMoveIntentSync.js +1 -1
- package/workflows/container-contents/documentMove/documentMoveIntentSync.js.map +1 -1
- package/workflows/container-contents/index.d.ts +1 -0
- package/workflows/container-contents/index.js.map +1 -1
- package/workflows/container-contents/info/documentInfo.d.ts +1 -1
- package/workflows/container-contents/info/documentInfo.js +1 -1
- package/workflows/container-contents/info/documentInfo.js.map +1 -1
- package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
- package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
- package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js +1 -2
- package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js.map +1 -1
- package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +3 -4
- package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/runtime.d.ts +5 -0
- package/workflows/container-contents/runtime.js +3 -0
- package/workflows/container-contents/runtime.js.map +1 -1
- package/workflows/container-contents/syncPause/documentRemoval.js +2 -0
- package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
- package/workflows/container-contents/tombstones/documentPurge.js +5 -2
- package/workflows/container-contents/tombstones/documentPurge.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/mutationSubmit.js +1 -1
- package/workflows/containers/child/mutationSubmit.js.map +1 -1
- package/workflows/containers/child/recite.js +1 -1
- package/workflows/containers/child/recite.js.map +1 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js +1 -1
- package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js.map +1 -1
- package/workflows/documents/documentMutationCommit.d.ts +2 -1
- package/workflows/documents/documentMutationCommit.js +1 -0
- package/workflows/documents/documentMutationCommit.js.map +1 -1
- package/workflows/documents/documentPersistGuards.js +2 -1
- package/workflows/documents/documentPersistGuards.js.map +1 -1
- package/workflows/documents/purge/persistedDocumentRemoval.d.ts +2 -1
- package/workflows/documents/purge/persistedDocumentRemoval.js +2 -2
- package/workflows/documents/purge/persistedDocumentRemoval.js.map +1 -1
- package/workflows/documents/runtime.d.ts +5 -0
- package/workflows/documents/runtime.js +1 -0
- package/workflows/documents/runtime.js.map +1 -1
- package/workflows/documents/sync/syncSubmittedResult.js +1 -1
- package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
- package/workflows/documents/syncPlan/syncContentKeys.js +1 -1
- package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
- package/workflows/organizations/containerContentsHost.js +14 -0
- package/workflows/organizations/containerContentsHost.js.map +1 -0
- package/workflows/organizations/groupMetadata/groupMetadataAccess.d.ts +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +1 -1
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
- package/workflows/organizations/groupNames/groupMembershipName.d.ts +1 -1
- package/workflows/organizations/groupNames/groupMembershipName.js +1 -1
- package/workflows/organizations/groupNames/groupMembershipName.js.map +1 -1
- package/workflows/organizations/groupNames/groupNameUniqueness.js +2 -2
- package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
- package/workflows/organizations/groupShare/currentShareGrantMutation.js +1 -1
- package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -1
- package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -1
- package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +1 -1
- package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/groupShare/sharePrincipalPolicy.d.ts +1 -1
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js +2 -2
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/groupShare/shareWithGroup.d.ts +1 -1
- package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/groupCreation.js +1 -1
- package/workflows/organizations/groups/groupCreation.js.map +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js +1 -1
- package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -1
- package/workflows/organizations/principalPolicy/index.d.ts +2 -2
- package/workflows/organizations/principalPolicy/index.js +1 -1
- package/workflows/organizations/principalPolicy/index.js.map +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
- package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
- package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
- package/workflows/principals/externalAdminPolicy.js +1 -1
- package/workflows/principals/externalAdminPolicy.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryPageAppend.js +1 -1
- package/workflows/principals/historyRecovery/principalHistoryPageAppend.js.map +1 -1
- package/workflows/principals/policyCache/index.d.ts +1 -1
- package/workflows/principals/policyCache/index.js +3 -2
- package/workflows/principals/policyCache/index.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +1 -1
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.d.ts +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/workflows/registration/index.d.ts +2 -1
- package/workflows/registration/index.js +1 -1
- package/workflows/registration/index.js.map +1 -1
- package/workflows/registration/organizationProvisioning.d.ts +1 -12
- package/workflows/registration/organizationProvisioning.js +2 -70
- package/workflows/registration/organizationProvisioning.js.map +1 -1
- package/workflows/registration/persistRegistrationBootstrap.js +2 -0
- package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
- package/data/containers/shared/heldContainerHeads.js.map +0 -1
- package/workflows/organizations/principalPolicy/principalPolicyRequest.js.map +0 -1
- package/workflows/principals/policyVerification.js.map +0 -1
- /package/data/{containers/shared → keyingProjectionVerification/checkpoints}/heldContainerHeads.js +0 -0
- /package/{client/runtime → data/shared}/listenerSet.js +0 -0
- /package/{client/runtime → data/shared}/listenerSet.js.map +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wBAAwB,GAEzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,+CAA+C,CAAC;AAC1F,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,oDAAoD,CAAC;AAQ5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAc3D,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAC5C,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACnC,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,6BAA6B,GAAG,GAAG,CAAC;AAC1C,MAAM,gCAAgC,GAAG,GAAG,CAAC;AAC7C,MAAM,oCAAoC,GAAG,MAAM,CAAC;AAgCpD,SAAS,gBAAgB,CAAC,KAAc;IACtC,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACnD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AAK,OAAO,IAAI,OAAO;oBACnD,CAAC,CAAC,qBAAqB,CAAC,OAAO,EAAE,OAAO,CAAC,WAAW,CAAC;oBACrD,CAAC,CAAC,IAAI,CAAC;YACX,CAAC;YACD,MAAM;YACN,SAAS,EAAE,SAAS,CAAC,SAAS;SAC/B;QACD,MAAM;KACP,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n isKeyingVerificationCode,\n type KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport { isKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n appendSecurityIncident,\n listSecurityIncidents,\n} from \"../../data/persistence/securityIncidentPersistence\";\nimport type {\n SecurityIncident,\n SecurityIncidentContext,\n SecurityIncidentObjectKind,\n SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport type { Database } from \"../runtime/database\";\nimport { createListenerSet } from \"../runtime/listenerSet\";\n\nexport type { SecurityIncident, SecurityIncidentObjectKind };\n\nexport type SecurityIncidentListener = (incident: SecurityIncident) => void;\n\n/**\n * Where a reported incident ended up: `recorded` rows are durable in the local\n * ledger, `buffered` ones wait in memory for a retried write, and `failed`\n * ones were dropped, so only `recorded` justifies telling a user it was kept.\n * Hosts name it as `Awaited<ReturnType<SecurityIncidents[\"record\"]>>`.\n */\ntype SecurityIncidentRecordingStatus = \"buffered\" | \"failed\" | \"recorded\";\n\nconst MAX_BUFFERED_SECURITY_INCIDENTS = 100;\nconst MAX_EVIDENCE_HASH_COUNT = 32;\nconst MAX_EVIDENCE_HASH_KEY_LENGTH = 64;\nconst MAX_EVIDENCE_HASH_VALUE_LENGTH = 256;\nconst MAX_INCIDENT_IDENTIFIER_LENGTH = 256;\nconst MAX_INCIDENT_OPERATION_LENGTH = 128;\nconst SECURITY_INCIDENT_RETRY_DELAY_MS = 250;\nconst SECURITY_INCIDENT_MAX_RETRY_DELAY_MS = 30_000;\n\nexport interface SecurityIncidents {\n /** Returns null while the local database is unavailable. */\n list(): Promise<ReadonlyArray<SecurityIncident> | null>;\n /**\n * Durably record a terminal verification failure the host detected itself,\n * such as conflicting purge proofs found while merging a local backup. The\n * report is redacted, coalesced, retained, and buffered exactly like an\n * SDK-detected incident; one error instance is recorded at most once, and\n * repeats of it resolve with the status of the first report.\n */\n record(\n error: KeyingVerificationError,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus>;\n subscribe(listener: SecurityIncidentListener): () => void;\n}\n\ninterface SecurityIncidentServiceOptions {\n readonly database: Database;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly onIncident?: SecurityIncidentListener | undefined;\n readonly trustDomain: string | null;\n}\n\ninterface SecurityIncidentServiceResult {\n readonly dispose: () => void;\n readonly incidents: SecurityIncidents;\n readonly report: SecurityIncidentReporter;\n}\n\nfunction verificationCode(error: unknown): SecurityIncident[\"code\"] | null {\n if (!isKeyingVerificationError(error)) return null;\n const code = Reflect.get(error, \"code\");\n return isKeyingVerificationCode(code)\n ? code\n : \"unrecognized_verification_code\";\n}\n\ninterface RedactedIncident {\n readonly code: SecurityIncident[\"code\"];\n readonly context: SecurityIncidentContext;\n readonly detectedAt: string;\n readonly lastDetectedAt: string;\n readonly occurrenceCount: number;\n}\n\nfunction boundIncidentText(value: string, maxLength: number): string {\n return value.slice(0, maxLength);\n}\n\nfunction boundNullableIncidentText(value: string | null): string | null {\n return value === null\n ? null\n : boundIncidentText(value, MAX_INCIDENT_IDENTIFIER_LENGTH);\n}\n\nfunction redactIncidentContext(\n context: SecurityIncidentContext,\n): SecurityIncidentContext {\n return {\n evidenceHashes: Object.fromEntries(\n Object.entries(context.evidenceHashes ?? {})\n .filter(\n ([key, value]) =>\n key.length > 0 &&\n key.length <= MAX_EVIDENCE_HASH_KEY_LENGTH &&\n value.length <= MAX_EVIDENCE_HASH_VALUE_LENGTH,\n )\n // Code-unit order: the retained keys feed the incident id hash, so\n // truncation must pick the same keys on every runtime and locale.\n .sort(([left], [right]) => compareCanonicalStrings(left, right))\n .slice(0, MAX_EVIDENCE_HASH_COUNT),\n ),\n objectId: boundNullableIncidentText(context.objectId),\n objectKind: context.objectKind,\n operation: boundIncidentText(\n context.operation,\n MAX_INCIDENT_OPERATION_LENGTH,\n ),\n organizationId: boundNullableIncidentText(context.organizationId ?? null),\n };\n}\n\nfunction redactedIncidentKey(incident: RedactedIncident): string {\n return JSON.stringify([\n incident.code,\n incident.context.operation,\n incident.context.objectKind,\n incident.context.objectId,\n incident.context.organizationId ?? null,\n incident.context.evidenceHashes,\n ]);\n}\n\ntype SecurityIncidentListeners = ReturnType<\n typeof createListenerSet<[SecurityIncident]>\n>;\n\nclass SecurityIncidentSink {\n private readonly bufferedIncidents = new Map<string, RedactedIncident>();\n private flushPromise: Promise<boolean> | null = null;\n private retryDelayMs = SECURITY_INCIDENT_RETRY_DELAY_MS;\n private retryTimeout: ReturnType<typeof setTimeout> | null = null;\n private readonly unsubscribeDatabase: () => void;\n private disposed = false;\n\n constructor(\n private readonly options: SecurityIncidentServiceOptions,\n private readonly listeners: SecurityIncidentListeners,\n ) {\n this.unsubscribeDatabase = options.database.subscribe(() => {\n void this.flush();\n });\n }\n\n dispose(): void {\n this.disposed = true;\n this.unsubscribeDatabase();\n if (this.retryTimeout) clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n this.bufferedIncidents.clear();\n }\n\n async persist(\n code: SecurityIncident[\"code\"],\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> {\n if (this.disposed) return \"failed\";\n const detectedAt = new Date().toISOString();\n const incident: RedactedIncident = {\n code,\n context: redactIncidentContext(context),\n detectedAt,\n lastDetectedAt: detectedAt,\n occurrenceCount: 1,\n };\n const execSql = this.options.database.execSql;\n if (this.options.database.status !== \"ready\" || !execSql) {\n return this.bufferStatus(incident);\n }\n\n try {\n const persisted = await this.append(execSql, incident);\n if (this.bufferedIncidents.size === 0) this.resetFlushRetry();\n if (!persisted) {\n this.options.logError(\n \"Security incident was dropped by the local retention limit\",\n );\n return \"failed\";\n }\n this.notify(persisted);\n return \"recorded\";\n } catch (persistenceError) {\n const status = this.bufferStatus(incident);\n if (status === \"buffered\") this.scheduleFlushRetry();\n this.options.logError(\n \"Security incident could not be persisted\",\n persistenceError,\n );\n return status;\n }\n }\n\n private bufferStatus(\n incident: RedactedIncident,\n ): SecurityIncidentRecordingStatus {\n return this.buffer(incident) ? \"buffered\" : \"failed\";\n }\n\n async flush(): Promise<void> {\n if (this.disposed) return;\n for (;;) {\n const activeFlush = this.flushPromise ?? this.startFlushBatch();\n if (!activeFlush) return;\n const succeeded = await activeFlush;\n if (succeeded) this.resetFlushRetry();\n if (this.flushPromise && this.flushPromise !== activeFlush) continue;\n if (this.flushPromise === activeFlush) this.flushPromise = null;\n if (\n !succeeded ||\n this.bufferedIncidents.size === 0 ||\n this.options.database.status !== \"ready\"\n ) {\n return;\n }\n }\n }\n\n private startFlushBatch(): Promise<boolean> | null {\n const execSql = this.options.database.execSql;\n if (this.options.database.status !== \"ready\" || !execSql) return null;\n\n const pending = [...this.bufferedIncidents.values()];\n if (pending.length === 0) return null;\n this.bufferedIncidents.clear();\n const flush = this.flushPending(execSql, pending);\n this.flushPromise = flush;\n return flush;\n }\n\n private append(\n execSql: NonNullable<Database[\"execSql\"]>,\n incident: RedactedIncident,\n ): Promise<SecurityIncident | null> {\n return appendSecurityIncident(execSql, {\n code: incident.code,\n detectedAt: incident.detectedAt,\n evidenceHashes: incident.context.evidenceHashes,\n lastDetectedAt: incident.lastDetectedAt,\n objectId: incident.context.objectId,\n objectKind: incident.context.objectKind,\n occurrenceCount: incident.occurrenceCount,\n operation: incident.context.operation,\n organizationId: incident.context.organizationId,\n trustDomain: this.options.trustDomain,\n });\n }\n\n private buffer(incident: RedactedIncident): boolean {\n if (this.disposed) return false;\n const key = redactedIncidentKey(incident);\n const existing = this.bufferedIncidents.get(key);\n if (existing) {\n this.bufferedIncidents.set(key, {\n ...existing,\n lastDetectedAt: incident.lastDetectedAt,\n occurrenceCount: existing.occurrenceCount + incident.occurrenceCount,\n });\n return true;\n }\n if (this.bufferedIncidents.size >= MAX_BUFFERED_SECURITY_INCIDENTS) {\n this.options.logError(\n \"Security incident could not be buffered because the startup buffer is full\",\n );\n return false;\n }\n this.bufferedIncidents.set(key, incident);\n return true;\n }\n\n private async flushPending(\n execSql: NonNullable<Database[\"execSql\"]>,\n pending: ReadonlyArray<RedactedIncident>,\n ): Promise<boolean> {\n let succeeded = true;\n for (const incident of pending) {\n try {\n const persisted = await this.append(execSql, incident);\n if (persisted) this.notify(persisted);\n } catch (persistenceError) {\n succeeded = false;\n if (this.buffer(incident)) this.scheduleFlushRetry();\n this.options.logError(\n \"Buffered security incident could not be persisted\",\n persistenceError,\n );\n }\n }\n return succeeded;\n }\n\n private notify(incident: SecurityIncident): void {\n if (this.disposed) return;\n this.listeners.notify(incident);\n try {\n this.options.onIncident?.(incident);\n } catch (callbackError) {\n this.options.logError(\"Security incident callback failed\", callbackError);\n }\n }\n\n private scheduleFlushRetry(): void {\n if (this.disposed || this.retryTimeout) return;\n const retryDelayMs = this.retryDelayMs;\n this.retryDelayMs = Math.min(\n this.retryDelayMs * 2,\n SECURITY_INCIDENT_MAX_RETRY_DELAY_MS,\n );\n this.retryTimeout = setTimeout(() => {\n this.retryTimeout = null;\n if (this.disposed) return;\n void this.flush();\n }, retryDelayMs);\n }\n\n private resetFlushRetry(): void {\n this.retryDelayMs = SECURITY_INCIDENT_RETRY_DELAY_MS;\n if (!this.retryTimeout) return;\n clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n}\n\nexport function createSecurityIncidentService(\n options: SecurityIncidentServiceOptions,\n): SecurityIncidentServiceResult {\n const listeners = createListenerSet<[SecurityIncident]>();\n const recordedErrors = new WeakMap<object, SecurityIncidentRecordingStatus>();\n const incidentReports = new WeakMap<\n object,\n Promise<SecurityIncidentRecordingStatus>\n >();\n const sink = new SecurityIncidentSink(options, listeners);\n\n const persistIncident = async (\n error: unknown,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> => {\n const code = verificationCode(error);\n if (!code) {\n return \"failed\";\n }\n if (code === \"unrecognized_verification_code\") {\n options.logError(\n \"Security incident used the fallback code because its verification code is unrecognized\",\n );\n }\n\n return sink.persist(code, context);\n };\n\n const record = async (\n error: unknown,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> => {\n if (typeof error !== \"object\" || error === null) {\n return \"failed\";\n }\n const recorded = recordedErrors.get(error);\n if (recorded) return recorded;\n const inFlight = incidentReports.get(error);\n if (inFlight) return inFlight;\n const pending = persistIncident(error, context)\n .then((status) => {\n if (status !== \"failed\") recordedErrors.set(error, status);\n return status;\n })\n .finally(() => {\n incidentReports.delete(error);\n });\n incidentReports.set(error, pending);\n return pending;\n };\n const report: SecurityIncidentReporter = async (error, context) => {\n await record(error, context);\n };\n\n return {\n dispose: () => sink.dispose(),\n incidents: {\n async list() {\n await sink.flush();\n const execSql = options.database.execSql;\n return options.database.status === \"ready\" && execSql\n ? listSecurityIncidents(execSql, options.trustDomain)\n : null;\n },\n record,\n subscribe: listeners.subscribe,\n },\n report,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wBAAwB,GAEzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EACL,yBAAyB,GAK1B,MAAM,qCAAqC,CAAC;AAe7C,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAC5C,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACnC,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,6BAA6B,GAAG,GAAG,CA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AC7B,SAAS,EAAE;YACT,KAAK,CAAC,IAAI;gBACR,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;gBACnB,MAAM,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;gBACzC,OAAO,OAAO,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO,IAAI,OAAO;oBACnD,CAAC,CAAC,qBAAqB,CAAC,OAAO,EAAE,OAAO,CAAC,WAAW,CAAC;oBACrD,CAAC,CAAC,IAAI,CAAC;YACX,CAAC;YACD,MAAM;YACN,SAAS,EAAE,SAAS,CAAC,SAAS;SAC/B;QACD,MAAM;KACP,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n isKeyingVerificationCode,\n type KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport {\n appendSecurityIncident,\n listSecurityIncidents,\n} from \"../../data/persistence/securityIncidentPersistence\";\nimport { createListenerSet } from \"../../data/shared/listenerSet\";\nimport {\n isKeyingVerificationError,\n type SecurityIncident,\n type SecurityIncidentContext,\n type SecurityIncidentObjectKind,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport type { Database } from \"../runtime/database\";\n\nexport type { SecurityIncident, SecurityIncidentObjectKind };\n\nexport type SecurityIncidentListener = (incident: SecurityIncident) => void;\n\n/**\n * Where a reported incident ended up: `recorded` rows are durable in the local\n * ledger, `buffered` ones wait in memory for a retried write, and `failed`\n * ones were dropped, so only `recorded` justifies telling a user it was kept.\n * Hosts name it as `Awaited<ReturnType<SecurityIncidents[\"record\"]>>`.\n */\ntype SecurityIncidentRecordingStatus = \"buffered\" | \"failed\" | \"recorded\";\n\nconst MAX_BUFFERED_SECURITY_INCIDENTS = 100;\nconst MAX_EVIDENCE_HASH_COUNT = 32;\nconst MAX_EVIDENCE_HASH_KEY_LENGTH = 64;\nconst MAX_EVIDENCE_HASH_VALUE_LENGTH = 256;\nconst MAX_INCIDENT_IDENTIFIER_LENGTH = 256;\nconst MAX_INCIDENT_OPERATION_LENGTH = 128;\nconst SECURITY_INCIDENT_RETRY_DELAY_MS = 250;\nconst SECURITY_INCIDENT_MAX_RETRY_DELAY_MS = 30_000;\n\nexport interface SecurityIncidents {\n /** Returns null while the local database is unavailable. */\n list(): Promise<ReadonlyArray<SecurityIncident> | null>;\n /**\n * Durably record a terminal verification failure the host detected itself,\n * such as conflicting purge proofs found while merging a local backup. The\n * report is redacted, coalesced, retained, and buffered exactly like an\n * SDK-detected incident; one error instance is recorded at most once, and\n * repeats of it resolve with the status of the first report.\n */\n record(\n error: KeyingVerificationError,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus>;\n subscribe(listener: SecurityIncidentListener): () => void;\n}\n\ninterface SecurityIncidentServiceOptions {\n readonly database: Database;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly onIncident?: SecurityIncidentListener | undefined;\n readonly trustDomain: string | null;\n}\n\ninterface SecurityIncidentServiceResult {\n readonly dispose: () => void;\n readonly incidents: SecurityIncidents;\n readonly report: SecurityIncidentReporter;\n}\n\nfunction verificationCode(error: unknown): SecurityIncident[\"code\"] | null {\n if (!isKeyingVerificationError(error)) return null;\n const code = Reflect.get(error, \"code\");\n return isKeyingVerificationCode(code)\n ? code\n : \"unrecognized_verification_code\";\n}\n\ninterface RedactedIncident {\n readonly code: SecurityIncident[\"code\"];\n readonly context: SecurityIncidentContext;\n readonly detectedAt: string;\n readonly lastDetectedAt: string;\n readonly occurrenceCount: number;\n}\n\nfunction boundIncidentText(value: string, maxLength: number): string {\n return value.slice(0, maxLength);\n}\n\nfunction boundNullableIncidentText(value: string | null): string | null {\n return value === null\n ? null\n : boundIncidentText(value, MAX_INCIDENT_IDENTIFIER_LENGTH);\n}\n\nfunction redactIncidentContext(\n context: SecurityIncidentContext,\n): SecurityIncidentContext {\n return {\n evidenceHashes: Object.fromEntries(\n Object.entries(context.evidenceHashes ?? {})\n .filter(\n ([key, value]) =>\n key.length > 0 &&\n key.length <= MAX_EVIDENCE_HASH_KEY_LENGTH &&\n value.length <= MAX_EVIDENCE_HASH_VALUE_LENGTH,\n )\n // Code-unit order: the retained keys feed the incident id hash, so\n // truncation must pick the same keys on every runtime and locale.\n .sort(([left], [right]) => compareCanonicalStrings(left, right))\n .slice(0, MAX_EVIDENCE_HASH_COUNT),\n ),\n objectId: boundNullableIncidentText(context.objectId),\n objectKind: context.objectKind,\n operation: boundIncidentText(\n context.operation,\n MAX_INCIDENT_OPERATION_LENGTH,\n ),\n organizationId: boundNullableIncidentText(context.organizationId ?? null),\n };\n}\n\nfunction redactedIncidentKey(incident: RedactedIncident): string {\n return JSON.stringify([\n incident.code,\n incident.context.operation,\n incident.context.objectKind,\n incident.context.objectId,\n incident.context.organizationId ?? null,\n incident.context.evidenceHashes,\n ]);\n}\n\ntype SecurityIncidentListeners = ReturnType<\n typeof createListenerSet<[SecurityIncident]>\n>;\n\nclass SecurityIncidentSink {\n private readonly bufferedIncidents = new Map<string, RedactedIncident>();\n private flushPromise: Promise<boolean> | null = null;\n private retryDelayMs = SECURITY_INCIDENT_RETRY_DELAY_MS;\n private retryTimeout: ReturnType<typeof setTimeout> | null = null;\n private readonly unsubscribeDatabase: () => void;\n private disposed = false;\n\n constructor(\n private readonly options: SecurityIncidentServiceOptions,\n private readonly listeners: SecurityIncidentListeners,\n ) {\n this.unsubscribeDatabase = options.database.subscribe(() => {\n void this.flush();\n });\n }\n\n dispose(): void {\n this.disposed = true;\n this.unsubscribeDatabase();\n if (this.retryTimeout) clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n this.bufferedIncidents.clear();\n }\n\n async persist(\n code: SecurityIncident[\"code\"],\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> {\n if (this.disposed) return \"failed\";\n const detectedAt = new Date().toISOString();\n const incident: RedactedIncident = {\n code,\n context: redactIncidentContext(context),\n detectedAt,\n lastDetectedAt: detectedAt,\n occurrenceCount: 1,\n };\n const execSql = this.options.database.execSql;\n if (this.options.database.status !== \"ready\" || !execSql) {\n return this.bufferStatus(incident);\n }\n\n try {\n const persisted = await this.append(execSql, incident);\n if (this.bufferedIncidents.size === 0) this.resetFlushRetry();\n if (!persisted) {\n this.options.logError(\n \"Security incident was dropped by the local retention limit\",\n );\n return \"failed\";\n }\n this.notify(persisted);\n return \"recorded\";\n } catch (persistenceError) {\n const status = this.bufferStatus(incident);\n if (status === \"buffered\") this.scheduleFlushRetry();\n this.options.logError(\n \"Security incident could not be persisted\",\n persistenceError,\n );\n return status;\n }\n }\n\n private bufferStatus(\n incident: RedactedIncident,\n ): SecurityIncidentRecordingStatus {\n return this.buffer(incident) ? \"buffered\" : \"failed\";\n }\n\n async flush(): Promise<void> {\n if (this.disposed) return;\n for (;;) {\n const activeFlush = this.flushPromise ?? this.startFlushBatch();\n if (!activeFlush) return;\n const succeeded = await activeFlush;\n if (succeeded) this.resetFlushRetry();\n if (this.flushPromise && this.flushPromise !== activeFlush) continue;\n if (this.flushPromise === activeFlush) this.flushPromise = null;\n if (\n !succeeded ||\n this.bufferedIncidents.size === 0 ||\n this.options.database.status !== \"ready\"\n ) {\n return;\n }\n }\n }\n\n private startFlushBatch(): Promise<boolean> | null {\n const execSql = this.options.database.execSql;\n if (this.options.database.status !== \"ready\" || !execSql) return null;\n\n const pending = [...this.bufferedIncidents.values()];\n if (pending.length === 0) return null;\n this.bufferedIncidents.clear();\n const flush = this.flushPending(execSql, pending);\n this.flushPromise = flush;\n return flush;\n }\n\n private append(\n execSql: NonNullable<Database[\"execSql\"]>,\n incident: RedactedIncident,\n ): Promise<SecurityIncident | null> {\n return appendSecurityIncident(execSql, {\n code: incident.code,\n detectedAt: incident.detectedAt,\n evidenceHashes: incident.context.evidenceHashes,\n lastDetectedAt: incident.lastDetectedAt,\n objectId: incident.context.objectId,\n objectKind: incident.context.objectKind,\n occurrenceCount: incident.occurrenceCount,\n operation: incident.context.operation,\n organizationId: incident.context.organizationId,\n trustDomain: this.options.trustDomain,\n });\n }\n\n private buffer(incident: RedactedIncident): boolean {\n if (this.disposed) return false;\n const key = redactedIncidentKey(incident);\n const existing = this.bufferedIncidents.get(key);\n if (existing) {\n this.bufferedIncidents.set(key, {\n ...existing,\n lastDetectedAt: incident.lastDetectedAt,\n occurrenceCount: existing.occurrenceCount + incident.occurrenceCount,\n });\n return true;\n }\n if (this.bufferedIncidents.size >= MAX_BUFFERED_SECURITY_INCIDENTS) {\n this.options.logError(\n \"Security incident could not be buffered because the startup buffer is full\",\n );\n return false;\n }\n this.bufferedIncidents.set(key, incident);\n return true;\n }\n\n private async flushPending(\n execSql: NonNullable<Database[\"execSql\"]>,\n pending: ReadonlyArray<RedactedIncident>,\n ): Promise<boolean> {\n let succeeded = true;\n for (const incident of pending) {\n try {\n const persisted = await this.append(execSql, incident);\n if (persisted) this.notify(persisted);\n } catch (persistenceError) {\n succeeded = false;\n if (this.buffer(incident)) this.scheduleFlushRetry();\n this.options.logError(\n \"Buffered security incident could not be persisted\",\n persistenceError,\n );\n }\n }\n return succeeded;\n }\n\n private notify(incident: SecurityIncident): void {\n if (this.disposed) return;\n this.listeners.notify(incident);\n try {\n this.options.onIncident?.(incident);\n } catch (callbackError) {\n this.options.logError(\"Security incident callback failed\", callbackError);\n }\n }\n\n private scheduleFlushRetry(): void {\n if (this.disposed || this.retryTimeout) return;\n const retryDelayMs = this.retryDelayMs;\n this.retryDelayMs = Math.min(\n this.retryDelayMs * 2,\n SECURITY_INCIDENT_MAX_RETRY_DELAY_MS,\n );\n this.retryTimeout = setTimeout(() => {\n this.retryTimeout = null;\n if (this.disposed) return;\n void this.flush();\n }, retryDelayMs);\n }\n\n private resetFlushRetry(): void {\n this.retryDelayMs = SECURITY_INCIDENT_RETRY_DELAY_MS;\n if (!this.retryTimeout) return;\n clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n}\n\nexport function createSecurityIncidentService(\n options: SecurityIncidentServiceOptions,\n): SecurityIncidentServiceResult {\n const listeners = createListenerSet<[SecurityIncident]>();\n const recordedErrors = new WeakMap<object, SecurityIncidentRecordingStatus>();\n const incidentReports = new WeakMap<\n object,\n Promise<SecurityIncidentRecordingStatus>\n >();\n const sink = new SecurityIncidentSink(options, listeners);\n\n const persistIncident = async (\n error: unknown,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> => {\n const code = verificationCode(error);\n if (!code) {\n return \"failed\";\n }\n if (code === \"unrecognized_verification_code\") {\n options.logError(\n \"Security incident used the fallback code because its verification code is unrecognized\",\n );\n }\n\n return sink.persist(code, context);\n };\n\n const record = async (\n error: unknown,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> => {\n if (typeof error !== \"object\" || error === null) {\n return \"failed\";\n }\n const recorded = recordedErrors.get(error);\n if (recorded) return recorded;\n const inFlight = incidentReports.get(error);\n if (inFlight) return inFlight;\n const pending = persistIncident(error, context)\n .then((status) => {\n if (status !== \"failed\") recordedErrors.set(error, status);\n return status;\n })\n .finally(() => {\n incidentReports.delete(error);\n });\n incidentReports.set(error, pending);\n return pending;\n };\n const report: SecurityIncidentReporter = async (error, context) => {\n await record(error, context);\n };\n\n return {\n dispose: () => sink.dispose(),\n incidents: {\n async list() {\n await sink.flush();\n const execSql = options.database.execSql;\n return options.database.status === \"ready\" && execSql\n ? listSecurityIncidents(execSql, options.trustDomain)\n : null;\n },\n record,\n subscribe: listeners.subscribe,\n },\n report,\n };\n}\n"]}
|
package/client/session/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { createListenerSet } from "../../data/shared/listenerSet.js";
|
|
1
2
|
import { bootstrapRootContainer, registerIdentity as registerIdentityWorkflow, removeNativeSubscriptionRestoreProvisioningAttempt, } from "../../workflows/registration/index.js";
|
|
2
|
-
import { createListenerSet } from "../runtime/listenerSet.js";
|
|
3
3
|
import { emptySessionSnapshot, mergeSessionContext, registrationSessionResult, sessionSnapshotsEqual, } from "./sessionContext.js";
|
|
4
4
|
import { registrationKeyAlreadyBound, requireRegistrationIdentityPinner, requireSessionTrustDomain, requireUserIdentityAvailable, SessionIdentityAcknowledgments, } from "./sessionIdentityTrust.js";
|
|
5
5
|
import { userSessionsFromResponse } from "./sessionListing.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,gBAAgB,IAAI,wBAAwB,EAC5C,kDAAkD,GACnD,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,EACjC,yBAAyB,EACzB,4BAA4B,EAC5B,8BAA8B,GAC/B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,wBAAwB,CAAC;AAgBhC,MAAM,UAAU,aAAa,CAAC,YAAiC;IAC7D,OAAO,IAAI,cAAc,CAAC,YAAY,CAAC,CAAC;AAC1C,CAAC;AAED,MAAM,cAAc;IAOW;IANZ,uBAAuB,GACtC,IAAI,8BAA8B,EAAE,CAAC;IACtB,SAAS,GAAG,iBAAiB,EAAE,CAAC;IACzC,gBAAgB,GAAG,IAAI,CAAC;IACxB,aAAa,GAAG,oBAAoB,EAAE,CAAC;IAE/C,YAA6B,YAAiC;QAAjC,iBAAY,GAAZ,YAAY,CAAqB;IAAG,CAAC;IAElE,IAAI,SAAS;Q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n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"../../workflows/registration\";\nimport type { ClearRemoteSyncStateResult } from \"../../workflows/sync\";\nimport { createListenerSet } from \"../runtime/listenerSet\";\nimport {\n emptySessionSnapshot,\n mergeSessionContext,\n registrationSessionResult,\n sessionSnapshotsEqual,\n} from \"./sessionContext\";\nimport {\n registrationKeyAlreadyBound,\n requireRegistrationIdentityPinner,\n requireSessionTrustDomain,\n requireUserIdentityAvailable,\n SessionIdentityAcknowledgments,\n} from \"./sessionIdentityTrust\";\nimport { userSessionsFromResponse } from \"./sessionListing\";\nimport {\n authenticateUnlessSuspended,\n refuseSessionLogin,\n} from \"./sessionLoginRefusal\";\nimport { createSessionOrganization } from \"./sessionOrganizationCreation\";\nimport {\n clearSessionRemoteSyncState,\n recoverPurgedSessionOrganization,\n} from \"./sessionPurgeRecovery\";\nimport {\n acknowledgedSessionRoot,\n commitSessionRootAcknowledgment,\n} from \"./sessionRootAuthority\";\nimport type {\n CreateOrganizationOptions,\n RegisterIdentityOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionDependencies,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./sessionTypes\";\n\nexport function createSession(dependencies: SessionDependencies): Session {\n return new SessionService(dependencies);\n}\n\nclass SessionService implements Session {\n private readonly identityAcknowledgments =\n new SessionIdentityAcknowledgments();\n private readonly listeners = createListenerSet();\n private syncEnabledValue = true;\n private snapshotValue = emptySessionSnapshot();\n\n constructor(private readonly dependencies: SessionDependencies) {}\n\n get authToken(): string | null {\n return this.snapshotValue.authToken;\n }\n\n get containerId(): string | null {\n return this.snapshotValue.containerId;\n }\n\n get defaultOrganizationId(): string | null {\n return this.snapshotValue.defaultOrganizationId;\n }\n\n get isAuthenticated(): boolean {\n return this.snapshotValue.isAuthenticated;\n }\n\n get isRoot(): boolean {\n return this.snapshotValue.isRoot;\n }\n\n get organizationId(): string | null {\n return this.snapshotValue.organizationId;\n }\n\n get snapshot(): SessionSnapshot {\n return this.snapshotValue;\n }\n\n get syncEnabled(): boolean {\n return this.syncEnabledValue;\n }\n\n get userId(): string | null {\n return this.snapshotValue.userId;\n }\n\n get userIdAcknowledged(): boolean {\n return this.identityAcknowledgments.isAcknowledged(\n this.snapshotValue.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n }\n\n async bootstrapLocalRootContainer(\n isCurrent: () => boolean = () => true,\n ): ReturnType<typeof bootstrapRootContainer> {\n if (!isCurrent()) throw new Error(\"Identity change was superseded.\");\n // Preserve a logged-in session's acknowledged root during local recovery.\n const acknowledgedRoot = acknowledgedSessionRoot(\n this,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n if (this.isAuthenticated && acknowledgedRoot) {\n return { containerId: acknowledgedRoot, created: false };\n }\n const result = await bootstrapRootContainer(\n this.dependencies.database.requireExecSql(\"bootstrapLocalRootContainer\"),\n );\n if (!isCurrent()) throw new Error(\"Identity change was superseded.\");\n this.setContainerId(result.containerId);\n if (result.created) {\n this.dependencies.log(\"Root container created\");\n }\n return result;\n }\n\n async listSessions(): Promise<UserSession[]> {\n return userSessionsFromResponse(await this.dependencies.api.listSessions());\n }\n\n async clearRemoteSyncState(\n organizationId: string,\n ): Promise<ClearRemoteSyncStateResult> {\n return clearSessionRemoteSyncState(this.dependencies, this, organizationId);\n }\n\n async destroySession(sessionId: string): Promise<boolean> {\n const response = await this.dependencies.api.destroySession(sessionId);\n return response?.message === \"ok\";\n }\n\n async login(challengeHex?: string | undefined): Promise<boolean> {\n const signingKeyPair =\n this.dependencies.identity.requireSigningKeyPair(\"login\");\n const fingerprint =\n (await this.dependencies.identity.refreshSigningFingerprint()) ?? null;\n\n if (!fingerprint) {\n return false;\n }\n // A refusal below clears the session it is evidence against; a session\n // another login committed meanwhile is not that session and stays.\n const snapshotAtStart = this.snapshotValue;\n const identitySnapshot = this.dependencies.identity.snapshot;\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n return false;\n }\n if (identitySnapshot.signingKeyPair !== signingKeyPair) {\n return false;\n }\n const pinLocalUserIdentity = requireUserIdentityAvailable(\n this.dependencies.onUserIdentityAvailable,\n \"Login\",\n );\n\n this.dependencies.log(\n challengeHex ? \"Authenticating with challenge...\" : \"Authenticating...\",\n );\n const authentication = await authenticateUnlessSuspended(\n () =>\n challengeHex\n ? this.dependencies.api.authenticateWithChallenge(\n fingerprint,\n signingKeyPair.signingPrivateKey,\n challengeHex,\n )\n : this.dependencies.api.authenticate(\n fingerprint,\n signingKeyPair.signingPrivateKey,\n ),\n () => {\n if (this.authToken === snapshotAtStart.authToken) this.logout();\n },\n );\n\n if (this.dependencies.identity.snapshot !== identitySnapshot) {\n return false;\n }\n\n if (!authentication) {\n this.logout();\n this.dependencies.log(\"Authentication failed\");\n return false;\n }\n\n try {\n this.identityAcknowledgments.assertMatches(\n authentication.userId,\n fingerprint,\n );\n await pinLocalUserIdentity(authentication.userId, {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: fingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n });\n if (this.dependencies.identity.snapshot !== identitySnapshot)\n return false;\n this.identityAcknowledgments.remember(authentication.userId, fingerprint);\n } catch (error) {\n return refuseSessionLogin(error, authentication.userId, {\n clear: () => this.logout(),\n report: this.dependencies.reportSecurityIncident,\n });\n }\n // A changed root for this identity+org is refused before the token is\n // usable. Decision and commit are one synchronous step against the live\n // snapshot (no await in between); the refusal clears the prior session in\n // that same step and then reports its own incident.\n await commitSessionRootAcknowledgment({\n context: {\n authToken: authentication.token,\n defaultOrganizationId: authentication.organizationId,\n isAuthenticated: true,\n isRoot: authentication.isRoot,\n organizationId: authentication.organizationId,\n userId: authentication.userId,\n },\n onRefused: () => {\n if (this.snapshotValue === snapshotAtStart) this.logout();\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: authentication,\n session: this,\n signingFingerprint: fingerprint,\n });\n this.dependencies.log(\"Authentication successful\");\n return true;\n }\n\n logout(): void {\n this.setContext({ authToken: null, isAuthenticated: false, isRoot: false });\n }\n\n async logoutRemote(): Promise<boolean> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n try {\n if (!this.authToken) {\n return true;\n }\n\n const response = await this.dependencies.api.logout();\n return response?.message === \"ok\";\n } finally {\n if (this.dependencies.identity.snapshot === identitySnapshot) {\n this.logout();\n }\n }\n }\n\n async registerIdentity(\n options?: RegisterIdentityOptions,\n ): Promise<SessionRegistrationResult | SessionRegistrationRefusal | null> {\n const containerId = this.containerId;\n if (!containerId) {\n this.dependencies.log(\n \"Registration skipped: container id is unavailable\",\n );\n return null;\n }\n\n const identitySnapshot = this.dependencies.identity.snapshot;\n const signingKeyPair = identitySnapshot.signingKeyPair;\n if (!signingKeyPair) {\n this.dependencies.log(\"Registration skipped: signing key is unavailable\");\n return null;\n }\n\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n this.dependencies.log(\n \"Registration skipped: encapsulation key is unavailable\",\n );\n return null;\n }\n\n const dbClient = this.dependencies.database.client;\n if (!dbClient) {\n this.dependencies.log(\n \"Registration skipped: database client is unavailable\",\n );\n return null;\n }\n const pinLocalUserIdentity = requireRegistrationIdentityPinner({\n identity: this.dependencies.identity,\n identitySnapshot,\n onUserIdentityAvailable: this.dependencies.onUserIdentityAvailable,\n });\n const keyBound = await registrationKeyAlreadyBound(\n this.dependencies,\n identitySnapshot.signingFingerprint,\n );\n if (this.dependencies.identity.snapshot !== identitySnapshot) return null;\n if (keyBound) return keyBound;\n\n let response: Awaited<ReturnType<typeof registerIdentityWorkflow>>;\n try {\n response = await registerIdentityWorkflow({\n identityTrustDomain: requireSessionTrustDomain(this.dependencies),\n apiClient: this.dependencies.api,\n containerId,\n dbClient,\n documentProjectors: this.dependencies.documentProjectors,\n encapsulationKeyPair,\n isIdentityCurrent: () =>\n this.dependencies.identity.snapshot === identitySnapshot,\n log: this.dependencies.log,\n logError: this.dependencies.logError,\n organizationProfileName: options?.organizationProfileName,\n pinLocalUserIdentity,\n primeProvisionedState: this.dependencies.primeProvisionedState,\n provisionedSystemContainers:\n this.dependencies.provisionedSystemContainers,\n rosterProfileNickname: options?.rosterProfileNickname,\n signingKeyFingerprint: identitySnapshot.signingFingerprint,\n signingKeyPair,\n });\n } catch (error: unknown) {\n this.dependencies.logError(\"Identity registration failed\", error);\n throw error;\n }\n\n if (this.dependencies.identity.snapshot !== identitySnapshot) return null;\n if (!response) {\n this.dependencies.log(\"Registration failed\");\n return null;\n }\n\n // The workflow pinned `response.userId` once the server confirmed it,\n // under the same currency check as above.\n await commitSessionRootAcknowledgment({\n context: {\n containerId: response.rootContainerId,\n defaultOrganizationId: response.organizationId,\n organizationId: response.organizationId,\n userId: response.userId,\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: response,\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n\n return registrationSessionResult(response);\n }\n\n async createOrganization(\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n nativeSubscriptionRestore?: boolean,\n ): Promise<SessionCreateOrganizationResult | null> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n const userId = this.userId;\n const response = await createSessionOrganization(this.dependencies, {\n nativeSubscriptionRestore,\n options,\n replacesOrganizationId,\n userId,\n });\n if (\n !response ||\n !userId ||\n this.userId !== userId ||\n this.dependencies.identity.snapshot !== identitySnapshot\n )\n return null;\n await commitSessionRootAcknowledgment({\n reporter: this.dependencies.reportSecurityIncident,\n root: {\n userId,\n organizationId: response.organizationId,\n rootContainerId: response.containerId,\n },\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n return response;\n }\n\n prepareNativeSubscriptionRestoreOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null> {\n return this.createOrganization(options, undefined, true);\n }\n\n async completeNativeSubscriptionRestoreOrganization(\n organizationId: string,\n ): Promise<boolean> {\n const userId = this.userId;\n const dbClient = this.dependencies.database.client;\n const identitySnapshot = this.dependencies.identity.snapshot;\n if (!userId || !dbClient) return false;\n return removeNativeSubscriptionRestoreProvisioningAttempt({\n canCommit: () =>\n this.userId === userId &&\n this.dependencies.identity.snapshot === identitySnapshot,\n dbClient,\n organizationId,\n userId,\n });\n }\n\n async recoverPurgedOrganization(\n organizationId: string,\n options?: CreateOrganizationOptions,\n ): Promise<SessionRecoverOrganizationResult | null> {\n return recoverPurgedSessionOrganization(\n this.dependencies,\n this,\n organizationId,\n options,\n );\n }\n\n setAuthToken(authToken: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, authToken });\n }\n\n setContainerId(containerId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, containerId });\n }\n\n setContext(context: SessionContext): void {\n const wasAcknowledged = this.userIdAcknowledged;\n this.identityAcknowledgments.remember(\n context.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n const previous = this.snapshotValue;\n this.setSnapshot(\n mergeSessionContext(\n previous,\n context,\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n // Acknowledging an already-held userId changes `userIdAcknowledged` without\n // changing the snapshot; persistence subscribers must still observe it.\n if (\n this.snapshotValue === previous &&\n wasAcknowledged !== this.userIdAcknowledged\n ) {\n this.listeners.notify();\n }\n }\n\n setOrganizationId(organizationId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, organizationId });\n }\n\n setSyncEnabled(enabled: boolean): void {\n if (this.syncEnabledValue === enabled) {\n return;\n }\n this.syncEnabledValue = enabled;\n this.listeners.notify();\n }\n\n setUserId(userId: string | null): void {\n this.setSnapshot(\n mergeSessionContext(\n this.snapshotValue,\n { userId },\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n }\n\n subscribe = (listener: SessionListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private setSnapshot(next: SessionSnapshot): void {\n const previous = this.snapshotValue;\n if (previous.authToken !== next.authToken) {\n this.dependencies.api.setAuthToken(next.authToken);\n }\n\n if (sessionSnapshotsEqual(previous, next)) {\n return;\n }\n\n this.snapshotValue = next;\n this.listeners.notify();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EACL,sBAAsB,EACtB,gBAAgB,IAAI,wBAAwB,EAC5C,kDAAkD,GACnD,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,EACjC,yBAAyB,EACzB,4BAA4B,EAC5B,8BAA8B,GAC/B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,wBAAwB,CAAC;AAgBhC,MAAM,UAAU,aAAa,CAAC,YAAiC;IAC7D,OAAO,IAAI,cAAc,CAAC,YAAY,CAAC,CAAC;AAC1C,CAAC;AAED,MAAM,cAAc;IAOW;IANZ,uBAAuB,GACtC,IAAI,8BAA8B,EAAE,CAAC;IACtB,SAAS,GAAG,iBAAiB,EAAE,CAAC;IACzC,gBAAgB,GAAG,IAAI,CAAC;IACxB,aAAa,GAAG,oBAAoB,EAAE,CAAC;IAE/C,YAA6B,YAAiC;QAAjC,iBAAY,GAAZ,YAAY,CAAqB;IAAG,CAAC;IAElE,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,aAAa,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IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;QAC1B,CAAC;IACH,CAAC;IAED,iBAAiB,CAAC,cAA6B;QAC7C,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,IAAI,CAAC,aAAa,EAAE,cAAc,EAAE,CAAC,CAAC;IAC9D,CAAC;IAED,cAAc,CAAC,OAAgB;QAC7B,IAAI,IAAI,CAAC,gBAAgB,KAAK,OAAO,EAAE,CAAC;YACtC,OAAO;QACT,CAAC;QACD,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;QAChC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;IAED,SAAS,CAAC,MAAqB;QAC7B,IAAI,CAAC,WAAW,CACd,mBAAmB,CACjB,IAAI,CAAC,aAAa,EAClB,EAAE,MAAM,EAAE,EACV,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC,kBAAkB,CACvD,CACF,CAAC;IACJ,CAAC;IAED,SAAS,GAAG,CAAC,QAAyB,EAAgB,EAAE,CACtD,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAE7B,WAAW,CAAC,IAAqB;QACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC;QACpC,IAAI,QAAQ,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS,EAAE,CAAC;YAC1C,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACrD,CAAC;QAED,IAAI,qBAAqB,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,CAAC;YAC1C,OAAO;QACT,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import { createListenerSet } from \"../../data/shared/listenerSet\";\nimport {\n bootstrapRootContainer,\n registerIdentity as registerIdentityWorkflow,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"../../workflows/registration\";\nimport type { ClearRemoteSyncStateResult } from \"../../workflows/sync\";\nimport {\n emptySessionSnapshot,\n mergeSessionContext,\n registrationSessionResult,\n sessionSnapshotsEqual,\n} from \"./sessionContext\";\nimport {\n registrationKeyAlreadyBound,\n requireRegistrationIdentityPinner,\n requireSessionTrustDomain,\n requireUserIdentityAvailable,\n SessionIdentityAcknowledgments,\n} from \"./sessionIdentityTrust\";\nimport { userSessionsFromResponse } from \"./sessionListing\";\nimport {\n authenticateUnlessSuspended,\n refuseSessionLogin,\n} from \"./sessionLoginRefusal\";\nimport { createSessionOrganization } from \"./sessionOrganizationCreation\";\nimport {\n clearSessionRemoteSyncState,\n recoverPurgedSessionOrganization,\n} from \"./sessionPurgeRecovery\";\nimport {\n acknowledgedSessionRoot,\n commitSessionRootAcknowledgment,\n} from \"./sessionRootAuthority\";\nimport type {\n CreateOrganizationOptions,\n RegisterIdentityOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionDependencies,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./sessionTypes\";\n\nexport function createSession(dependencies: SessionDependencies): Session {\n return new SessionService(dependencies);\n}\n\nclass SessionService implements Session {\n private readonly identityAcknowledgments =\n new SessionIdentityAcknowledgments();\n private readonly listeners = createListenerSet();\n private syncEnabledValue = true;\n private snapshotValue = emptySessionSnapshot();\n\n constructor(private readonly dependencies: SessionDependencies) {}\n\n get authToken(): string | null {\n return this.snapshotValue.authToken;\n }\n\n get containerId(): string | null {\n return this.snapshotValue.containerId;\n }\n\n get defaultOrganizationId(): string | null {\n return this.snapshotValue.defaultOrganizationId;\n }\n\n get isAuthenticated(): boolean {\n return this.snapshotValue.isAuthenticated;\n }\n\n get isRoot(): boolean {\n return this.snapshotValue.isRoot;\n }\n\n get organizationId(): string | null {\n return this.snapshotValue.organizationId;\n }\n\n get snapshot(): SessionSnapshot {\n return this.snapshotValue;\n }\n\n get syncEnabled(): boolean {\n return this.syncEnabledValue;\n }\n\n get userId(): string | null {\n return this.snapshotValue.userId;\n }\n\n get userIdAcknowledged(): boolean {\n return this.identityAcknowledgments.isAcknowledged(\n this.snapshotValue.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n }\n\n async bootstrapLocalRootContainer(\n isCurrent: () => boolean = () => true,\n ): ReturnType<typeof bootstrapRootContainer> {\n if (!isCurrent()) throw new Error(\"Identity change was superseded.\");\n // Preserve a logged-in session's acknowledged root during local recovery.\n const acknowledgedRoot = acknowledgedSessionRoot(\n this,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n if (this.isAuthenticated && acknowledgedRoot) {\n return { containerId: acknowledgedRoot, created: false };\n }\n const result = await bootstrapRootContainer(\n this.dependencies.database.requireExecSql(\"bootstrapLocalRootContainer\"),\n );\n if (!isCurrent()) throw new Error(\"Identity change was superseded.\");\n this.setContainerId(result.containerId);\n if (result.created) {\n this.dependencies.log(\"Root container created\");\n }\n return result;\n }\n\n async listSessions(): Promise<UserSession[]> {\n return userSessionsFromResponse(await this.dependencies.api.listSessions());\n }\n\n async clearRemoteSyncState(\n organizationId: string,\n ): Promise<ClearRemoteSyncStateResult> {\n return clearSessionRemoteSyncState(this.dependencies, this, organizationId);\n }\n\n async destroySession(sessionId: string): Promise<boolean> {\n const response = await this.dependencies.api.destroySession(sessionId);\n return response?.message === \"ok\";\n }\n\n async login(challengeHex?: string | undefined): Promise<boolean> {\n const signingKeyPair =\n this.dependencies.identity.requireSigningKeyPair(\"login\");\n const fingerprint =\n (await this.dependencies.identity.refreshSigningFingerprint()) ?? null;\n\n if (!fingerprint) {\n return false;\n }\n // A refusal below clears the session it is evidence against; a session\n // another login committed meanwhile is not that session and stays.\n const snapshotAtStart = this.snapshotValue;\n const identitySnapshot = this.dependencies.identity.snapshot;\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n return false;\n }\n if (identitySnapshot.signingKeyPair !== signingKeyPair) {\n return false;\n }\n const pinLocalUserIdentity = requireUserIdentityAvailable(\n this.dependencies.onUserIdentityAvailable,\n \"Login\",\n );\n\n this.dependencies.log(\n challengeHex ? \"Authenticating with challenge...\" : \"Authenticating...\",\n );\n const authentication = await authenticateUnlessSuspended(\n () =>\n challengeHex\n ? this.dependencies.api.authenticateWithChallenge(\n fingerprint,\n signingKeyPair.signingPrivateKey,\n challengeHex,\n )\n : this.dependencies.api.authenticate(\n fingerprint,\n signingKeyPair.signingPrivateKey,\n ),\n () => {\n if (this.authToken === snapshotAtStart.authToken) this.logout();\n },\n );\n\n if (this.dependencies.identity.snapshot !== identitySnapshot) {\n return false;\n }\n\n if (!authentication) {\n this.logout();\n this.dependencies.log(\"Authentication failed\");\n return false;\n }\n\n try {\n this.identityAcknowledgments.assertMatches(\n authentication.userId,\n fingerprint,\n );\n await pinLocalUserIdentity(authentication.userId, {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: fingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n });\n if (this.dependencies.identity.snapshot !== identitySnapshot)\n return false;\n this.identityAcknowledgments.remember(authentication.userId, fingerprint);\n } catch (error) {\n return refuseSessionLogin(error, authentication.userId, {\n clear: () => this.logout(),\n report: this.dependencies.reportSecurityIncident,\n });\n }\n // A changed root for this identity+org is refused before the token is\n // usable. Decision and commit are one synchronous step against the live\n // snapshot (no await in between); the refusal clears the prior session in\n // that same step and then reports its own incident.\n await commitSessionRootAcknowledgment({\n context: {\n authToken: authentication.token,\n defaultOrganizationId: authentication.organizationId,\n isAuthenticated: true,\n isRoot: authentication.isRoot,\n organizationId: authentication.organizationId,\n userId: authentication.userId,\n },\n onRefused: () => {\n if (this.snapshotValue === snapshotAtStart) this.logout();\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: authentication,\n session: this,\n signingFingerprint: fingerprint,\n });\n this.dependencies.log(\"Authentication successful\");\n return true;\n }\n\n logout(): void {\n this.setContext({ authToken: null, isAuthenticated: false, isRoot: false });\n }\n\n async logoutRemote(): Promise<boolean> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n try {\n if (!this.authToken) {\n return true;\n }\n\n const response = await this.dependencies.api.logout();\n return response?.message === \"ok\";\n } finally {\n if (this.dependencies.identity.snapshot === identitySnapshot) {\n this.logout();\n }\n }\n }\n\n async registerIdentity(\n options?: RegisterIdentityOptions,\n ): Promise<SessionRegistrationResult | SessionRegistrationRefusal | null> {\n const containerId = this.containerId;\n if (!containerId) {\n this.dependencies.log(\n \"Registration skipped: container id is unavailable\",\n );\n return null;\n }\n\n const identitySnapshot = this.dependencies.identity.snapshot;\n const signingKeyPair = identitySnapshot.signingKeyPair;\n if (!signingKeyPair) {\n this.dependencies.log(\"Registration skipped: signing key is unavailable\");\n return null;\n }\n\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n this.dependencies.log(\n \"Registration skipped: encapsulation key is unavailable\",\n );\n return null;\n }\n\n const dbClient = this.dependencies.database.client;\n if (!dbClient) {\n this.dependencies.log(\n \"Registration skipped: database client is unavailable\",\n );\n return null;\n }\n const pinLocalUserIdentity = requireRegistrationIdentityPinner({\n identity: this.dependencies.identity,\n identitySnapshot,\n onUserIdentityAvailable: this.dependencies.onUserIdentityAvailable,\n });\n const keyBound = await registrationKeyAlreadyBound(\n this.dependencies,\n identitySnapshot.signingFingerprint,\n );\n if (this.dependencies.identity.snapshot !== identitySnapshot) return null;\n if (keyBound) return keyBound;\n\n let response: Awaited<ReturnType<typeof registerIdentityWorkflow>>;\n try {\n response = await registerIdentityWorkflow({\n identityTrustDomain: requireSessionTrustDomain(this.dependencies),\n apiClient: this.dependencies.api,\n containerId,\n dbClient,\n documentProjectors: this.dependencies.documentProjectors,\n encapsulationKeyPair,\n isIdentityCurrent: () =>\n this.dependencies.identity.snapshot === identitySnapshot,\n log: this.dependencies.log,\n logError: this.dependencies.logError,\n organizationProfileName: options?.organizationProfileName,\n pinLocalUserIdentity,\n primeProvisionedState: this.dependencies.primeProvisionedState,\n provisionedSystemContainers:\n this.dependencies.provisionedSystemContainers,\n rosterProfileNickname: options?.rosterProfileNickname,\n signingKeyFingerprint: identitySnapshot.signingFingerprint,\n signingKeyPair,\n });\n } catch (error: unknown) {\n this.dependencies.logError(\"Identity registration failed\", error);\n throw error;\n }\n\n if (this.dependencies.identity.snapshot !== identitySnapshot) return null;\n if (!response) {\n this.dependencies.log(\"Registration failed\");\n return null;\n }\n\n // The workflow pinned `response.userId` once the server confirmed it,\n // under the same currency check as above.\n await commitSessionRootAcknowledgment({\n context: {\n containerId: response.rootContainerId,\n defaultOrganizationId: response.organizationId,\n organizationId: response.organizationId,\n userId: response.userId,\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: response,\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n\n return registrationSessionResult(response);\n }\n\n async createOrganization(\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n nativeSubscriptionRestore?: boolean,\n ): Promise<SessionCreateOrganizationResult | null> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n const userId = this.userId;\n const response = await createSessionOrganization(this.dependencies, {\n nativeSubscriptionRestore,\n options,\n replacesOrganizationId,\n userId,\n });\n if (\n !response ||\n !userId ||\n this.userId !== userId ||\n this.dependencies.identity.snapshot !== identitySnapshot\n )\n return null;\n await commitSessionRootAcknowledgment({\n reporter: this.dependencies.reportSecurityIncident,\n root: {\n userId,\n organizationId: response.organizationId,\n rootContainerId: response.containerId,\n },\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n return response;\n }\n\n prepareNativeSubscriptionRestoreOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null> {\n return this.createOrganization(options, undefined, true);\n }\n\n async completeNativeSubscriptionRestoreOrganization(\n organizationId: string,\n ): Promise<boolean> {\n const userId = this.userId;\n const dbClient = this.dependencies.database.client;\n const identitySnapshot = this.dependencies.identity.snapshot;\n if (!userId || !dbClient) return false;\n return removeNativeSubscriptionRestoreProvisioningAttempt({\n canCommit: () =>\n this.userId === userId &&\n this.dependencies.identity.snapshot === identitySnapshot,\n dbClient,\n organizationId,\n userId,\n });\n }\n\n async recoverPurgedOrganization(\n organizationId: string,\n options?: CreateOrganizationOptions,\n ): Promise<SessionRecoverOrganizationResult | null> {\n return recoverPurgedSessionOrganization(\n this.dependencies,\n this,\n organizationId,\n options,\n );\n }\n\n setAuthToken(authToken: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, authToken });\n }\n\n setContainerId(containerId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, containerId });\n }\n\n setContext(context: SessionContext): void {\n const wasAcknowledged = this.userIdAcknowledged;\n this.identityAcknowledgments.remember(\n context.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n const previous = this.snapshotValue;\n this.setSnapshot(\n mergeSessionContext(\n previous,\n context,\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n // Acknowledging an already-held userId changes `userIdAcknowledged` without\n // changing the snapshot; persistence subscribers must still observe it.\n if (\n this.snapshotValue === previous &&\n wasAcknowledged !== this.userIdAcknowledged\n ) {\n this.listeners.notify();\n }\n }\n\n setOrganizationId(organizationId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, organizationId });\n }\n\n setSyncEnabled(enabled: boolean): void {\n if (this.syncEnabledValue === enabled) {\n return;\n }\n this.syncEnabledValue = enabled;\n this.listeners.notify();\n }\n\n setUserId(userId: string | null): void {\n this.setSnapshot(\n mergeSessionContext(\n this.snapshotValue,\n { userId },\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n }\n\n subscribe = (listener: SessionListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private setSnapshot(next: SessionSnapshot): void {\n const previous = this.snapshotValue;\n if (previous.authToken !== next.authToken) {\n this.dependencies.api.setAuthToken(next.authToken);\n }\n\n if (sessionSnapshotsEqual(previous, next)) {\n return;\n }\n\n this.snapshotValue = next;\n this.listeners.notify();\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AccountSuspendedError } from "../../internal/api-client/index.js";
|
|
2
|
-
import { reportAndRethrowKeyingVerificationError } from "../../data/
|
|
2
|
+
import { reportAndRethrowKeyingVerificationError, } from "../../data/shared/securityIncidents.js";
|
|
3
3
|
/**
|
|
4
4
|
* A server answering this identity with another account, or an identity
|
|
5
5
|
* whose durable pin no longer matches, is evidence, not a login failure: the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionLoginRefusal.js","sourceRoot":"","sources":["sessionLoginRefusal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,
|
|
1
|
+
{"version":3,"file":"sessionLoginRefusal.js","sourceRoot":"","sources":["sessionLoginRefusal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EACL,uCAAuC,GAExC,MAAM,qCAAqC,CAAC;AAE7C;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,KAAc,EACd,MAAc,EACd,OAGC;IAED,OAAO,CAAC,KAAK,EAAE,CAAC;IAChB,MAAM,uCAAuC,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,EAAE;QACnE,QAAQ,EAAE,MAAM;QAChB,UAAU,EAAE,MAAM;QAClB,SAAS,EAAE,eAAe;KAC3B,CAAC,CAAC;IACH,MAAM,KAAK,CAAC;AACd,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,YAA2C,EAC3C,KAAiB;IAEjB,IAAI,CAAC;QACH,OAAO,MAAM,YAAY,EAAE,CAAC;IAC9B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,qBAAqB,EAAE,CAAC;YAC3C,KAAK,EAAE,CAAC;QACV,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { AccountSuspendedError } from \"@tearleads/api-client\";\nimport {\n reportAndRethrowKeyingVerificationError,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\n\n/**\n * A server answering this identity with another account, or an identity\n * whose durable pin no longer matches, is evidence, not a login failure: the\n * session is cleared, the keying error is recorded, and the error propagates.\n */\nexport async function refuseSessionLogin(\n error: unknown,\n userId: string,\n session: {\n readonly clear: () => void;\n readonly report: SecurityIncidentReporter | undefined;\n },\n): Promise<never> {\n session.clear();\n await reportAndRethrowKeyingVerificationError(error, session.report, {\n objectId: userId,\n objectKind: \"user\",\n operation: \"session.login\",\n });\n throw error;\n}\n\n/**\n * Runs the sign-in request. A suspended account is terminal: the session it\n * would have renewed is cleared, so that session's requests stop renewing,\n * and the error propagates for the host to name.\n */\nexport async function authenticateUnlessSuspended<Authentication>(\n authenticate: () => Promise<Authentication>,\n clear: () => void,\n): Promise<Authentication> {\n try {\n return await authenticate();\n } catch (error) {\n if (error instanceof AccountSuspendedError) {\n clear();\n }\n throw error;\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
2
|
-
import { reportKeyingVerificationErrorInCauseChain } from "../../data/
|
|
2
|
+
import { reportKeyingVerificationErrorInCauseChain, } from "../../data/shared/securityIncidents.js";
|
|
3
3
|
/**
|
|
4
4
|
* The login, registration and organization-creation responses that carry a
|
|
5
5
|
* root id are unsigned. An organization's root row is created once, in the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionRootAuthority.js","sourceRoot":"","sources":["sessionRootAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,
|
|
1
|
+
{"version":3,"file":"sessionRootAuthority.js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CAAC,MAAM,EACjB,CAAC;YACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,gDAAgD,CACjD,CAAC;QACJ,CAAC;QACD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,OAAgB,EAChB,kBAAiC;IAEjC,OAAO,CACL,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAC,IAAI,CACvC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,kBAAkB,KAAK,kBAAkB;QAC/C,KAAK,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM;QAC/B,KAAK,CAAC,cAAc,KAAK,OAAO,CAAC,cAAc,CAClD,EAAE,eAAe,IAAI,IAAI,CAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n reportKeyingVerificationErrorInCauseChain,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport type { Session, SessionContext, SessionSnapshot } from \"./sessionTypes\";\n\ntype RootAcknowledgments = SessionSnapshot[\"rootAcknowledgments\"];\ntype RootAcknowledgmentInput = Omit<\n RootAcknowledgments[number],\n \"signingFingerprint\"\n>;\n\n/**\n * The login, registration and organization-creation responses that carry a\n * root id are unsigned. An organization's root row is created once, in the\n * provisioning transaction, and only ever disappears through a purge, so an\n * honest server can re-acknowledge the same root or report it gone (null) but\n * never presents a different root for an organization this identity already\n * acknowledged. A different id is a substitution attempt: the previous root\n * stays authoritative and the caller records a security incident.\n */\nfunction assertRootAcknowledgmentUnchanged(\n previous: RootAcknowledgments[number] | undefined,\n input: RootAcknowledgmentInput,\n): void {\n if (\n !previous ||\n previous.rootContainerId === input.rootContainerId ||\n input.rootContainerId === null\n ) {\n return;\n }\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Session root acknowledgement changed for an acknowledged organization\",\n );\n}\n\nexport function acknowledgeSessionRoot(\n known: RootAcknowledgments,\n input: RootAcknowledgmentInput,\n signingFingerprint: string | null,\n): RootAcknowledgments {\n if (!signingFingerprint)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Session root acknowledgement requires a signing identity\",\n );\n const matchesIdentity = (entry: RootAcknowledgments[number]) =>\n entry.signingFingerprint === signingFingerprint &&\n entry.userId === input.userId;\n assertRootAcknowledgmentUnchanged(\n known.find(\n (entry) =>\n matchesIdentity(entry) && entry.organizationId === input.organizationId,\n ),\n input,\n );\n return [\n ...known.filter(\n (entry) =>\n matchesIdentity(entry) && entry.organizationId !== input.organizationId,\n ),\n {\n userId: input.userId,\n organizationId: input.organizationId,\n rootContainerId: input.rootContainerId,\n signingFingerprint,\n },\n ];\n}\n\n/**\n * Decides and commits an acknowledgement against the session's CURRENT\n * snapshot in one synchronous step: reading `rootAcknowledgments`, deciding,\n * and `setContext` happen with no await between them, so an overlapping login,\n * registration or organization creation can never overwrite this entry with a\n * stale copy (a lost acknowledgement would erase that organization's root-swap\n * protection). Only the incident report for a refusal is asynchronous, and it\n * runs after the decision has been made and before the error propagates;\n * `onRefused` runs synchronously with the decision, ahead of that report.\n */\nexport async function commitSessionRootAcknowledgment(input: {\n readonly context?: Omit<SessionContext, \"rootAcknowledgments\"> | undefined;\n readonly onRefused?: (() => void) | undefined;\n readonly reporter: SecurityIncidentReporter | undefined;\n readonly root: RootAcknowledgmentInput;\n readonly session: Pick<Session, \"setContext\" | \"snapshot\">;\n readonly signingFingerprint: string | null;\n}): Promise<void> {\n const { context, reporter, root, session, signingFingerprint } = input;\n let rootAcknowledgments: RootAcknowledgments;\n try {\n rootAcknowledgments = acknowledgeSessionRoot(\n session.snapshot.rootAcknowledgments,\n root,\n signingFingerprint,\n );\n } catch (error) {\n input.onRefused?.();\n if (signingFingerprint) {\n await reportKeyingVerificationErrorInCauseChain(error, reporter, {\n objectId: root.rootContainerId,\n objectKind: \"container\",\n operation: \"session.root.acknowledge\",\n organizationId: root.organizationId,\n });\n }\n throw error;\n }\n session.setContext({ ...context, rootAcknowledgments });\n}\n\n/** Only the encrypted host restore may supply previously acknowledged roots. */\nexport function restoreSessionRoots(\n known: RootAcknowledgments,\n restored: RootAcknowledgments | undefined,\n signingFingerprint: string | null,\n userId: string | null,\n): RootAcknowledgments {\n const matches = (entry: RootAcknowledgments[number]) =>\n entry.signingFingerprint === signingFingerprint && entry.userId === userId;\n if (restored) {\n if (\n !restored.every(matches) ||\n new Set(restored.map((entry) => entry.organizationId)).size !==\n restored.length\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Restored roots differ from the active identity\",\n );\n }\n return restored.map((entry) => ({ ...entry }));\n }\n return known.every(matches) ? known : known.filter(matches);\n}\n\nexport function acknowledgedSessionRoot(\n session: Session,\n signingFingerprint: string | null,\n): string | null {\n return (\n session.snapshot.rootAcknowledgments.find(\n (entry) =>\n entry.signingFingerprint === signingFingerprint &&\n entry.userId === session.userId &&\n entry.organizationId === session.organizationId,\n )?.rootContainerId ?? null\n );\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../../internal/crypto/index.js";
|
|
2
|
-
import { isKeyingVerificationError } from "../../../keyingProjectionVerification/error.js";
|
|
3
2
|
import { ProjectionDependencyUnavailableError } from "../../../shared/dependencyUnavailable.js";
|
|
3
|
+
import { isKeyingVerificationError } from "../../../shared/securityIncidents.js";
|
|
4
4
|
import { ContainerKekRepairRequiredError } from "../containerKek/containerKekCurrency.js";
|
|
5
5
|
function keyingVerificationErrorCode(error) {
|
|
6
6
|
if (!isKeyingVerificationError(error) || !(error instanceof Error)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"freshProjectionRetry.js","sourceRoot":"","sources":["freshProjectionRetry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"freshProjectionRetry.js","sourceRoot":"","sources":["freshProjectionRetry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,uCAAuC,CAAC;AAC7F,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AAOvF,SAAS,2BAA2B,CAAC,KAAc;IACjD,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC,EAAE,CAAC;QACnE,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACxC,OAAO,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AAChD,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,KAAc;IAEd,IACE,CAAC,CAAC,KAAK,YAAY,uBAAuB,CAAC;QAC3C,CAAC,CAAC,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,yBAAyB,CAAC,EACrE,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,IAAI,GAAG,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAChD,OAAO,IAAI,KAAK,UAAU;QACxB,IAAI,KAAK,cAAc;QACvB,IAAI,KAAK,mBAAmB;QAC5B,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,8BAA8B,CAC5C,KAAc,EACd,cAA4C;IAE5C,2EAA2E;IAC3E,wEAAwE;IACxE,IACE,KAAK,YAAY,+BAA+B;QAChD,KAAK,YAAY,oCAAoC;QAErD,OAAO,IAAI,CAAC;IACd,MAAM,kBAAkB,GAAG,4BAA4B,CAAC,KAAK,CAAC,CAAC;IAC/D,IAAI,kBAAkB,EAAE,CAAC;QACvB,OAAO,kBAAkB,KAAK,UAAU,CAAC;IAC3C,CAAC;IACD,IAAI,2BAA2B,CAAC,KAAK,CAAC,KAAK,eAAe,EAAE,CAAC;QAC3D,yEAAyE;QACzE,0EAA0E;QAC1E,0DAA0D;QAC1D,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,yBAAyB,CAAC,KAAK,CAAC,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,KAAK,YAAY,KAAK,IAAI,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACjE,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../shared/dependencyUnavailable\";\nimport { isKeyingVerificationError } from \"../../../shared/securityIncidents\";\nimport { ContainerKekRepairRequiredError } from \"../containerKek/containerKekCurrency\";\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"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { containerKekWireLevel, } from "../../../internal/validators/response/index.js";
|
|
3
|
-
import { rememberVerifiedContainerHeads } from "../../containers/shared/heldContainerHeads.js";
|
|
4
3
|
import { PrincipalAuthorizationCheckpointUnavailableError } from "../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js";
|
|
5
4
|
import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
|
|
6
5
|
import { projectionLifetimeGuard } from "../projectionLifetimes.js";
|
|
7
6
|
import { assertProjectionVerificationCurrent, } from "../types.js";
|
|
8
7
|
import { enforceAccessManifestCheckpoints, validateAccessManifestCheckpoints, } from "./accessManifestCheckpointEnforcement.js";
|
|
8
|
+
import { rememberVerifiedContainerHeads } from "./heldContainerHeads.js";
|
|
9
9
|
import { matchesVerifiedBundleBytes } from "./verifiedBundleBytes.js";
|
|
10
10
|
export function createProjectionCheckpointContext(input) {
|
|
11
11
|
if (typeof input.execSql !== "function") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,qBAAqB,GACtB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAE5F,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAGzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EACL,mCAAmC,GAEpC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAmBnE,MAAM,UAAU,iCAAiC,CAAC,KAIjD;IACC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACxC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,oEAAoE,CACrE,CAAC;IACJ,CAAC;IAED,OAAO;QACL,kBAAkB,EAAE,EAAE;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;QACtE,gBAAgB,EAAE,IAAI,GAAG,EAAE;QAC3B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,EAAE;QACZ,qBAAqB,EAAE,EAAE;QACzB,eAAe,EAAE,EAAE;QACnB,aAAa,EAAE,EAAE;QACjB,iBAAiB,E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CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport { rememberVerifiedContainerHeads } from \"../../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type OpenPrincipalPolicyBundleReader,\n} from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // The caller's principal policy bundle store, opened per executor.\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL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BAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC7C,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC1B,IAAI,KAAK,YAAY,gDAAgD;YACnE,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AAC3D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAoC,EACpC,KAIC;IAED,IAAI,KAAK,CAAC,8BAA8B,KAAK,KAAK,EAAE,CAAC;QACnD,MAAM,6BAA6B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACpD,OAAO;IACT,CAAC;IACD,MAAM,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAClD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO;IAC7C,MAAM,cAAc,GAClB,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type OpenPrincipalPolicyBundleReader,\n} from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { rememberVerifiedContainerHeads } from \"./heldContainerHeads\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // The caller's principal policy bundle store, opened per executor.\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"heldContainerHeads.js","sourceRoot":"","sources":["heldContainerHeads.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAEvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE,OAAO,EAAgB,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAkB/E,6EAA6E;AAC7E,gFAAgF;AAChF,MAAM,cAAc,GAAG,IAAI,OAAO,EAA2B,CAAC;AAC9D,4EAA4E;AAC5E,+EAA+E;AAC/E,MAAM,SAAS,GAAG,GAAG,CAAC;AACtB,MAAM,YAAY,GAAG,GAAG,CAAC;AAEzB,SAAS,cAAc,CAAC,OA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AI,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC3B,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC;IACpC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWire } from \"@tearleads/validators/request\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport type { AuthoredContainerMutationHead } from \"../../containers/shared/mutationAcknowledgement\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { type ExecSql, resolveCanonicalExecSql } from \"../../sqlite/sqlSchema\";\n\nexport interface HeldContainerHead {\n readonly bundle: AccessManifestBundleWire;\n readonly state: ContainerAccessManifestState;\n}\n\ninterface HeldContainers {\n readonly heads: Map<string, HeldContainerHead>;\n readonly policies: Map<\n string,\n {\n readonly organizationId: string;\n readonly policy: PrincipalPolicyCheckpointEvidence;\n }\n >;\n}\n\n// Opportunistic, process-local evidence, not a persistent cache or freshness\n// oracle. No secret keys are retained. Eviction merely limits cascade coverage.\nconst heldByDatabase = new WeakMap<ExecSql, HeldContainers>();\n// Executor-wide limits: another organization's activity may evict evidence,\n// which only skips optional recitations and never changes durable checkpoints.\nconst MAX_HEADS = 256;\nconst MAX_POLICIES = 512;\n\nfunction heldContainers(execSql: ExecSql): HeldContainers {\n const canonical = resolveCanonicalExecSql(execSql);\n let held = heldByDatabase.get(canonical);\n if (!held) {\n held = { heads: new Map(), policies: new Map() };\n heldByDatabase.set(canonical, held);\n }\n return held;\n}\n\nfunction boundedSet<T>(\n map: Map<string, T>,\n key: string,\n value: T,\n max: number,\n) {\n map.delete(key);\n map.set(key, value);\n if (map.size > max) {\n const oldest = map.keys().next().value;\n if (oldest !== undefined) map.delete(oldest);\n }\n}\n\nfunction rememberHead(\n execSql: ExecSql,\n head: Pick<VerifiedContainerAccessManifest, \"state\" | \"manifestHash\">,\n build: () => HeldContainerHead,\n): void {\n const heads = heldContainers(execSql).heads;\n const previous = heads.get(head.state.containerId);\n if (previous && previous.state.epoch >= head.state.epoch) {\n if (previous.bundle.manifestHash === head.manifestHash) {\n boundedSet(heads, head.state.containerId, previous, MAX_HEADS);\n }\n return;\n }\n boundedSet(\n heads,\n head.state.containerId,\n structuredClone(build()),\n MAX_HEADS,\n );\n}\n\n/** Called only after the complete projection and its durable pins validate. */\nexport function rememberVerifiedContainerHeads(input: {\n readonly organizationId: string;\n readonly execSql: ExecSql;\n readonly heads: readonly VerifiedContainerAccessManifest[];\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n}): void {\n for (const policy of input.policies) {\n if (\n policy.principalType === \"organization\" &&\n policy.principalId !== input.organizationId\n ) {\n throw new Error(\"Held principal policy belongs to another organization\");\n }\n }\n // Group signed states contain no organization ID. Their scope is supplied\n // by the already-verified projection/policy caller, not inferred here.\n for (const head of input.heads) {\n if (head.state.organizationId !== input.organizationId) {\n throw new Error(\"Held container head belongs to another organization\");\n }\n }\n for (const head of input.heads) {\n rememberHead(input.execSql, head, () => ({\n state: head.state,\n bundle: {\n event: readCanonicalRecord(head.event, \"Verified container event\"),\n manifest: readCanonicalRecord(\n head.manifest,\n \"Verified container manifest\",\n ),\n manifestHash: head.manifestHash,\n state: readCanonicalRecord(head.state, \"Verified container state\"),\n },\n }));\n }\n const policies = heldContainers(input.execSql).policies;\n for (const policy of input.policies) {\n const key = `${input.organizationId}:${policy.principalType}:${policy.principalId}`;\n const previous = policies.get(key);\n if (previous && previous.policy.version > policy.version) continue;\n if (\n previous?.policy.version === policy.version &&\n previous.policy.stateHash !== policy.stateHash\n )\n continue;\n boundedSet(\n policies,\n key,\n { organizationId: input.organizationId, policy: structuredClone(policy) },\n MAX_POLICIES,\n );\n }\n}\n\n/** Caller must first correlate the exact response and durably acknowledge it. */\nexport function rememberAcknowledgedContainerHead(\n execSql: ExecSql,\n plan: Pick<\n AuthoredContainerMutationHead,\n \"body\" | \"event\" | \"eventHash\" | \"manifest\" | \"manifestHash\" | \"state\"\n >,\n): HeldContainerHead {\n const head: HeldContainerHead = {\n state: plan.state,\n bundle: {\n event: readCanonicalRecord(\n {\n event: plan.event,\n eventHash: plan.eventHash,\n body: plan.body,\n },\n \"Acknowledged container event\",\n ),\n manifest: readCanonicalRecord(\n plan.manifest,\n \"Acknowledged container manifest\",\n ),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Acknowledged container state\"),\n },\n };\n rememberHead(execSql, plan, () => head);\n return head;\n}\n\nexport function heldContainerSnapshot(\n execSql: ExecSql,\n organizationId: string,\n) {\n const held = heldContainers(execSql);\n return {\n heads: new Map(\n [...held.heads]\n .filter(([, head]) => head.state.organizationId === organizationId)\n .map(([id, head]) => [id, structuredClone(head)] as const),\n ),\n policies: [...held.policies.values()]\n .filter((entry) => entry.organizationId === organizationId)\n .map((entry) => structuredClone(entry.policy)),\n };\n}\n\n/** Resolve parent edges only; parentManifestHash is historical keying evidence. */\nexport function heldContainerPath(\n heads: ReadonlyMap<string, HeldContainerHead>,\n containerId: string,\n): HeldContainerHead[] | null {\n const path: HeldContainerHead[] = [];\n const seen = new Set<string>();\n let id: string | null = containerId;\n while (id !== null) {\n if (seen.has(id) || path.length >= MAX_CONTAINER_PATH_LENGTH) return null;\n seen.add(id);\n const head = heads.get(id);\n if (!head) return null;\n path.unshift(head);\n id = head.state.parentContainerId;\n }\n return path;\n}\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
2
2
|
import { ProjectionDependencyUnavailableError } from "../shared/dependencyUnavailable.js";
|
|
3
3
|
import { errorMessage } from "../shared/errorMessage.js";
|
|
4
|
+
import { isKeyingVerificationError } from "../shared/securityIncidents.js";
|
|
4
5
|
import { isDatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
|
|
5
6
|
import { rethrowProjectionVerificationCancelled } from "./types.js";
|
|
6
7
|
const KEYING_VERIFICATION_CONTEXT_LIMIT = 16;
|
|
7
|
-
const KEYING_VERIFICATION_CAUSE_LIMIT = 16;
|
|
8
8
|
/** Use only for synchronous parsing of received protocol material. */
|
|
9
9
|
export function readKeyingVerificationShape(read) {
|
|
10
10
|
try {
|
|
@@ -16,67 +16,11 @@ export function readKeyingVerificationShape(read) {
|
|
|
16
16
|
throw new KeyingVerificationError("invalid_shape", errorMessage(error));
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
-
/**
|
|
20
|
-
* Preserve identity and projection verification failures across workflow
|
|
21
|
-
* boundaries that intentionally soften ordinary transport or availability
|
|
22
|
-
* errors. These failures are terminal: retrying or falling back could continue
|
|
23
|
-
* with an untrusted identity.
|
|
24
|
-
*/
|
|
25
|
-
export function isKeyingVerificationError(error) {
|
|
26
|
-
return (error instanceof KeyingVerificationError ||
|
|
27
|
-
(error instanceof Error && error.name === "KeyingVerificationError"));
|
|
28
|
-
}
|
|
29
19
|
export function rethrowKeyingVerificationError(error) {
|
|
30
20
|
if (isKeyingVerificationError(error)) {
|
|
31
21
|
throw error;
|
|
32
22
|
}
|
|
33
23
|
}
|
|
34
|
-
function keyingVerificationErrorInCauseChain(error) {
|
|
35
|
-
let current = error;
|
|
36
|
-
const seen = new Set();
|
|
37
|
-
for (let depth = 0; depth < KEYING_VERIFICATION_CAUSE_LIMIT; depth += 1) {
|
|
38
|
-
if (isKeyingVerificationError(current))
|
|
39
|
-
return current;
|
|
40
|
-
if (!(current instanceof Error) || seen.has(current))
|
|
41
|
-
return null;
|
|
42
|
-
seen.add(current);
|
|
43
|
-
current = current.cause;
|
|
44
|
-
}
|
|
45
|
-
return null;
|
|
46
|
-
}
|
|
47
|
-
export async function reportKeyingVerificationErrorInCauseChain(error, reporter, context) {
|
|
48
|
-
const verificationError = keyingVerificationErrorInCauseChain(error);
|
|
49
|
-
if (!verificationError)
|
|
50
|
-
return false;
|
|
51
|
-
try {
|
|
52
|
-
await reporter?.(verificationError, context);
|
|
53
|
-
}
|
|
54
|
-
catch {
|
|
55
|
-
// Incident reporting is best-effort at this boundary. It must never replace
|
|
56
|
-
// the boundary behavior that stopped use of untrusted data.
|
|
57
|
-
}
|
|
58
|
-
return true;
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Persist a terminal integrity failure before preserving the boundary error.
|
|
62
|
-
* Call only outside an open persistence transaction: the reporter serializes
|
|
63
|
-
* its own write and awaiting it from that transaction would deadlock.
|
|
64
|
-
*/
|
|
65
|
-
export async function reportAndRethrowKeyingVerificationError(error, reporter, context) {
|
|
66
|
-
const reported = await reportKeyingVerificationErrorInCauseChain(error, reporter, context);
|
|
67
|
-
if (!reported)
|
|
68
|
-
return;
|
|
69
|
-
throw error;
|
|
70
|
-
}
|
|
71
|
-
export async function runWithSecurityIncidentReporting(reporter, context, operation) {
|
|
72
|
-
try {
|
|
73
|
-
return await operation();
|
|
74
|
-
}
|
|
75
|
-
catch (error) {
|
|
76
|
-
await reportAndRethrowKeyingVerificationError(error, reporter, context);
|
|
77
|
-
throw error;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
24
|
export function rethrowDatabaseUnavailableError(error) {
|
|
81
25
|
if (isDatabaseUnavailableError(error)) {
|
|
82
26
|
throw error;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.js","sourceRoot":"","sources":["error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,iCAAiC,CAAC;AACvF,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"error.js","sourceRoot":"","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G,OAAO,KAAK,OAAO,EAAE,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../shared/dependencyUnavailable\";\nimport { errorMessage } from \"../shared/errorMessage\";\nimport { isKeyingVerificationError } from \"../shared/securityIncidents\";\nimport { isDatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nimport { rethrowProjectionVerificationCancelled } from \"./types\";\n\nconst KEYING_VERIFICATION_CONTEXT_LIMIT = 16;\n\n/** Use only for synchronous parsing of received protocol material. */\nexport function readKeyingVerificationShape<T>(read: () => T): T {\n try {\n return read();\n } catch (error) {\n if (error instanceof KeyingVerificationError) throw error;\n throw new KeyingVerificationError(\"invalid_shape\", errorMessage(error));\n }\n}\n\nexport function rethrowKeyingVerificationError(error: unknown): void {\n if (isKeyingVerificationError(error)) {\n throw error;\n }\n}\n\nexport function rethrowDatabaseUnavailableError(error: unknown): void {\n if (isDatabaseUnavailableError(error)) {\n throw error;\n }\n}\n\nexport function rethrowProjectionVerificationBoundaryError(\n error: unknown,\n): void {\n rethrowDatabaseUnavailableError(error);\n rethrowProjectionVerificationCancelled(error);\n if (error instanceof ProjectionDependencyUnavailableError) throw error;\n}\n\n/**\n * The verification layer reports a shape or hash failure in received protocol\n * material with a plain `Error` (or a `SyntaxError` from decoding its JSON).\n * Anything more specific is not evidence about that material: a boundary error\n * is retryable, a `TypeError` or other typed runtime failure is a defect, and a\n * non-Error value is a foreign throw. Those keep their type so callers can\n * classify them instead of recording them as tampering.\n */\nfunction isReceivedMaterialShapeFailure(error: unknown): error is Error {\n return (\n error instanceof Error &&\n (Object.getPrototypeOf(error) === Error.prototype ||\n error instanceof SyntaxError)\n );\n}\n\n/** Classify the failure of an async verification pass; never returns. */\nexport function throwKeyingVerificationShapeFailure(error: unknown): never {\n rethrowProjectionVerificationBoundaryError(error);\n if (\n isKeyingVerificationError(error) ||\n !isReceivedMaterialShapeFailure(error)\n )\n throw error;\n throw new KeyingVerificationError(\"invalid_shape\", error.message);\n}\n\nexport function throwKeyingVerificationErrorWithContext(\n error: unknown,\n context: string,\n): never {\n // Availability and cancellation keep their retryable types across contexts.\n rethrowProjectionVerificationBoundaryError(error);\n if (isKeyingVerificationError(error)) {\n // Preserve identity so nested reporting boundaries persist one incident.\n // The incident's operation supplies boundary context without minting a new\n // verification error that could bypass identity-based deduplication. Keep\n // the boundary labels non-enumerably for host-side diagnostics.\n try {\n const previous = Reflect.get(error, \"keyingVerificationContexts\");\n const contexts = Array.isArray(previous)\n ? [...previous, context].slice(-KEYING_VERIFICATION_CONTEXT_LIMIT)\n : [context];\n Object.defineProperty(error, \"keyingVerificationContexts\", {\n configurable: true,\n enumerable: false,\n value: contexts,\n });\n } catch {\n // A frozen foreign error still preserves its identity and code.\n }\n throw error;\n }\n const message = errorMessage(error);\n throw new Error(`${context}: ${message}`);\n}\n"]}
|