@tearleads/client-sdk 0.1.220 → 0.1.221
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/organizations/recipientAdmission.js +1 -1
- package/client/organizations/recipientAdmission.js.map +1 -1
- package/data/keyingProjectionVerification/error.js +1 -1
- package/data/keyingProjectionVerification/error.js.map +1 -1
- package/data/sync/syncCoordinator.d.ts +1 -1
- package/data/sync/syncCoordinator.js +1 -1
- package/data/sync/syncCoordinator.js.map +1 -1
- package/data/trustedUserIdentity/pinnedResolution.js +1 -1
- package/data/trustedUserIdentity/pinnedResolution.js.map +1 -1
- package/data/trustedUserIdentity/service.js +1 -1
- package/data/trustedUserIdentity/service.js.map +1 -1
- package/package.json +1 -1
- package/workflows/container-contents/documentLinks/index.js +1 -1
- package/workflows/container-contents/documentLinks/index.js.map +1 -1
- package/workflows/documents/writerKeys.js +1 -1
- package/workflows/documents/writerKeys.js.map +1 -1
- /package/data/{sync → sqlite/availability}/databaseUnavailable.d.ts +0 -0
- /package/data/{sync → sqlite/availability}/databaseUnavailable.js +0 -0
- /package/data/{sync → sqlite/availability}/databaseUnavailable.js.map +0 -0
|
@@ -2,7 +2,7 @@ import { computeUserIdentityBundleFingerprint } from "../../internal/crypto/inde
|
|
|
2
2
|
import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
|
|
3
3
|
import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
|
|
4
4
|
import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
|
|
5
|
-
import { DatabaseUnavailableError } from "../../data/
|
|
5
|
+
import { DatabaseUnavailableError } from "../../data/sqlite/availability/databaseUnavailable.js";
|
|
6
6
|
import { UnverifiedUserIdentityError, } from "../../data/trustedUserIdentity/index.js";
|
|
7
7
|
import { isRosterVouchedRecipient, } from "../../workflows/organizations/memberships/rosterVouchedAdmission.js";
|
|
8
8
|
import { currentOrganizationMutation, currentOrganizationSigningMutation, } from "./principalMutationScope.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recipientAdmission.js","sourceRoot":"","sources":["recipientAdmission.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,mBAAmB,CAAC;AAEzE,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAG/F,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC/E,OAAO,EAGL,2BAA2B,GAC5B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,wBAAwB,GAGzB,MAAM,kEAAkE,CAAC;AAE1E,OAAO,EACL,2BAA2B,EAC3B,kCAAkC,GACnC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAE1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAOrE,+EAA+E;AAC/E,MAAM,mBAAoB,SAAQ,KAAK;CAAG;AAE1C,KAAK,UAAU,SAAS,CACtB,SAAuE;IAEvE,OAAO;QACL,2BAA2B,EAAE,SAAS,CAAC,2BAA2B;QAClE,yBAAyB,EACvB,MAAM,oCAAoC,CAAC,SAAS,CAAC;QACvD,qBAAqB,EAAE,SAAS,CAAC,qBAAqB;QACtD,QAAQ,EAAE,KAAK;KAChB,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,KAAK,UAAU,8BAA8B,CAC3C,MAAc,EACd,QAAiC,EACjC,QAAqC,EACrC,aAAuC;IAEvC,0EAA0E;IAC1E,IAAI,CAAC,QAAQ,CAAC,oBAAoB;QAChC,OAAO,wBAAwB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACpD,IAAI,CAAC;QACH,OAAO,MAAM,QAAQ,CAAC,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CAAC,EAAE,CAAC;YAC1E,sEAAsE;YACtE,0EAA0E;YAC1E,MAAM,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QACxE,CAAC;aAAM,IACL,SAAS,CAAC,MAAM,KAAK,QAAQ;YAC7B,CAAC,6BAA6B,CAAC,OAAO,CAAC,YAAY,EAAE,SAAS,CAAC,IAAI,CAAC,EACpE,CAAC;YACD,MAAM,IAAI,oCAAoC,CAC5C,uDAAuD,CACxD,CAAC;QACJ,CAAC;QACD,aAAa,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAC8C,EAC9C,MAAc;IAEd,MAAM,QAAQ,GAAG,kCAAkC,CAAC,OAAO,CAAC,CAAC;IAC7D,MAAM,SAAS,GAAG,MAAM,2BAA2B,CACjD,OAAO,EACP,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAC9B,MAAM,CACP,CAAC;IACF,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE;QAC1B,MAAM,IAAI,wBAAwB,CAChC,mEAAmE,CACpE,CAAC;IACJ,OAAO,EAAE,GAAG,QAAQ,EAAE,SAAS,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { computeUserIdentityBundleFingerprint } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../../data/sync/databaseUnavailable\";\nimport {\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n UnverifiedUserIdentityError,\n} from \"../../data/trustedUserIdentity\";\nimport {\n isRosterVouchedRecipient,\n type RosterAdmissionEvidence,\n type RosterAdmissionPin,\n} from \"../../workflows/organizations/memberships/rosterVouchedAdmission\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport {\n currentOrganizationMutation,\n currentOrganizationSigningMutation,\n} from \"./principalMutationScope\";\nimport { createRosterAdmissionEvidence } from \"./rosterAdmissionEvidence\";\n\nexport { loadServedStateEnvelopes } from \"./rosterAdmissionEvidence\";\n\ntype AdmissionRuntimeService = Pick<\n InternalRuntime,\n \"identityLinks\" | \"sessionGeneration\" | \"workflowInput\"\n>;\n\n/** Thrown inside the staged scope so a refused recipient publishes nothing. */\nclass RecipientNotVouched extends Error {}\n\nasync function stagedPin(\n candidate: NonNullable<Awaited<ReturnType<StagedUserIdentityResolver>>>,\n): Promise<RosterAdmissionPin> {\n return {\n encapsulationKeyFingerprint: candidate.encapsulationKeyFingerprint,\n identityBundleFingerprint:\n await computeUserIdentityBundleFingerprint(candidate),\n signingKeyFingerprint: candidate.signingKeyFingerprint,\n verified: false,\n };\n}\n\n/**\n * Admit against the server's first answers without pinning them: the\n * recipient's answer, and that of any historical signer the chain needs but\n * this device has not pinned (a departed admin seen only in older Members\n * states), are staged. Each is checked against its committed Members bundle,\n * and all are pinned as observed only once the signed roster vouches for the\n * recipient's exact identity bundle. A substituted answer leaves no pin, so a\n * corrected retry or the honest identity link still succeeds.\n */\nasync function isStagedRosterVouchedRecipient(\n userId: string,\n evidence: RosterAdmissionEvidence,\n resolver: TrustedUserIdentityResolver,\n assertCurrent: (() => void) | undefined,\n): Promise<boolean> {\n // Without staging, admit only a durable pin: never pin before the roster.\n if (!resolver.withPinnedIdentities)\n return isRosterVouchedRecipient(userId, evidence);\n try {\n return await resolver.withPinnedIdentities(\n [userId],\n async (resolve) => {\n const candidate = await resolve(userId);\n const vouched =\n candidate !== null &&\n (await isRosterVouchedRecipient(userId, {\n ...evidence,\n loadPin: async (id) => {\n const pin = await evidence.loadPin(id);\n if (pin) return pin;\n const staged = id === userId ? candidate : await resolve(id);\n return staged ? stagedPin(staged) : null;\n },\n }));\n if (!vouched) throw new RecipientNotVouched();\n return true;\n },\n { publish: true, assertCurrent },\n );\n } catch (error) {\n if (error instanceof RecipientNotVouched) return false;\n throw error;\n }\n}\n\n/**\n * Whether the signed roster vouches for `userId` on this device, for exactly\n * the domain-scoped signing and encapsulation identity bundle the server\n * serves. Served material that fails verification is recorded as a security\n * incident before the error propagates.\n */\nexport function isReportedRosterVouchedRecipient(input: {\n readonly evidence: RosterAdmissionEvidence;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly userId: string;\n /** The admission's lifetime, checked inside every pin write. */\n readonly assertCurrent?: (() => void) | undefined;\n}): Promise<boolean> {\n const { evidence, userId } = input;\n return runWithSecurityIncidentReporting(\n input.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"container.share.roster_vouch\",\n organizationId: input.organizationId,\n },\n () =>\n isStagedRosterVouchedRecipient(\n userId,\n evidence,\n input.resolveTrustedUserIdentity,\n input.assertCurrent,\n ),\n );\n}\n\ntype RecipientAdmission =\n | { readonly status: \"verified\" }\n | { readonly status: \"roster\"; readonly head: ReferencedPrincipalHead };\n\nasync function requireOrganizationRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<RecipientAdmission> {\n try {\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n return { status: \"verified\" };\n } catch (error) {\n const runtime = service.workflowInput();\n const organizationId = runtime.auth.organizationId;\n if (!(error instanceof UnverifiedUserIdentityError) || !organizationId)\n throw error;\n const evidence = createRosterAdmissionEvidence(\n service,\n admittingExecSql,\n organizationId,\n );\n if (!evidence) throw error;\n let head: ReferencedPrincipalHead | undefined;\n const vouched = await isReportedRosterVouchedRecipient({\n assertCurrent: admissionLifetime(service, admittingExecSql),\n evidence: {\n ...evidence,\n async loadCurrentMembers() {\n const members = await evidence.loadCurrentMembers();\n head = members.head;\n return members;\n },\n },\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n userId,\n });\n if (!vouched || !head) throw error;\n return { status: \"roster\", head };\n }\n}\n\nfunction admissionLifetime(service: AdmissionRuntimeService, execSql: ExecSql) {\n const scope = currentOrganizationMutation(service);\n return () => {\n if (scope.runtime.infra.execSql !== execSql || !scope.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active identity or database changed while admitting this user. Try again.\",\n );\n };\n}\n\n/** Full-bundle roster authentication admits read, write, and admin shares. */\nexport async function requireShareRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n _accessLevel: ContainerAccessLevel,\n): Promise<void> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n await requireOrganizationRecipient(service, admittingExecSql, userId);\n assertCurrent();\n}\n\nexport type GroupMemberAdmission = (\n members: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n) => Promise<void>;\n\n/** The proof is usable only at its exact Members head, within this runtime. */\nexport async function requireGroupMemberAdmission(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<GroupMemberAdmission> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n const admission = await requireOrganizationRecipient(\n service,\n admittingExecSql,\n userId,\n );\n assertCurrent();\n return async (members) => {\n assertCurrent();\n if (!members.currentProjection.some((member) => member.userId === userId)) {\n // A retry may find the user removed since the proof. Enrollment still\n // requires this device's self/link anchor, never an earlier roster proof.\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n } else if (\n admission.status === \"roster\" &&\n !principalHeadMatchesReference(members.currentState, admission.head)\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Members changed while admitting this user. Try again.\",\n );\n }\n assertCurrent();\n };\n}\n\n/** Capture the mutation scope before obtaining its head-bound admission proof. */\nexport async function admitGroupMutation(\n service: AdmissionRuntimeService &\n Pick<InternalRuntime, \"identityTrustDomain\">,\n userId: string,\n) {\n const mutation = currentOrganizationSigningMutation(service);\n const admission = await requireGroupMemberAdmission(\n service,\n mutation.runtime.infra.execSql,\n userId,\n );\n if (!mutation.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n return { ...mutation, admission };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"recipientAdmission.js","sourceRoot":"","sources":["recipientAdmission.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,mBAAmB,CAAC;AAEzE,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAE/F,OAAO,EAAE,wBAAwB,EAAE,MAAM,oDAAoD,CAAC;AAE9F,OAAO,EAGL,2BAA2B,GAC5B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,wBAAwB,GAGzB,MAAM,kEAAkE,CAAC;AAE1E,OAAO,EACL,2BAA2B,EAC3B,kCAAkC,GACnC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAE1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAOrE,+EAA+E;AAC/E,MAAM,mBAAoB,SAAQ,KAAK;CAAG;AAE1C,KAAK,UAAU,SAAS,CACtB,SAAuE;IAEvE,OAAO;QACL,2BAA2B,EAAE,SAAS,CAAC,2BAA2B;QAClE,yBAAyB,EACvB,MAAM,oCAAoC,CAAC,SAAS,CAAC;QACvD,qBAAqB,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undleFingerprint } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { DatabaseUnavailableError } from \"../../data/sqlite/availability/databaseUnavailable\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n UnverifiedUserIdentityError,\n} from \"../../data/trustedUserIdentity\";\nimport {\n isRosterVouchedRecipient,\n type RosterAdmissionEvidence,\n type RosterAdmissionPin,\n} from \"../../workflows/organizations/memberships/rosterVouchedAdmission\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport {\n currentOrganizationMutation,\n currentOrganizationSigningMutation,\n} from \"./principalMutationScope\";\nimport { createRosterAdmissionEvidence } from \"./rosterAdmissionEvidence\";\n\nexport { loadServedStateEnvelopes } from \"./rosterAdmissionEvidence\";\n\ntype AdmissionRuntimeService = Pick<\n InternalRuntime,\n \"identityLinks\" | \"sessionGeneration\" | \"workflowInput\"\n>;\n\n/** Thrown inside the staged scope so a refused recipient publishes nothing. */\nclass RecipientNotVouched extends Error {}\n\nasync function stagedPin(\n candidate: NonNullable<Awaited<ReturnType<StagedUserIdentityResolver>>>,\n): Promise<RosterAdmissionPin> {\n return {\n encapsulationKeyFingerprint: candidate.encapsulationKeyFingerprint,\n identityBundleFingerprint:\n await computeUserIdentityBundleFingerprint(candidate),\n signingKeyFingerprint: candidate.signingKeyFingerprint,\n verified: false,\n };\n}\n\n/**\n * Admit against the server's first answers without pinning them: the\n * recipient's answer, and that of any historical signer the chain needs but\n * this device has not pinned (a departed admin seen only in older Members\n * states), are staged. Each is checked against its committed Members bundle,\n * and all are pinned as observed only once the signed roster vouches for the\n * recipient's exact identity bundle. A substituted answer leaves no pin, so a\n * corrected retry or the honest identity link still succeeds.\n */\nasync function isStagedRosterVouchedRecipient(\n userId: string,\n evidence: RosterAdmissionEvidence,\n resolver: TrustedUserIdentityResolver,\n assertCurrent: (() => void) | undefined,\n): Promise<boolean> {\n // Without staging, admit only a durable pin: never pin before the roster.\n if (!resolver.withPinnedIdentities)\n return isRosterVouchedRecipient(userId, evidence);\n try {\n return await resolver.withPinnedIdentities(\n [userId],\n async (resolve) => {\n const candidate = await resolve(userId);\n const vouched =\n candidate !== null &&\n (await isRosterVouchedRecipient(userId, {\n ...evidence,\n loadPin: async (id) => {\n const pin = await evidence.loadPin(id);\n if (pin) return pin;\n const staged = id === userId ? candidate : await resolve(id);\n return staged ? stagedPin(staged) : null;\n },\n }));\n if (!vouched) throw new RecipientNotVouched();\n return true;\n },\n { publish: true, assertCurrent },\n );\n } catch (error) {\n if (error instanceof RecipientNotVouched) return false;\n throw error;\n }\n}\n\n/**\n * Whether the signed roster vouches for `userId` on this device, for exactly\n * the domain-scoped signing and encapsulation identity bundle the server\n * serves. Served material that fails verification is recorded as a security\n * incident before the error propagates.\n */\nexport function isReportedRosterVouchedRecipient(input: {\n readonly evidence: RosterAdmissionEvidence;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly userId: string;\n /** The admission's lifetime, checked inside every pin write. */\n readonly assertCurrent?: (() => void) | undefined;\n}): Promise<boolean> {\n const { evidence, userId } = input;\n return runWithSecurityIncidentReporting(\n input.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"container.share.roster_vouch\",\n organizationId: input.organizationId,\n },\n () =>\n isStagedRosterVouchedRecipient(\n userId,\n evidence,\n input.resolveTrustedUserIdentity,\n input.assertCurrent,\n ),\n );\n}\n\ntype RecipientAdmission =\n | { readonly status: \"verified\" }\n | { readonly status: \"roster\"; readonly head: ReferencedPrincipalHead };\n\nasync function requireOrganizationRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<RecipientAdmission> {\n try {\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n return { status: \"verified\" };\n } catch (error) {\n const runtime = service.workflowInput();\n const organizationId = runtime.auth.organizationId;\n if (!(error instanceof UnverifiedUserIdentityError) || !organizationId)\n throw error;\n const evidence = createRosterAdmissionEvidence(\n service,\n admittingExecSql,\n organizationId,\n );\n if (!evidence) throw error;\n let head: ReferencedPrincipalHead | undefined;\n const vouched = await isReportedRosterVouchedRecipient({\n assertCurrent: admissionLifetime(service, admittingExecSql),\n evidence: {\n ...evidence,\n async loadCurrentMembers() {\n const members = await evidence.loadCurrentMembers();\n head = members.head;\n return members;\n },\n },\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n userId,\n });\n if (!vouched || !head) throw error;\n return { status: \"roster\", head };\n }\n}\n\nfunction admissionLifetime(service: AdmissionRuntimeService, execSql: ExecSql) {\n const scope = currentOrganizationMutation(service);\n return () => {\n if (scope.runtime.infra.execSql !== execSql || !scope.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active identity or database changed while admitting this user. Try again.\",\n );\n };\n}\n\n/** Full-bundle roster authentication admits read, write, and admin shares. */\nexport async function requireShareRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n _accessLevel: ContainerAccessLevel,\n): Promise<void> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n await requireOrganizationRecipient(service, admittingExecSql, userId);\n assertCurrent();\n}\n\nexport type GroupMemberAdmission = (\n members: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n) => Promise<void>;\n\n/** The proof is usable only at its exact Members head, within this runtime. */\nexport async function requireGroupMemberAdmission(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<GroupMemberAdmission> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n const admission = await requireOrganizationRecipient(\n service,\n admittingExecSql,\n userId,\n );\n assertCurrent();\n return async (members) => {\n assertCurrent();\n if (!members.currentProjection.some((member) => member.userId === userId)) {\n // A retry may find the user removed since the proof. Enrollment still\n // requires this device's self/link anchor, never an earlier roster proof.\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n } else if (\n admission.status === \"roster\" &&\n !principalHeadMatchesReference(members.currentState, admission.head)\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Members changed while admitting this user. Try again.\",\n );\n }\n assertCurrent();\n };\n}\n\n/** Capture the mutation scope before obtaining its head-bound admission proof. */\nexport async function admitGroupMutation(\n service: AdmissionRuntimeService &\n Pick<InternalRuntime, \"identityTrustDomain\">,\n userId: string,\n) {\n const mutation = currentOrganizationSigningMutation(service);\n const admission = await requireGroupMemberAdmission(\n service,\n mutation.runtime.infra.execSql,\n userId,\n );\n if (!mutation.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n return { ...mutation, admission };\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
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 { isDatabaseUnavailableError } from "../
|
|
4
|
+
import { isDatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
|
|
5
5
|
import { rethrowProjectionVerificationCancelled } from "./types.js";
|
|
6
6
|
const KEYING_VERIFICATION_CONTEXT_LIMIT = 16;
|
|
7
7
|
const KEYING_VERIFICATION_CAUSE_LIMIT = 16;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.js","sourceRoot":"","sources":["error.ts"],"names":[],"mappings":"AAAA,OAAO,EAA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CAAC;YACH,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,4BAA4B,CAAC,CAAC;YAClE,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;gBACtC,CAAC,CAAC,CAAC,GAAG,QAAQ,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,iCAAiC,CAAC;gBAClE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;YACd,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,4BAA4B,EAAE;gBACzD,YAAY,EAAE,IAAI;gBAClB,UAAU,EAAE,KAAK;gBACjB,KAAK,EAAE,QAAQ;aAChB,CAAC,CAAC;QACL,CAAC;QAAC,MAAM,CAAC;YACP,gEAAgE;QAClE,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;IACD,MAAM,OAAO,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;IACpC,MAAM,IAAI,KAAK,CAAC,GAAG,OAAO,KAAK,OAAO,EAAE,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../shared/dependencyUnavailable\";\nimport { errorMessage } from \"../shared/errorMessage\";\nimport type {\n SecurityIncidentContext,\n SecurityIncidentReporter,\n} from \"../shared/securityIncidents\";\nimport { isDatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nimport { rethrowProjectionVerificationCancelled } from \"./types\";\n\nconst KEYING_VERIFICATION_CONTEXT_LIMIT = 16;\nconst KEYING_VERIFICATION_CAUSE_LIMIT = 16;\n\n/** Use only for synchronous parsing of received protocol material. */\nexport function readKeyingVerificationShape<T>(read: () => T): T {\n try {\n return read();\n } catch (error) {\n if (error instanceof KeyingVerificationError) throw error;\n throw new KeyingVerificationError(\"invalid_shape\", errorMessage(error));\n }\n}\n\n/**\n * Preserve identity and projection verification failures across workflow\n * boundaries that intentionally soften ordinary transport or availability\n * errors. These failures are terminal: retrying or falling back could continue\n * with an untrusted identity.\n */\nexport function isKeyingVerificationError(\n error: unknown,\n): error is Error & { readonly code?: unknown } {\n return (\n error instanceof KeyingVerificationError ||\n (error instanceof Error && error.name === \"KeyingVerificationError\")\n );\n}\n\nexport function rethrowKeyingVerificationError(error: unknown): void {\n if (isKeyingVerificationError(error)) {\n throw error;\n }\n}\n\nfunction keyingVerificationErrorInCauseChain(\n error: unknown,\n): (Error & { readonly code?: unknown }) | null {\n let current = error;\n const seen = new Set<unknown>();\n for (let depth = 0; depth < KEYING_VERIFICATION_CAUSE_LIMIT; depth += 1) {\n if (isKeyingVerificationError(current)) return current;\n if (!(current instanceof Error) || seen.has(current)) return null;\n seen.add(current);\n current = current.cause;\n }\n return null;\n}\n\nexport async function reportKeyingVerificationErrorInCauseChain(\n error: unknown,\n reporter: SecurityIncidentReporter | undefined,\n context: SecurityIncidentContext,\n): Promise<boolean> {\n const verificationError = keyingVerificationErrorInCauseChain(error);\n if (!verificationError) return false;\n try {\n await reporter?.(verificationError, context);\n } catch {\n // Incident reporting is best-effort at this boundary. It must never replace\n // the boundary behavior that stopped use of untrusted data.\n }\n return true;\n}\n\n/**\n * Persist a terminal integrity failure before preserving the boundary error.\n * Call only outside an open persistence transaction: the reporter serializes\n * its own write and awaiting it from that transaction would deadlock.\n */\nexport async function reportAndRethrowKeyingVerificationError(\n error: unknown,\n reporter: SecurityIncidentReporter | undefined,\n context: SecurityIncidentContext,\n): Promise<void> {\n const reported = await reportKeyingVerificationErrorInCauseChain(\n error,\n reporter,\n context,\n );\n if (!reported) return;\n throw error;\n}\n\nexport async function runWithSecurityIncidentReporting<T>(\n reporter: SecurityIncidentReporter | undefined,\n context: SecurityIncidentContext,\n operation: () => Promise<T>,\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n await reportAndRethrowKeyingVerificationError(error, reporter, context);\n throw error;\n }\n}\n\nexport function rethrowDatabaseUnavailableError(error: unknown): void {\n if (isDatabaseUnavailableError(error)) {\n throw error;\n }\n}\n\nexport function rethrowProjectionVerificationBoundaryError(\n error: unknown,\n): void {\n rethrowDatabaseUnavailableError(error);\n rethrowProjectionVerificationCancelled(error);\n if (error instanceof ProjectionDependencyUnavailableError) throw error;\n}\n\n/**\n * The verification layer reports a shape or hash failure in received protocol\n * material with a plain `Error` (or a `SyntaxError` from decoding its JSON).\n * Anything more specific is not evidence about that material: a boundary error\n * is retryable, a `TypeError` or other typed runtime failure is a defect, and a\n * non-Error value is a foreign throw. Those keep their type so callers can\n * classify them instead of recording them as tampering.\n */\nfunction isReceivedMaterialShapeFailure(error: unknown): error is Error {\n return (\n error instanceof Error &&\n (Object.getPrototypeOf(error) === Error.prototype ||\n error instanceof SyntaxError)\n );\n}\n\n/** Classify the failure of an async verification pass; never returns. */\nexport function throwKeyingVerificationShapeFailure(error: unknown): never {\n rethrowProjectionVerificationBoundaryError(error);\n if (\n isKeyingVerificationError(error) ||\n !isReceivedMaterialShapeFailure(error)\n )\n throw error;\n throw new KeyingVerificationError(\"invalid_shape\", error.message);\n}\n\nexport function throwKeyingVerificationErrorWithContext(\n error: unknown,\n context: string,\n): never {\n // Availability and cancellation keep their retryable types across contexts.\n rethrowProjectionVerificationBoundaryError(error);\n if (isKeyingVerificationError(error)) {\n // Preserve identity so nested reporting boundaries persist one incident.\n // The incident's operation supplies boundary context without minting a new\n // verification error that could bypass identity-based deduplication. Keep\n // the boundary labels non-enumerably for host-side diagnostics.\n try {\n const previous = Reflect.get(error, \"keyingVerificationContexts\");\n const contexts = Array.isArray(previous)\n ? [...previous, context].slice(-KEYING_VERIFICATION_CONTEXT_LIMIT)\n : [context];\n Object.defineProperty(error, \"keyingVerificationContexts\", {\n configurable: true,\n enumerable: false,\n value: contexts,\n });\n } catch {\n // A frozen foreign error still preserves its identity and code.\n }\n throw error;\n }\n const message = errorMessage(error);\n throw new Error(`${context}: ${message}`);\n}\n"]}
|
|
@@ -3,8 +3,8 @@ import { type SyncIdleOptions } from "./coordinatorPump.js";
|
|
|
3
3
|
import type { SyncLane, SyncLaneConfig } from "./syncLaneConfig.js";
|
|
4
4
|
import type { DomainSyncSnapshot } from "./syncTelemetry.js";
|
|
5
5
|
import type { UploadSyncLane, UploadSyncLaneOptions } from "./uploadLane.js";
|
|
6
|
+
export { isDatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
|
|
6
7
|
export type { SyncIdleOptions } from "./coordinatorPump.js";
|
|
7
|
-
export { isDatabaseUnavailableError } from "./databaseUnavailable.js";
|
|
8
8
|
export type { SyncLane, SyncLaneConfig } from "./syncLaneConfig.js";
|
|
9
9
|
export { didRegainSyncPrerequisites, type SyncRuntimeStatus, } from "./syncPrerequisites.js";
|
|
10
10
|
export type { DomainSyncSnapshot, SyncLaneLastAction, SyncLanePhase, SyncLaneProgress, SyncLaneSnapshot, SyncLaneStatus, } from "./syncTelemetry.js";
|
|
@@ -6,7 +6,7 @@ import { beginUploadLane } from "./uploadLane.js";
|
|
|
6
6
|
// Re-exported here because lanes reach it as a shouldIgnoreError alongside the
|
|
7
7
|
// rest of the coordinator surface; it lives beside this coordinator with the
|
|
8
8
|
// error type it discriminates on.
|
|
9
|
-
export { isDatabaseUnavailableError } from "
|
|
9
|
+
export { isDatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
|
|
10
10
|
export { didRegainSyncPrerequisites, } from "./syncPrerequisites.js";
|
|
11
11
|
const coordinatorsByScope = new WeakMap();
|
|
12
12
|
function createSyncLaneHandle(coordinatorState, lane) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncCoordinator.js","sourceRoot":"","sources":["syncCoordinator.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,eAAe,EACf,oBAAoB,EAEpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,kBAAkB,EAClB,2BAA2B,EAC3B,8BAA8B,GAC/B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,yBAAyB,EAAE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C,CAAC;AAC3E,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,WAAwB,EACxB,GAAW,EACX,OAA+B;IAE/B,OAAO,gCAAgC,CAAC,WAAW,CAAC,CAAC,eAAe,CAClE,GAAG,EACH,OAAO,CACR,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oCAAoC,CAClD,WAAwB,EACxB,OAAyB;IAEzB,OAAO,CACL,mBAAmB,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC,OAAO,CAAC;QAC1D,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CACtB,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../shared/domainScope\";\nimport {\n requestAllPumpDrivenLanes,\n requestLaneSync,\n requestLaneSyncAfter,\n type SyncIdleOptions,\n waitForIdleLanes,\n} from \"./coordinatorPump\";\nimport type {\n DomainSyncCoordinatorState,\n SyncLaneState,\n} from \"./coordinatorState\";\nimport {\n hasPendingLaneWork,\n INITIAL_SYNC_LANE_RUN_STATE,\n publishSyncCoordinatorSnapshot,\n} from \"./coordinatorState\";\nimport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nimport { transitionSyncLaneRequest } from \"./syncLaneMachine\";\nimport type { DomainSyncSnapshot } from \"./syncTelemetry\";\nimport { createDomainSyncSnapshot, createSyncTimestamp } from \"./syncTelemetry\";\nimport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\nimport { beginUploadLane } from \"./uploadLane\";\n\nexport type { SyncIdleOptions } from \"./coordinatorPump\";\n// Re-exported here because lanes reach it as a shouldIgnoreError alongside the\n// rest of the coordinator surface; it lives beside this coordinator with the\n// error type it discriminates on.\nexport { isDatabaseUnavailableError } from \"./databaseUnavailable\";\nexport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nexport {\n didRegainSyncPrerequisites,\n type SyncRuntimeStatus,\n} from \"./syncPrerequisites\";\nexport type {\n DomainSyncSnapshot,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./syncTelemetry\";\nexport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\n\nexport interface DomainSyncCoordinator {\n beginUploadLane: (\n key: string,\n options?: UploadSyncLaneOptions,\n ) => UploadSyncLane;\n // Drop queued work and refuse new runs; active callbacks retain ownership.\n dispose: () => void;\n getSnapshot: () => DomainSyncSnapshot;\n registerLane: (key: string, config: SyncLaneConfig) => SyncLane;\n // Re-request every pump-driven lane — a manual \"sync now\" that re-drives\n // durable owners stranded by a transient failure. Observational upload rows\n // are updated only by those owners' real attachment upload attempts.\n requestAllLanes: () => void;\n // Request one registered pump lane without re-driving unrelated owners.\n requestLane: (key: string) => void;\n hasPendingWork: () => boolean;\n isDisposed: () => boolean;\n subscribe: (listener: () => void) => () => void;\n waitForIdle: (options?: SyncIdleOptions) => Promise<boolean>;\n}\n\nconst coordinatorsByScope = new WeakMap<DomainScope, DomainSyncCoordinator>();\n\nfunction createSyncLaneHandle(\n coordinatorState: DomainSyncCoordinatorState,\n lane: SyncLaneState,\n): SyncLane {\n return {\n isDisposed: () => coordinatorState.disposed,\n requestSync: () => requestLaneSync(coordinatorState, lane),\n requestSyncAfter: (delayMs) =>\n requestLaneSyncAfter(coordinatorState, lane, delayMs),\n };\n}\n\nfunction createDomainSyncCoordinator(): DomainSyncCoordinator {\n const coordinatorState: DomainSyncCoordinatorState = {\n disposed: false,\n lanes: new Map<string, SyncLaneState>(),\n listeners: new Set(),\n nextRegistrationIndex: 0,\n nextRunOrder: 0,\n wakePump: null,\n pump: null,\n snapshot: createDomainSyncSnapshot({\n hasPendingWork: false,\n lanes: [],\n pumpActive: false,\n }),\n };\n\n return {\n beginUploadLane(key: string, options: UploadSyncLaneOptions = {}) {\n return beginUploadLane(coordinatorState, key, options);\n },\n dispose() {\n coordinatorState.disposed = true;\n // Drop queued work so waitForIdle reports settled immediately and a\n // lane left re-requested by an in-flight run does not survive teardown.\n for (const lane of coordinatorState.lanes.values()) {\n lane.request = transitionSyncLaneRequest(lane.request, {\n type: \"clear\",\n });\n }\n // Publish the final settled snapshot, then release listener closures:\n // the coordinator is dropped from the registry and a remount subscribes\n // to a fresh one.\n publishSyncCoordinatorSnapshot(coordinatorState);\n coordinatorState.listeners.clear();\n },\n getSnapshot() {\n return coordinatorState.snapshot;\n },\n hasPendingWork() {\n return (\n !!coordinatorState.pump ||\n hasPendingLaneWork(coordinatorState.lanes.values())\n );\n },\n isDisposed() {\n return coordinatorState.disposed;\n },\n registerLane(key: string, config: SyncLaneConfig): SyncLane {\n const existingLane = coordinatorState.lanes.get(key);\n if (existingLane) {\n existingLane.config = config;\n existingLane.blobStorageKey = null;\n existingLane.pumpDriven = true;\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, existingLane);\n }\n\n const registeredAt = createSyncTimestamp();\n const nextLane: SyncLaneState = {\n ...INITIAL_SYNC_LANE_RUN_STATE,\n blobStorageKey: null,\n config,\n errorCount: 0,\n key,\n lastAction: \"registered\",\n lastActionAt: registeredAt,\n lastCompletedAt: null,\n lastError: null,\n lastFailedAt: null,\n lastRequestedAt: null,\n lastStartedAt: null,\n progress: null,\n pumpDriven: true,\n registrationIndex: coordinatorState.nextRegistrationIndex,\n requestCount: 0,\n };\n coordinatorState.nextRegistrationIndex += 1;\n coordinatorState.lanes.set(key, nextLane);\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, nextLane);\n },\n requestAllLanes() {\n requestAllPumpDrivenLanes(coordinatorState);\n },\n requestLane(key: string) {\n const lane = coordinatorState.lanes.get(key);\n if (lane?.pumpDriven) {\n requestLaneSync(coordinatorState, lane);\n }\n },\n subscribe(listener: () => void) {\n coordinatorState.listeners.add(listener);\n return () => {\n coordinatorState.listeners.delete(listener);\n };\n },\n waitForIdle(options?: SyncIdleOptions) {\n return waitForIdleLanes(coordinatorState, options);\n },\n };\n}\n\nexport function getOrCreateDomainSyncCoordinator(\n domainScope: DomainScope,\n): DomainSyncCoordinator {\n const existingCoordinator = coordinatorsByScope.get(domainScope);\n if (existingCoordinator) {\n return existingCoordinator;\n }\n\n const nextCoordinator = createDomainSyncCoordinator();\n coordinatorsByScope.set(domainScope, nextCoordinator);\n return nextCoordinator;\n}\n\nexport function hasDomainSyncCoordinatorPendingWork(\n domainScope: DomainScope,\n): boolean {\n return coordinatorsByScope.get(domainScope)?.hasPendingWork() ?? false;\n}\n\n// Re-request every pump-driven lane for a scope: a user-driven \"sync now\" that\n// retries durable work stranded by a transient failure. Observational upload\n// telemetry is never directly pumped. A no-op when no coordinator exists yet\n// (nothing has been synced) or it has been disposed.\nexport function requestAllDomainSyncLanes(domainScope: DomainScope): void {\n coordinatorsByScope.get(domainScope)?.requestAllLanes();\n}\n\nexport function requestDomainSyncLane(\n domainScope: DomainScope,\n key: string,\n): void {\n coordinatorsByScope.get(domainScope)?.requestLane(key);\n}\n\n// Stop admitting work and remove this scope's coordinator. Active callbacks\n// drain under their existing watchdogs; getOrCreate builds a fresh coordinator.\nexport function disposeDomainSyncCoordinator(domainScope: DomainScope): void {\n const coordinator = coordinatorsByScope.get(domainScope);\n if (!coordinator) {\n return;\n }\n\n coordinator.dispose();\n coordinatorsByScope.delete(domainScope);\n}\n\nexport function getDomainSyncCoordinatorSnapshot(\n domainScope: DomainScope,\n): DomainSyncSnapshot {\n return getOrCreateDomainSyncCoordinator(domainScope).getSnapshot();\n}\n\nexport function subscribeToDomainSyncCoordinator(\n domainScope: DomainScope,\n listener: () => void,\n): () => void {\n return getOrCreateDomainSyncCoordinator(domainScope).subscribe(listener);\n}\n\nexport function beginDomainSyncUploadLane(\n domainScope: DomainScope,\n key: string,\n options?: UploadSyncLaneOptions,\n): UploadSyncLane {\n return getOrCreateDomainSyncCoordinator(domainScope).beginUploadLane(\n key,\n options,\n );\n}\n\nexport function waitForDomainSyncCoordinatorToSettle(\n domainScope: DomainScope,\n options?: SyncIdleOptions,\n): Promise<boolean> {\n return (\n coordinatorsByScope.get(domainScope)?.waitForIdle(options) ??\n Promise.resolve(true)\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncCoordinator.js","sourceRoot":"","sources":["syncCoordinator.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,eAAe,EACf,oBAAoB,EAEpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,kBAAkB,EAClB,2BAA2B,EAC3B,8BAA8B,GAC/B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEhF,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,+EAA+E;AAC/E,6EAA6E;AAC7E,kCAAkC;AAClC,OAAO,EAAE,0BAA0B,EAAE,MAAM,4CAA4C,CAAC;AAGxF,OAAO,EACL,0BAA0B,GAE3B,MAAM,qBAAqB,CAAC;AAgC7B,MAAM,mBAAmB,GAAG,IAAI,OAAO,EAAsC,CAAC;AAE9E,SAAS,oBAAoB,CAC3B,gBAA4C,EAC5C,IAAmB;IAEnB,OAAO;QACL,UAAU,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,QAAQ;QAC3C,WAAW,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,gBAAgB,EAAE,IAAI,CAAC;QAC1D,gBAAgB,EAAE,CAAC,OAAO,EAAE,EAAE,CAC5B,oBAAoB,CAAC,gBAAgB,EAAE,IAAI,EAAE,OAAO,CAAC;KACxD,CAAC;AACJ,CAAC;AAED,SAAS,2BAA2B;IAClC,MAAM,gBAAgB,GAA+B;QACnD,QAAQ,EAAE,KAAK;QACf,KAAK,EAAE,IAAI,GAAG,EAAyB;QACvC,SAAS,EAAE,IAAI,GAAG,EAAE;QACpB,qBAAqB,EAAE,CAAC;QACxB,YAAY,EAA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,EAAE,CAAC;QACjB,OAAO;IACT,CAAC;IAED,WAAW,CAAC,OAAO,EAAE,CAAC;IACtB,mBAAmB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,WAAwB;IAExB,OAAO,gCAAgC,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,WAAwB,EACxB,QAAoB;IAEpB,OAAO,gCAAgC,CAAC,WAAW,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;AAC3E,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,WAAwB,EACxB,GAAW,EACX,OAA+B;IAE/B,OAAO,gCAAgC,CAAC,WAAW,CAAC,CAAC,eAAe,CAClE,GAAG,EACH,OAAO,CACR,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oCAAoC,CAClD,WAAwB,EACxB,OAAyB;IAEzB,OAAO,CACL,mBAAmB,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC,OAAO,CAAC;QAC1D,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CACtB,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../shared/domainScope\";\nimport {\n requestAllPumpDrivenLanes,\n requestLaneSync,\n requestLaneSyncAfter,\n type SyncIdleOptions,\n waitForIdleLanes,\n} from \"./coordinatorPump\";\nimport type {\n DomainSyncCoordinatorState,\n SyncLaneState,\n} from \"./coordinatorState\";\nimport {\n hasPendingLaneWork,\n INITIAL_SYNC_LANE_RUN_STATE,\n publishSyncCoordinatorSnapshot,\n} from \"./coordinatorState\";\nimport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nimport { transitionSyncLaneRequest } from \"./syncLaneMachine\";\nimport type { DomainSyncSnapshot } from \"./syncTelemetry\";\nimport { createDomainSyncSnapshot, createSyncTimestamp } from \"./syncTelemetry\";\nimport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\nimport { beginUploadLane } from \"./uploadLane\";\n\n// Re-exported here because lanes reach it as a shouldIgnoreError alongside the\n// rest of the coordinator surface; it lives beside this coordinator with the\n// error type it discriminates on.\nexport { isDatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nexport type { SyncIdleOptions } from \"./coordinatorPump\";\nexport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nexport {\n didRegainSyncPrerequisites,\n type SyncRuntimeStatus,\n} from \"./syncPrerequisites\";\nexport type {\n DomainSyncSnapshot,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./syncTelemetry\";\nexport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\n\nexport interface DomainSyncCoordinator {\n beginUploadLane: (\n key: string,\n options?: UploadSyncLaneOptions,\n ) => UploadSyncLane;\n // Drop queued work and refuse new runs; active callbacks retain ownership.\n dispose: () => void;\n getSnapshot: () => DomainSyncSnapshot;\n registerLane: (key: string, config: SyncLaneConfig) => SyncLane;\n // Re-request every pump-driven lane — a manual \"sync now\" that re-drives\n // durable owners stranded by a transient failure. Observational upload rows\n // are updated only by those owners' real attachment upload attempts.\n requestAllLanes: () => void;\n // Request one registered pump lane without re-driving unrelated owners.\n requestLane: (key: string) => void;\n hasPendingWork: () => boolean;\n isDisposed: () => boolean;\n subscribe: (listener: () => void) => () => void;\n waitForIdle: (options?: SyncIdleOptions) => Promise<boolean>;\n}\n\nconst coordinatorsByScope = new WeakMap<DomainScope, DomainSyncCoordinator>();\n\nfunction createSyncLaneHandle(\n coordinatorState: DomainSyncCoordinatorState,\n lane: SyncLaneState,\n): SyncLane {\n return {\n isDisposed: () => coordinatorState.disposed,\n requestSync: () => requestLaneSync(coordinatorState, lane),\n requestSyncAfter: (delayMs) =>\n requestLaneSyncAfter(coordinatorState, lane, delayMs),\n };\n}\n\nfunction createDomainSyncCoordinator(): DomainSyncCoordinator {\n const coordinatorState: DomainSyncCoordinatorState = {\n disposed: false,\n lanes: new Map<string, SyncLaneState>(),\n listeners: new Set(),\n nextRegistrationIndex: 0,\n nextRunOrder: 0,\n wakePump: null,\n pump: null,\n snapshot: createDomainSyncSnapshot({\n hasPendingWork: false,\n lanes: [],\n pumpActive: false,\n }),\n };\n\n return {\n beginUploadLane(key: string, options: UploadSyncLaneOptions = {}) {\n return beginUploadLane(coordinatorState, key, options);\n },\n dispose() {\n coordinatorState.disposed = true;\n // Drop queued work so waitForIdle reports settled immediately and a\n // lane left re-requested by an in-flight run does not survive teardown.\n for (const lane of coordinatorState.lanes.values()) {\n lane.request = transitionSyncLaneRequest(lane.request, {\n type: \"clear\",\n });\n }\n // Publish the final settled snapshot, then release listener closures:\n // the coordinator is dropped from the registry and a remount subscribes\n // to a fresh one.\n publishSyncCoordinatorSnapshot(coordinatorState);\n coordinatorState.listeners.clear();\n },\n getSnapshot() {\n return coordinatorState.snapshot;\n },\n hasPendingWork() {\n return (\n !!coordinatorState.pump ||\n hasPendingLaneWork(coordinatorState.lanes.values())\n );\n },\n isDisposed() {\n return coordinatorState.disposed;\n },\n registerLane(key: string, config: SyncLaneConfig): SyncLane {\n const existingLane = coordinatorState.lanes.get(key);\n if (existingLane) {\n existingLane.config = config;\n existingLane.blobStorageKey = null;\n existingLane.pumpDriven = true;\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, existingLane);\n }\n\n const registeredAt = createSyncTimestamp();\n const nextLane: SyncLaneState = {\n ...INITIAL_SYNC_LANE_RUN_STATE,\n blobStorageKey: null,\n config,\n errorCount: 0,\n key,\n lastAction: \"registered\",\n lastActionAt: registeredAt,\n lastCompletedAt: null,\n lastError: null,\n lastFailedAt: null,\n lastRequestedAt: null,\n lastStartedAt: null,\n progress: null,\n pumpDriven: true,\n registrationIndex: coordinatorState.nextRegistrationIndex,\n requestCount: 0,\n };\n coordinatorState.nextRegistrationIndex += 1;\n coordinatorState.lanes.set(key, nextLane);\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, nextLane);\n },\n requestAllLanes() {\n requestAllPumpDrivenLanes(coordinatorState);\n },\n requestLane(key: string) {\n const lane = coordinatorState.lanes.get(key);\n if (lane?.pumpDriven) {\n requestLaneSync(coordinatorState, lane);\n }\n },\n subscribe(listener: () => void) {\n coordinatorState.listeners.add(listener);\n return () => {\n coordinatorState.listeners.delete(listener);\n };\n },\n waitForIdle(options?: SyncIdleOptions) {\n return waitForIdleLanes(coordinatorState, options);\n },\n };\n}\n\nexport function getOrCreateDomainSyncCoordinator(\n domainScope: DomainScope,\n): DomainSyncCoordinator {\n const existingCoordinator = coordinatorsByScope.get(domainScope);\n if (existingCoordinator) {\n return existingCoordinator;\n }\n\n const nextCoordinator = createDomainSyncCoordinator();\n coordinatorsByScope.set(domainScope, nextCoordinator);\n return nextCoordinator;\n}\n\nexport function hasDomainSyncCoordinatorPendingWork(\n domainScope: DomainScope,\n): boolean {\n return coordinatorsByScope.get(domainScope)?.hasPendingWork() ?? false;\n}\n\n// Re-request every pump-driven lane for a scope: a user-driven \"sync now\" that\n// retries durable work stranded by a transient failure. Observational upload\n// telemetry is never directly pumped. A no-op when no coordinator exists yet\n// (nothing has been synced) or it has been disposed.\nexport function requestAllDomainSyncLanes(domainScope: DomainScope): void {\n coordinatorsByScope.get(domainScope)?.requestAllLanes();\n}\n\nexport function requestDomainSyncLane(\n domainScope: DomainScope,\n key: string,\n): void {\n coordinatorsByScope.get(domainScope)?.requestLane(key);\n}\n\n// Stop admitting work and remove this scope's coordinator. Active callbacks\n// drain under their existing watchdogs; getOrCreate builds a fresh coordinator.\nexport function disposeDomainSyncCoordinator(domainScope: DomainScope): void {\n const coordinator = coordinatorsByScope.get(domainScope);\n if (!coordinator) {\n return;\n }\n\n coordinator.dispose();\n coordinatorsByScope.delete(domainScope);\n}\n\nexport function getDomainSyncCoordinatorSnapshot(\n domainScope: DomainScope,\n): DomainSyncSnapshot {\n return getOrCreateDomainSyncCoordinator(domainScope).getSnapshot();\n}\n\nexport function subscribeToDomainSyncCoordinator(\n domainScope: DomainScope,\n listener: () => void,\n): () => void {\n return getOrCreateDomainSyncCoordinator(domainScope).subscribe(listener);\n}\n\nexport function beginDomainSyncUploadLane(\n domainScope: DomainScope,\n key: string,\n options?: UploadSyncLaneOptions,\n): UploadSyncLane {\n return getOrCreateDomainSyncCoordinator(domainScope).beginUploadLane(\n key,\n options,\n );\n}\n\nexport function waitForDomainSyncCoordinatorToSettle(\n domainScope: DomainScope,\n options?: SyncIdleOptions,\n): Promise<boolean> {\n return (\n coordinatorsByScope.get(domainScope)?.waitForIdle(options) ??\n Promise.resolve(true)\n );\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
|
2
2
|
import { TrustedUserIdentityPinCorruptError, } from "../persistence/identity/trustedUserIdentityPinModel.js";
|
|
3
3
|
import { TrustedUserIdentityPinRepository } from "../persistence/identity/trustedUserIdentityPinRepository.js";
|
|
4
4
|
import { TrustedUserIdentityPinContentionError } from "../persistence/identity/trustedUserIdentityPinTransaction.js";
|
|
5
|
-
import { DatabaseUnavailableError } from "../
|
|
5
|
+
import { DatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
|
|
6
6
|
import { assertTrustedUserIdentityUserId, validateRemoteUserIdentity, } from "./validation.js";
|
|
7
7
|
/** The trust store, account, and runtime generation one operation runs in. */
|
|
8
8
|
function capturePinScope(dependencies) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pinnedResolution.js","sourceRoot":"","sources":["pinnedResolution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAEL,kCAAkC,GACnC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAA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,CAAC,2BAA2B,CAAC;oBAC5B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;oBAC9C,oEAAoE;oBACpE,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,KAAK,KAAK,CAAC,WAAW,CAAC;iBAClE,CAAC,CAAC;gBACH,KAAK,CAAC,aAAa,EAAE,CAAC;gBACtB,MAAM,MAAM,GAAG,MAAM,MAAM,CACzB,cAAc,CAAC;oBACb,OAAO;oBACP,UAAU;oBACV,OAAO;oBACP,IAAI;oBACJ,OAAO,EAAE,OAAO,CAAC,OAAO;oBACxB,OAAO;oBACP,KAAK;oBACL,MAAM;iBACP,CAAC,CACH,CAAC;gBACF,IAAI,OAAO,CAAC,OAAO,IAAI,MAAM,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;oBACvC,KAAK,CAAC,aAAa,EAAE,CAAC;oBACtB,MAAM,UAAU,CAAC,WAAW,CAC1B,KAAK,CAAC,OAAO,EACb,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EACpB,KAAK,CAAC,aAAa,CACpB,CAAC;gBACJ,CAAC;gBACD,KAAK,CAAC,aAAa,EAAE,CAAC;gBACtB,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC;gBAC5B,SAAS,GAAG,IAAI,CAAC;gBACjB,OAAO,MAAM,CAAC;YAChB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;YAC7B,CAAC;oBAAS,CAAC;gBACT,WAAW,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;YACzE,CAAC;QACH,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n type TrustedUserIdentityPin,\n TrustedUserIdentityPinCorruptError,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport type {\n HandoffScope,\n StagedIdentityHandoff,\n} from \"./stagedIdentityHandoff\";\nimport type {\n StagedUserIdentityOptions,\n StagedUserIdentityResolver,\n TrustedUserIdentityResolver,\n TrustedUserIdentityServiceDependencies,\n ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\n/** The gateway's own first-sight steps, split so a structural check can stage. */\nexport interface FirstSightIdentitySteps {\n /** The endpoint's validated candidate for a user; never pinned here. */\n readonly loadCandidate: (\n userId: string,\n identityTrustDomain: string,\n ) => Promise<ValidatedUserIdentityCandidate | null>;\n /**\n * Compare-or-insert candidates as `observed` pins in one write transaction:\n * a conflict on any of them, or a failed `assertCurrent` at COMMIT, commits\n * none, so a refused scope leaves no partial publication.\n */\n readonly pinObserved: (\n execSql: ExecSql,\n identities: readonly ValidatedUserIdentityCandidate[],\n assertCurrent: () => void,\n ) => Promise<unknown>;\n}\n\ninterface PinScope extends HandoffScope {\n readonly assertCurrent: () => void;\n}\n\n/** The trust store, account, and runtime generation one operation runs in. */\nfunction capturePinScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n): PinScope {\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (!identityTrustDomain)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n const execSql = dependencies.getExecSql();\n if (!execSql)\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n const localUserId = dependencies.getLocalUserId();\n const generation = dependencies.getScopeGeneration?.();\n return {\n execSql,\n generation,\n identityTrustDomain,\n localUserId,\n assertCurrent() {\n if (\n dependencies.getExecSql() !== execSql ||\n dependencies.getLocalUserId() !== localUserId ||\n dependencies.getScopeGeneration?.() !== generation\n )\n throw new DatabaseUnavailableError(\n \"The active identity changed while verifying pinned users.\",\n );\n },\n };\n}\n\n/**\n * Existing pins, self through ordinary resolution, and first sights staged in\n * memory; a publishing scope first takes an earlier unpublished scope's\n * handed-off answer. `fetched` records every such read so a failure evicts it.\n */\nfunction stagedResolver(input: {\n readonly fetched: Set<string>;\n readonly firstSight: FirstSightIdentitySteps;\n readonly handoff: StagedIdentityHandoff;\n readonly pins: ReadonlyMap<string, TrustedUserIdentityPin>;\n readonly publish: boolean;\n readonly resolve: TrustedUserIdentityResolver;\n readonly scope: PinScope;\n readonly staged: Map<string, ValidatedUserIdentityCandidate>;\n}): StagedUserIdentityResolver {\n const { scope } = input;\n return async (userId) => {\n scope.assertCurrent();\n if (userId === scope.localUserId) {\n const self = await input.resolve(userId);\n scope.assertCurrent();\n return self;\n }\n const pin = input.pins.get(userId);\n if (pin)\n return validateRemoteUserIdentity({\n candidate: pin,\n identityTrustDomain: scope.identityTrustDomain,\n requestedUserId: userId,\n });\n const known = input.staged.get(userId);\n if (known) return known;\n input.fetched.add(userId);\n const handed = input.publish\n ? input.handoff.take(scope, userId)\n : undefined;\n if (handed) {\n input.staged.set(userId, handed);\n return handed;\n }\n const candidate = await input.firstSight.loadCandidate(\n userId,\n scope.identityTrustDomain,\n );\n scope.assertCurrent();\n if (candidate) input.staged.set(userId, candidate);\n return candidate;\n };\n}\n\nfunction pinStoreError(error: unknown): unknown {\n if (error instanceof TrustedUserIdentityPinCorruptError)\n return new KeyingVerificationError(\"invalid_shape\", error.message);\n if (error instanceof TrustedUserIdentityPinContentionError)\n return new DatabaseUnavailableError(\n \"Trusted user identity pin store is busy\",\n );\n return error;\n}\n\n/**\n * A refused scope's answers are evicted, so a corrected retry reads the\n * endpoint again. An unpublished answer is unauthenticated even when `verify`\n * succeeded, since the caller's signature check may still refuse it: it stays\n * pending, readable only by a publishing scope that rechecks it, and any\n * other lookup reads the endpoint.\n */\nfunction settleScope(input: {\n readonly completed: boolean;\n readonly published: boolean;\n readonly fetched: ReadonlySet<string>;\n readonly staged: ReadonlyMap<string, ValidatedUserIdentityCandidate>;\n readonly scope: PinScope;\n readonly handoff: StagedIdentityHandoff;\n}): void {\n if (!input.completed) input.handoff.evict(input.fetched);\n else if (input.published) input.handoff.published(input.staged.keys());\n else input.handoff.retain(input.scope, input.staged);\n}\n\n/** Keep direct resolution unchanged; only structural verifiers opt into pins. */\nexport function withPinnedIdentityResolution(\n dependencies: TrustedUserIdentityServiceDependencies,\n resolve: TrustedUserIdentityResolver,\n firstSight: FirstSightIdentitySteps,\n handoff: StagedIdentityHandoff,\n): TrustedUserIdentityResolver {\n return Object.assign(resolve, {\n async withPinnedIdentities<T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ): Promise<T> {\n const captured = capturePinScope(dependencies);\n const scope: PinScope = {\n ...captured,\n assertCurrent() {\n captured.assertCurrent();\n options.assertCurrent?.();\n },\n };\n for (const userId of userIds) assertTrustedUserIdentityUserId(userId);\n // First sights stay in memory until `verify` succeeds for a projection\n // the caller has authenticated: a refusal leaves no durable trace.\n const fetched = new Set<string>();\n const staged = new Map<string, ValidatedUserIdentityCandidate>();\n let published = false;\n let completed = false;\n try {\n const pins = await new TrustedUserIdentityPinRepository(\n scope.execSql,\n ).loadTrustedUserIdentityPins({\n identityTrustDomain: scope.identityTrustDomain,\n // Self always rechecks the authoritative local keys and provenance.\n userIds: userIds.filter((userId) => userId !== scope.localUserId),\n });\n scope.assertCurrent();\n const result = await verify(\n stagedResolver({\n fetched,\n firstSight,\n handoff,\n pins,\n publish: options.publish,\n resolve,\n scope,\n staged,\n }),\n );\n if (options.publish && staged.size > 0) {\n scope.assertCurrent();\n await firstSight.pinObserved(\n scope.execSql,\n [...staged.values()],\n scope.assertCurrent,\n );\n }\n scope.assertCurrent();\n published = options.publish;\n completed = true;\n return result;\n } catch (error) {\n throw pinStoreError(error);\n } finally {\n settleScope({ completed, published, fetched, staged, scope, handoff });\n }\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"pinnedResolution.js","sourceRoot":"","sources":["pinnedResolution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAEL,kCAAkC,GACnC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAAE,qCAAqC,EAAE,MAAM,2DAA2D,CAAC;AAClH,OAAO,EAAE,wBAAwB,EAAE,MAAM,4CAA4C,CAAC;AAatF,OAAO,EACL,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,cAAc,CAAC;AAyBtB,8EAA8E;AAC9E,SAAS,eAAe,CACtB,YAAoD;IAEpD,MAAM,mBAAmB,GAAG,YAAY,CAAC,mBAAmB,CAAC;IAC7D,IAAI,CAAC,mBAAmB;QACtB,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,qEAAqE,CACtE,CAAC;IACJ,MAAM,OAAO,GAAG,YAAY,CAAC,UAAU,EAAE,CAAC;IAC1C,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,wBAAwB,CAChC,sEAAsE,CACvE,CAAC;IACJ,MAAM,WAAW,GAAG,YAAY,CAAC,cAAc,EAAE,CAAC;IAClD,MAAM,UAAU,GAAG,YAAY,CAAC,kBAAkB,EAAE,EAAE,CAAC;IACvD,OAAO;QACL,OAAO;QACP,UAAU;QACV,mBAAmB;QACnB,WAAW;QACX,aAAa;YACX,IACE,YAAY,CAAC,UAAU,EAAE,KAAK,OAAO;gBACrC,YAAY,CAAC,cAAc,EAAE,KAAK,WAAW;gBAC7C,YAAY,CAAC,kBAAkB,EAAE,EAAE,KAAK,UAAU;gBAElD,MAAM,IAAI,wBAA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MAAM,CAAC;YAChB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;YAC7B,CAAC;oBAAS,CAAC;gBACT,WAAW,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;YACzE,CAAC;QACH,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n type TrustedUserIdentityPin,\n TrustedUserIdentityPinCorruptError,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport { DatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport type {\n HandoffScope,\n StagedIdentityHandoff,\n} from \"./stagedIdentityHandoff\";\nimport type {\n StagedUserIdentityOptions,\n StagedUserIdentityResolver,\n TrustedUserIdentityResolver,\n TrustedUserIdentityServiceDependencies,\n ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\n/** The gateway's own first-sight steps, split so a structural check can stage. */\nexport interface FirstSightIdentitySteps {\n /** The endpoint's validated candidate for a user; never pinned here. */\n readonly loadCandidate: (\n userId: string,\n identityTrustDomain: string,\n ) => Promise<ValidatedUserIdentityCandidate | null>;\n /**\n * Compare-or-insert candidates as `observed` pins in one write transaction:\n * a conflict on any of them, or a failed `assertCurrent` at COMMIT, commits\n * none, so a refused scope leaves no partial publication.\n */\n readonly pinObserved: (\n execSql: ExecSql,\n identities: readonly ValidatedUserIdentityCandidate[],\n assertCurrent: () => void,\n ) => Promise<unknown>;\n}\n\ninterface PinScope extends HandoffScope {\n readonly assertCurrent: () => void;\n}\n\n/** The trust store, account, and runtime generation one operation runs in. */\nfunction capturePinScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n): PinScope {\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (!identityTrustDomain)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n const execSql = dependencies.getExecSql();\n if (!execSql)\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n const localUserId = dependencies.getLocalUserId();\n const generation = dependencies.getScopeGeneration?.();\n return {\n execSql,\n generation,\n identityTrustDomain,\n localUserId,\n assertCurrent() {\n if (\n dependencies.getExecSql() !== execSql ||\n dependencies.getLocalUserId() !== localUserId ||\n dependencies.getScopeGeneration?.() !== generation\n )\n throw new DatabaseUnavailableError(\n \"The active identity changed while verifying pinned users.\",\n );\n },\n };\n}\n\n/**\n * Existing pins, self through ordinary resolution, and first sights staged in\n * memory; a publishing scope first takes an earlier unpublished scope's\n * handed-off answer. `fetched` records every such read so a failure evicts it.\n */\nfunction stagedResolver(input: {\n readonly fetched: Set<string>;\n readonly firstSight: FirstSightIdentitySteps;\n readonly handoff: StagedIdentityHandoff;\n readonly pins: ReadonlyMap<string, TrustedUserIdentityPin>;\n readonly publish: boolean;\n readonly resolve: TrustedUserIdentityResolver;\n readonly scope: PinScope;\n readonly staged: Map<string, ValidatedUserIdentityCandidate>;\n}): StagedUserIdentityResolver {\n const { scope } = input;\n return async (userId) => {\n scope.assertCurrent();\n if (userId === scope.localUserId) {\n const self = await input.resolve(userId);\n scope.assertCurrent();\n return self;\n }\n const pin = input.pins.get(userId);\n if (pin)\n return validateRemoteUserIdentity({\n candidate: pin,\n identityTrustDomain: scope.identityTrustDomain,\n requestedUserId: userId,\n });\n const known = input.staged.get(userId);\n if (known) return known;\n input.fetched.add(userId);\n const handed = input.publish\n ? input.handoff.take(scope, userId)\n : undefined;\n if (handed) {\n input.staged.set(userId, handed);\n return handed;\n }\n const candidate = await input.firstSight.loadCandidate(\n userId,\n scope.identityTrustDomain,\n );\n scope.assertCurrent();\n if (candidate) input.staged.set(userId, candidate);\n return candidate;\n };\n}\n\nfunction pinStoreError(error: unknown): unknown {\n if (error instanceof TrustedUserIdentityPinCorruptError)\n return new KeyingVerificationError(\"invalid_shape\", error.message);\n if (error instanceof TrustedUserIdentityPinContentionError)\n return new DatabaseUnavailableError(\n \"Trusted user identity pin store is busy\",\n );\n return error;\n}\n\n/**\n * A refused scope's answers are evicted, so a corrected retry reads the\n * endpoint again. An unpublished answer is unauthenticated even when `verify`\n * succeeded, since the caller's signature check may still refuse it: it stays\n * pending, readable only by a publishing scope that rechecks it, and any\n * other lookup reads the endpoint.\n */\nfunction settleScope(input: {\n readonly completed: boolean;\n readonly published: boolean;\n readonly fetched: ReadonlySet<string>;\n readonly staged: ReadonlyMap<string, ValidatedUserIdentityCandidate>;\n readonly scope: PinScope;\n readonly handoff: StagedIdentityHandoff;\n}): void {\n if (!input.completed) input.handoff.evict(input.fetched);\n else if (input.published) input.handoff.published(input.staged.keys());\n else input.handoff.retain(input.scope, input.staged);\n}\n\n/** Keep direct resolution unchanged; only structural verifiers opt into pins. */\nexport function withPinnedIdentityResolution(\n dependencies: TrustedUserIdentityServiceDependencies,\n resolve: TrustedUserIdentityResolver,\n firstSight: FirstSightIdentitySteps,\n handoff: StagedIdentityHandoff,\n): TrustedUserIdentityResolver {\n return Object.assign(resolve, {\n async withPinnedIdentities<T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ): Promise<T> {\n const captured = capturePinScope(dependencies);\n const scope: PinScope = {\n ...captured,\n assertCurrent() {\n captured.assertCurrent();\n options.assertCurrent?.();\n },\n };\n for (const userId of userIds) assertTrustedUserIdentityUserId(userId);\n // First sights stay in memory until `verify` succeeds for a projection\n // the caller has authenticated: a refusal leaves no durable trace.\n const fetched = new Set<string>();\n const staged = new Map<string, ValidatedUserIdentityCandidate>();\n let published = false;\n let completed = false;\n try {\n const pins = await new TrustedUserIdentityPinRepository(\n scope.execSql,\n ).loadTrustedUserIdentityPins({\n identityTrustDomain: scope.identityTrustDomain,\n // Self always rechecks the authoritative local keys and provenance.\n userIds: userIds.filter((userId) => userId !== scope.localUserId),\n });\n scope.assertCurrent();\n const result = await verify(\n stagedResolver({\n fetched,\n firstSight,\n handoff,\n pins,\n publish: options.publish,\n resolve,\n scope,\n staged,\n }),\n );\n if (options.publish && staged.size > 0) {\n scope.assertCurrent();\n await firstSight.pinObserved(\n scope.execSql,\n [...staged.values()],\n scope.assertCurrent,\n );\n }\n scope.assertCurrent();\n published = options.publish;\n completed = true;\n return result;\n } catch (error) {\n throw pinStoreError(error);\n } finally {\n settleScope({ completed, published, fetched, staged, scope, handoff });\n }\n },\n });\n}\n"]}
|
|
@@ -3,7 +3,7 @@ import { bytesToBase64 } from "../../internal/encoding/index.js";
|
|
|
3
3
|
import { TrustedUserIdentityPinCorruptError, TrustedUserIdentityPinMismatchError, } from "../persistence/identity/trustedUserIdentityPinModel.js";
|
|
4
4
|
import { TrustedUserIdentityPinRepository } from "../persistence/identity/trustedUserIdentityPinRepository.js";
|
|
5
5
|
import { TrustedUserIdentityPinContentionError } from "../persistence/identity/trustedUserIdentityPinTransaction.js";
|
|
6
|
-
import { DatabaseUnavailableError } from "../
|
|
6
|
+
import { DatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
|
|
7
7
|
import { UnverifiedUserIdentityError } from "./admission.js";
|
|
8
8
|
import { assertIdentityLinkMatches, createIdentityLink, parseIdentityLink, } from "./identityLink.js";
|
|
9
9
|
import { loadPin, loadPinnedUserIdentity } from "./pinnedIdentity.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,aA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YAChE,WAAW,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,CAClD,sBAAsB,CAAC;gBACrB,aAAa;gBACb,OAAO;gBACP,WAAW,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE;gBAC/D,UAAU;gBACV,UAAU,EAAE,UAAU;aACvB,CAAC;SACL,EACD,OAAO,CACR;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport { UnverifiedUserIdentityError } from \"./admission\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport { loadPin, loadPinnedUserIdentity } from \"./pinnedIdentity\";\nimport { withPinnedIdentityResolution } from \"./pinnedResolution\";\nimport { withStagedIdentityHandoff } from \"./stagedIdentityHandoff\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nfunction durablePin(\n identity: ValidatedUserIdentityCandidate,\n provenance: TrustedUserIdentityPinProvenance,\n firstSeenAt: string,\n) {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt,\n provenance,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: identity.identityTrustDomain,\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: identity.userId,\n };\n}\n\n/** Compare-or-insert every identity in one transaction: all pin, or none. */\nasync function compareWithDurablePins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identities: readonly ValidatedUserIdentityCandidate[];\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<void> {\n const userIds = input.identities.map((identity) => identity.userId);\n try {\n await new TrustedUserIdentityPinRepository(\n input.execSql,\n ).compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n pins: input.identities.map((identity) =>\n durablePin(identity, input.provenance, input.firstSeenAt),\n ),\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${error.candidate.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${error.candidate.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${error.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${userIds.join(\", \")}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * The candidate for `userId` and where it came from: this device's own keys\n * (`self`) or the identity endpoint (`observed`). Provenance follows the\n * source, never the account that happens to be active once a lookup returns.\n */\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<{\n readonly identity: ValidatedUserIdentityCandidate;\n readonly source: \"self\" | \"observed\";\n} | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return {\n identity: await validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n }),\n source: \"self\",\n };\n }\n\n const identity = await loadRemoteCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n return identity ? { identity, source: \"observed\" } : null;\n}\n\nasync function loadRemoteCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\n/** The trust store and account a lookup started under must still be active. */\nfunction assertResolutionScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n scope: { readonly execSql: ExecSql; readonly localUserId: string | null },\n message: string,\n): void {\n if (\n dependencies.getExecSql() !== scope.execSql ||\n dependencies.getLocalUserId() !== scope.localUserId\n ) {\n throw new DatabaseUnavailableError(message);\n }\n}\n\nasync function pinIdentity(input: {\n /** Checked inside the pin's write transaction, before it commits. */\n readonly assertCurrent?: (() => void) | undefined;\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identities: [input.identity],\n provenance: input.provenance,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/** The user this trust store already binds to a signing key, if any. */\nasync function boundUserId(\n dependencies: TrustedUserIdentityServiceDependencies,\n signingKeyFingerprint: string,\n): Promise<string | null> {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return new TrustedUserIdentityPinRepository(\n execSql,\n ).loadTrustedUserIdForSigningKey({\n identityTrustDomain,\n signingKeyFingerprint,\n });\n}\n\n/** Compares an independently received link before pinning it as `link`. */\nasync function verifyIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n link: string,\n): Promise<TrustedUserIdentity> {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!candidate)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, candidate.identity);\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed. Open the identity link again.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source === \"self\" ? \"self\" : \"link\",\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n}\n\nfunction admissionScopeChanged(): DatabaseUnavailableError {\n return new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n}\n\n/** Reads that admit a user: only `self` and `link` pins qualify. */\nfunction verifiedPinReaders(\n dependencies: TrustedUserIdentityServiceDependencies,\n): Pick<\n TrustedUserIdentityService,\n \"loadAdmissionPin\" | \"resolveVerified\" | \"requireVerified\"\n> {\n const resolveVerified = async (userId: string) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin && pin.provenance !== \"observed\" ? pin.identity : null;\n };\n // The pin in the trust store of the database the admission captured.\n const loadAdmittingPin = async (\n userId: string,\n admittingExecSql: ExecSql | null,\n ) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (execSql !== admittingExecSql) throw admissionScopeChanged();\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin;\n };\n return {\n resolveVerified,\n async requireVerified(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n if (!pin || pin.provenance === \"observed\") {\n throw new UnverifiedUserIdentityError(userId);\n }\n return pin.identity;\n },\n async loadAdmissionPin(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n return pin\n ? { identity: pin.identity, verified: pin.provenance !== \"observed\" }\n : null;\n },\n };\n}\n\n/** This user's own link, derived exclusively from this device's local keys. */\nasync function createLocalIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n appUrl: string,\n): Promise<string> {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n}\n\nexport function createTrustedUserIdentityService(\n input: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n const { dependencies, handoff } = withStagedIdentityHandoff(input);\n const verifiedReaders = verifiedPinReaders(dependencies);\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n ...verifiedReaders,\n createLink: (appUrl) => createLocalIdentityLink(dependencies, appUrl),\n async createLinkFor(userId, appUrl) {\n if (\n userId === dependencies.getLocalUserId() &&\n dependencies.getLocalIdentity(userId)\n ) {\n return createLocalIdentityLink(dependencies, appUrl);\n }\n // Only a `link` or `self` pin: re-sharing an observed (TOFU) key as a\n // link would let its recipient pin an unverified key as `link`.\n const identity = await verifiedReaders.resolveVerified(userId);\n return identity ? createIdentityLink(identity, appUrl) : null;\n },\n verifyLink: (link) => verifyIdentityLink(dependencies, link),\n boundUserId: (signingKeyFingerprint) =>\n boundUserId(dependencies, signingKeyFingerprint),\n async pinLocal(userId, candidate) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({\n dependencies,\n execSql,\n identity,\n provenance: \"self\",\n });\n },\n resolve: withPinnedIdentityResolution(\n dependencies,\n async (userId) => {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } =\n requireTrustStore(dependencies);\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!candidate) {\n return null;\n }\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed while resolving this user.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source,\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n {\n loadCandidate: (userId, identityTrustDomain) =>\n loadRemoteCandidate(dependencies, userId, identityTrustDomain),\n pinObserved: (execSql, identities, assertCurrent) =>\n compareWithDurablePins({\n assertCurrent,\n execSql,\n firstSeenAt: (dependencies.now?.() ?? new Date()).toISOString(),\n identities,\n provenance: \"observed\",\n }),\n },\n handoff,\n ),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GAEpC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAAE,qCAAqC,EAAE,MAAM,2DAA2D,CAAC;AAClH,OAAO,EAAE,wBAAwB,EAAE,MAAM,4CAA4C,CAAC;AAEtF,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM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ACpC,iBAAiB,CAAC,YAAY,CAAC,CAAC;YAClC,MAAM,WAAW,GAAG,YAAY,CAAC,cAAc,EAAE,CAAC;YAClD,IAAI,CAAC;gBACH,MAAM,SAAS,GAAG,MAAM,gBAAgB,CACtC,YAAY,EACZ,MAAM,EACN,mBAAmB,CACpB,CAAC;gBACF,IAAI,CAAC,SAAS,EAAE,CAAC;oBACf,OAAO,IAAI,CAAC;gBACd,CAAC;gBACD,MAAM,aAAa,GAAG,GAAG,EAAE,CACzB,qBAAqB,CACnB,YAAY,EACZ,EAAE,OAAO,EAAE,WAAW,EAAE,EACxB,wDAAwD,CACzD,CAAC;gBACJ,aAAa,EAAE,CAAC;gBAChB,OAAO,MAAM,WAAW,CAAC;oBACvB,aAAa;oBACb,YAAY;oBACZ,OAAO;oBACP,QAAQ,EAAE,SAAS,CAAC,QAAQ;oBAC5B,UAAU,EAAE,SAAS,CAAC,MAAM;iBAC7B,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,YAAY,CAAC,YAAY,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;gBAC7C,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC,EACD;YACE,aAAa,EAAE,CAAC,MAAM,EAAE,mBAAmB,EAAE,EAAE,CAC7C,mBAAmB,CAAC,YAAY,EAAE,MAAM,EAAE,mBAAmB,CAAC;YAChE,WAAW,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,CAClD,sBAAsB,CAAC;gBACrB,aAAa;gBACb,OAAO;gBACP,WAAW,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE;gBAC/D,UAAU;gBACV,UAAU,EAAE,UAAU;aACvB,CAAC;SACL,EACD,OAAO,CACR;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport { DatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { UnverifiedUserIdentityError } from \"./admission\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport { loadPin, loadPinnedUserIdentity } from \"./pinnedIdentity\";\nimport { withPinnedIdentityResolution } from \"./pinnedResolution\";\nimport { withStagedIdentityHandoff } from \"./stagedIdentityHandoff\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nfunction durablePin(\n identity: ValidatedUserIdentityCandidate,\n provenance: TrustedUserIdentityPinProvenance,\n firstSeenAt: string,\n) {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt,\n provenance,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: identity.identityTrustDomain,\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: identity.userId,\n };\n}\n\n/** Compare-or-insert every identity in one transaction: all pin, or none. */\nasync function compareWithDurablePins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identities: readonly ValidatedUserIdentityCandidate[];\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<void> {\n const userIds = input.identities.map((identity) => identity.userId);\n try {\n await new TrustedUserIdentityPinRepository(\n input.execSql,\n ).compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n pins: input.identities.map((identity) =>\n durablePin(identity, input.provenance, input.firstSeenAt),\n ),\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${error.candidate.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${error.candidate.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${error.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${userIds.join(\", \")}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * The candidate for `userId` and where it came from: this device's own keys\n * (`self`) or the identity endpoint (`observed`). Provenance follows the\n * source, never the account that happens to be active once a lookup returns.\n */\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<{\n readonly identity: ValidatedUserIdentityCandidate;\n readonly source: \"self\" | \"observed\";\n} | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return {\n identity: await validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n }),\n source: \"self\",\n };\n }\n\n const identity = await loadRemoteCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n return identity ? { identity, source: \"observed\" } : null;\n}\n\nasync function loadRemoteCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\n/** The trust store and account a lookup started under must still be active. */\nfunction assertResolutionScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n scope: { readonly execSql: ExecSql; readonly localUserId: string | null },\n message: string,\n): void {\n if (\n dependencies.getExecSql() !== scope.execSql ||\n dependencies.getLocalUserId() !== scope.localUserId\n ) {\n throw new DatabaseUnavailableError(message);\n }\n}\n\nasync function pinIdentity(input: {\n /** Checked inside the pin's write transaction, before it commits. */\n readonly assertCurrent?: (() => void) | undefined;\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identities: [input.identity],\n provenance: input.provenance,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/** The user this trust store already binds to a signing key, if any. */\nasync function boundUserId(\n dependencies: TrustedUserIdentityServiceDependencies,\n signingKeyFingerprint: string,\n): Promise<string | null> {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return new TrustedUserIdentityPinRepository(\n execSql,\n ).loadTrustedUserIdForSigningKey({\n identityTrustDomain,\n signingKeyFingerprint,\n });\n}\n\n/** Compares an independently received link before pinning it as `link`. */\nasync function verifyIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n link: string,\n): Promise<TrustedUserIdentity> {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!candidate)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, candidate.identity);\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed. Open the identity link again.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source === \"self\" ? \"self\" : \"link\",\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n}\n\nfunction admissionScopeChanged(): DatabaseUnavailableError {\n return new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n}\n\n/** Reads that admit a user: only `self` and `link` pins qualify. */\nfunction verifiedPinReaders(\n dependencies: TrustedUserIdentityServiceDependencies,\n): Pick<\n TrustedUserIdentityService,\n \"loadAdmissionPin\" | \"resolveVerified\" | \"requireVerified\"\n> {\n const resolveVerified = async (userId: string) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin && pin.provenance !== \"observed\" ? pin.identity : null;\n };\n // The pin in the trust store of the database the admission captured.\n const loadAdmittingPin = async (\n userId: string,\n admittingExecSql: ExecSql | null,\n ) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (execSql !== admittingExecSql) throw admissionScopeChanged();\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin;\n };\n return {\n resolveVerified,\n async requireVerified(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n if (!pin || pin.provenance === \"observed\") {\n throw new UnverifiedUserIdentityError(userId);\n }\n return pin.identity;\n },\n async loadAdmissionPin(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n return pin\n ? { identity: pin.identity, verified: pin.provenance !== \"observed\" }\n : null;\n },\n };\n}\n\n/** This user's own link, derived exclusively from this device's local keys. */\nasync function createLocalIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n appUrl: string,\n): Promise<string> {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n}\n\nexport function createTrustedUserIdentityService(\n input: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n const { dependencies, handoff } = withStagedIdentityHandoff(input);\n const verifiedReaders = verifiedPinReaders(dependencies);\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n ...verifiedReaders,\n createLink: (appUrl) => createLocalIdentityLink(dependencies, appUrl),\n async createLinkFor(userId, appUrl) {\n if (\n userId === dependencies.getLocalUserId() &&\n dependencies.getLocalIdentity(userId)\n ) {\n return createLocalIdentityLink(dependencies, appUrl);\n }\n // Only a `link` or `self` pin: re-sharing an observed (TOFU) key as a\n // link would let its recipient pin an unverified key as `link`.\n const identity = await verifiedReaders.resolveVerified(userId);\n return identity ? createIdentityLink(identity, appUrl) : null;\n },\n verifyLink: (link) => verifyIdentityLink(dependencies, link),\n boundUserId: (signingKeyFingerprint) =>\n boundUserId(dependencies, signingKeyFingerprint),\n async pinLocal(userId, candidate) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({\n dependencies,\n execSql,\n identity,\n provenance: \"self\",\n });\n },\n resolve: withPinnedIdentityResolution(\n dependencies,\n async (userId) => {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } =\n requireTrustStore(dependencies);\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!candidate) {\n return null;\n }\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed while resolving this user.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source,\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n {\n loadCandidate: (userId, identityTrustDomain) =>\n loadRemoteCandidate(dependencies, userId, identityTrustDomain),\n pinObserved: (execSql, identities, assertCurrent) =>\n compareWithDurablePins({\n assertCurrent,\n execSql,\n firstSeenAt: (dependencies.now?.() ?? new Date()).toISOString(),\n identities,\n provenance: \"observed\",\n }),\n },\n handoff,\n ),\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { reportAndRethrowKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
|
|
2
2
|
import { DocumentContainerProjectionRepository } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
|
|
3
3
|
import { errorMessage } from "../../../data/shared/errorMessage.js";
|
|
4
|
-
import { isDatabaseUnavailableError } from "../../../data/
|
|
4
|
+
import { isDatabaseUnavailableError } from "../../../data/sqlite/availability/databaseUnavailable.js";
|
|
5
5
|
import { RemoteDocumentService, resolveDocumentCreateAuthor, } from "../../documents/index.js";
|
|
6
6
|
/**
|
|
7
7
|
* Hand a link/unlink/move/purge failure to host diagnostics as a real `Error`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,qCAAqC,EAAE,MAAM,qFAAqF,CAAC;AAC5I,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAAE,0BAA0B,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,qCAAqC,EAAE,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AC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,uCAAuC,CAC3C,KAAK,EACL,OAAO,CAAC,IAAI,CAAC,sBAAsB,EACnC;YACE,QAAQ,EAAE,UAAU;YACpB,UAAU,EAAE,UAAU;YACtB,SAAS,EAAE,YAAY,SAAS,EAAE;SACnC,CACF,CAAC;QACF,MAAM,OAAO,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,iCAAiC,SAAS,SAAS,MAAM,IAAI,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,cAAc,iBAAiB,KAAK,OAAO,EAAE,CAC/I,CAAC;QACF,sEAAsE;QACtE,4EAA4E;QAC5E,oEAAoE;QACpE,iCAAiC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACvD,KAAK,CAAC,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAC7C,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CAAC,KAanD;IACC,OAAO,6BAA6B,CAAC;QACnC,GAAG,KAAK;QACR,SAAS,EAAE,QAAQ;KACpB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { DocumentContainerProjectionRepository } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport { isDatabaseUnavailableError } from \"../../../data/sqlite/availability/databaseUnavailable\";\nimport {\n type DocumentLinkSetFailureHandler,\n type LinkSetAttachmentReuse,\n type RelinkRemoteDocumentResult,\n RemoteDocumentService,\n type RemoteDocumentServiceApi,\n resolveDocumentCreateAuthor,\n} from \"../../documents\";\nimport type { SubtreePurgeRoot } from \"../../documents/purge/subtreePurgeScope\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerDocumentLinkApi = RemoteDocumentServiceApi;\ntype ContainerDocumentLinkOperation = Parameters<\n RemoteDocumentService[\"relinkRemoteDocument\"]\n>[0][\"operation\"];\ntype RemoteDocumentPersistedState =\n RelinkRemoteDocumentResult[\"persistedState\"];\n\nexport interface ContainerDocumentLinkRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: ContainerDocumentLinkApi;\n}\n\nexport type { RemoteDocumentPersistedState };\n\n/**\n * Hand a link/unlink/move/purge failure to host diagnostics as a real `Error`.\n * The caller's string-only log line stays the fallback for a host without\n * `logError`, so this never logs a second copy of the same failure.\n */\nfunction reportDocumentLinkMutationFailure(\n util: ContainerDocumentLinkRuntime[\"util\"],\n error: unknown,\n): void {\n // `ApiClient` returns `RequestFailure` objects instead of throwing, so\n // offline and 403/404/409 already left through the `!result` branch: a status\n // filter here would be dead code. Only a database lost mid-flight stays quiet.\n if (!util.logError || isDatabaseUnavailableError(error)) return;\n try {\n // A host logger that throws or rejects must not replace the null result or\n // skip the failure handler below.\n void Promise.resolve(\n util.logError(\"Container contents: document link mutation failed\", error),\n ).catch(() => undefined);\n } catch {\n // Hosts may throw synchronously or return a rejected promise.\n }\n}\n\nexport async function relinkRemoteContainerDocument(input: {\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: ContainerDocumentLinkOperation;\n /** A workflow root's token; each leg otherwise discovers on its own. */\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const {\n documentId,\n noteId,\n operation,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n const author = resolveDocumentCreateAuthor(runtime);\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n const execSql = runtime.infra.execSql;\n if (input.isCurrent?.() === false) return null;\n if (!author || !targetSecretKey) {\n runtime.util.log(\n \"Container contents: document mutation skipped because the local key context is unavailable\",\n );\n input.onFailure?.({\n message: \"the local key context is unavailable\",\n status: null,\n });\n return null;\n }\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: targetSecretKey,\n execSql,\n });\n\n try {\n const result = await remoteDocuments.relinkRemoteDocument({\n attachmentReuse: input.attachmentReuse,\n beforeSubmit: input.beforeSubmit,\n author,\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n onFailure: input.onFailure,\n operation,\n resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n stillCurrent: input.isCurrent,\n targetContainerId,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n }),\n });\n if (!result) {\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}`,\n );\n return null;\n }\n if (input.isCurrent?.() === false) return null;\n\n await new DocumentContainerProjectionRepository(\n execSql,\n ).replaceDocumentLinks(documentId, result.linkedContainerIds, {\n stillCurrent: input.isCurrent,\n });\n\n return result;\n } catch (error) {\n await reportAndRethrowKeyingVerificationError(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: `document.${operation}`,\n },\n );\n const message = errorMessage(error);\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}: ${message}`,\n );\n // After the keying rethrow above, so a verification failure keeps its\n // security incident instead of being reported twice, and before the failure\n // handler, so a throwing caller callback cannot swallow the report.\n reportDocumentLinkMutationFailure(runtime.util, error);\n input.onFailure?.({ message, status: null });\n return null;\n }\n}\n\nexport async function unlinkRemoteContainerDocument(input: {\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"unlink\",\n });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
2
|
-
import { isDatabaseUnavailableError } from "../../data/
|
|
2
|
+
import { isDatabaseUnavailableError } from "../../data/sqlite/availability/databaseUnavailable.js";
|
|
3
3
|
import { requireTrustedUserIdentityResolver, } from "../../data/trustedUserIdentity/index.js";
|
|
4
4
|
export function createDocumentWriterPublicKeyResolver(input) {
|
|
5
5
|
const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(input.runtime.resolveTrustedUserIdentity);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writerKeys.js","sourceRoot":"","sources":["writerKeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"writerK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K,CAAC,YAAY,CAAC,CAAC;QAC5E,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO,IAAI,CAAC;QACd,CAAC;QAED,IAAI,QAAQ,CAAC,qBAAqB,KAAK,KAAK,CAAC,iBAAiB,EAAE,CAAC;YAC/D,KAAK,CAAC,IAAI,CAAC,GAAG,CACZ,GAAG,KAAK,CAAC,SAAS,aAAa,KAAK,CAAC,cAAc,QAAQ,KAAK,CAAC,YAAY,6DAA6D,CAC3I,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,QAAQ,CAAC,gBAAgB,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC7C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,0EAA0E;QAC1E,2EAA2E;QAC3E,0EAA0E;QAC1E,0EAA0E;QAC1E,wEAAwE;QACxE,IAAI,0BAA0B,CAAC,KAAK,CAAC,EAAE,CAAC;YACtC,MAAM,KAAK,CAAC;QACd,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,GAAG,CACZ,GAAG,KAAK,CAAC,SAAS,aAAa,KAAK,CAAC,cAAc,QAAQ,KAAK,CAAC,YAAY,kCAAkC,CAChH,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterPublicKeyResolver } from \"../../data/documents/shared/types\";\nimport { isDatabaseUnavailableError } from \"../../data/sqlite/availability/databaseUnavailable\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\n\ninterface DocumentWriterPublicKeyRuntime {\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: {\n readonly log: (message: string) => void;\n };\n}\n\nexport function createDocumentWriterPublicKeyResolver(input: {\n readonly logPrefix: string;\n readonly runtime: DocumentWriterPublicKeyRuntime;\n readonly writerKeyLabel: string;\n}): DocumentWriterPublicKeyResolver {\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.runtime.resolveTrustedUserIdentity,\n );\n const cache = new Map<string, Promise<Uint8Array | null>>();\n\n return async ({ writerSigningKeyFingerprint, writerUserId }) => {\n const cacheKey = `${writerUserId}:${writerSigningKeyFingerprint}`;\n let cached = cache.get(cacheKey);\n if (!cached) {\n cached = resolveWriterPublicKey({\n authorFingerprint: writerSigningKeyFingerprint,\n logPrefix: input.logPrefix,\n resolveTrustedUserIdentity,\n util: input.runtime.util,\n writerKeyLabel: input.writerKeyLabel,\n writerUserId,\n }).catch((error: unknown) => {\n cache.delete(cacheKey);\n throw error;\n });\n cache.set(cacheKey, cached);\n }\n\n return cached;\n };\n}\n\nasync function resolveWriterPublicKey(input: {\n readonly authorFingerprint: string;\n readonly logPrefix: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: DocumentWriterPublicKeyRuntime[\"util\"];\n readonly writerKeyLabel: string;\n readonly writerUserId: string;\n}): Promise<Uint8Array | null> {\n try {\n const identity = await input.resolveTrustedUserIdentity(input.writerUserId);\n if (!identity) {\n return null;\n }\n\n if (identity.signingKeyFingerprint !== input.authorFingerprint) {\n input.util.log(\n `${input.logPrefix}: skipped ${input.writerKeyLabel} for ${input.writerUserId} because the signing fingerprint does not match the writer.`,\n );\n return null;\n }\n\n return identity.signingPublicKey;\n } catch (error) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n // A vanished database is infrastructure loss, not an unresolvable writer.\n // Returning null here would surface downstream as a generic \"writer public\n // key missing\" verification error that sync lanes cannot classify, so the\n // lane would count a real failure for a routine runtime swap. Rethrow and\n // let the lanes' shouldIgnoreError treat it as the benign signal it is.\n if (isDatabaseUnavailableError(error)) {\n throw error;\n }\n input.util.log(\n `${input.logPrefix}: skipped ${input.writerKeyLabel} for ${input.writerUserId} because it could not be loaded.`,\n );\n return null;\n }\n}\n"]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|