@tearleads/client-sdk 0.1.198 → 0.1.199

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.
Files changed (22) hide show
  1. package/data/persistence/identity/trustedUserIdentityPinModel.d.ts +4 -0
  2. package/data/persistence/identity/trustedUserIdentityPinModel.js +113 -0
  3. package/data/persistence/identity/trustedUserIdentityPinModel.js.map +1 -1
  4. package/data/persistence/identity/trustedUserIdentityPinRepository.js +196 -0
  5. package/data/persistence/identity/trustedUserIdentityPinRepository.js.map +1 -0
  6. package/data/trustedUserIdentity/pinnedIdentity.d.ts +1 -1
  7. package/data/trustedUserIdentity/pinnedIdentity.js +2 -2
  8. package/data/trustedUserIdentity/pinnedIdentity.js.map +1 -1
  9. package/data/trustedUserIdentity/pinnedResolution.js +4 -5
  10. package/data/trustedUserIdentity/pinnedResolution.js.map +1 -1
  11. package/data/trustedUserIdentity/service.js +12 -13
  12. package/data/trustedUserIdentity/service.js.map +1 -1
  13. package/package.json +1 -1
  14. package/data/persistence/identity/trustedUserIdentityPinBatch.js +0 -36
  15. package/data/persistence/identity/trustedUserIdentityPinBatch.js.map +0 -1
  16. package/data/persistence/identity/trustedUserIdentitySigningKeyBinding.js +0 -18
  17. package/data/persistence/identity/trustedUserIdentitySigningKeyBinding.js.map +0 -1
  18. package/data/persistence/trustedUserIdentityPinPersistence.d.ts +0 -37
  19. package/data/persistence/trustedUserIdentityPinPersistence.js +0 -258
  20. package/data/persistence/trustedUserIdentityPinPersistence.js.map +0 -1
  21. /package/data/persistence/{trustedUserIdentityPinTransaction.js → identity/trustedUserIdentityPinTransaction.js} +0 -0
  22. /package/data/persistence/{trustedUserIdentityPinTransaction.js.map → identity/trustedUserIdentityPinTransaction.js.map} +0 -0
@@ -56,4 +56,8 @@ export declare class TrustedUserIdentityPinInputError extends Error {
56
56
  constructor(scope: PinScope, reason: string);
57
57
  }
58
58
  export declare function differingPinFields(existing: TrustedUserIdentityPin, candidate: TrustedUserIdentityPin): readonly ComparedPinField[];
59
+ export declare const provenanceRank: Readonly<Record<TrustedUserIdentityPinProvenance, number>>;
60
+ export declare function validationFailure(value: unknown): string | null;
61
+ export declare function assertCandidatePin(pin: TrustedUserIdentityPin): void;
62
+ export declare function parseStoredPin(value: unknown, scope: PinScope): TrustedUserIdentityPin;
59
63
  export {};
@@ -1,3 +1,4 @@
1
+ import { TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE, TRUSTED_USER_IDENTITY_FORMAT_VERSION, TRUSTED_USER_IDENTITY_SIGNING_SUITE, } from "../../trustedUserIdentity/types.js";
1
2
  const comparedPinFields = [
2
3
  "userId",
3
4
  "formatVersion",
@@ -65,4 +66,116 @@ export class TrustedUserIdentityPinInputError extends Error {
65
66
  export function differingPinFields(existing, candidate) {
66
67
  return comparedPinFields.filter((field) => existing[field] !== candidate[field]);
67
68
  }
69
+ export const provenanceRank = { observed: 0, link: 1, self: 2 };
70
+ function isTrustedUserIdentityPinProvenance(value) {
71
+ return value === "self" || value === "link" || value === "observed";
72
+ }
73
+ const requiredStringFields = [
74
+ "identityTrustDomain",
75
+ "userId",
76
+ "signingSuite",
77
+ "signingPublicKey",
78
+ "signingKeyFingerprint",
79
+ "encapsulationSuite",
80
+ "encapsulationPublicKey",
81
+ "encapsulationKeyFingerprint",
82
+ ];
83
+ function pinScope(value) {
84
+ if (typeof value !== "object" || value === null) {
85
+ return { identityTrustDomain: "<invalid>", userId: "<invalid>" };
86
+ }
87
+ const identityTrustDomain = Reflect.get(value, "identityTrustDomain");
88
+ const userId = Reflect.get(value, "userId");
89
+ return {
90
+ identityTrustDomain: typeof identityTrustDomain === "string"
91
+ ? identityTrustDomain
92
+ : "<invalid>",
93
+ userId: typeof userId === "string" ? userId : "<invalid>",
94
+ };
95
+ }
96
+ export function validationFailure(value) {
97
+ if (typeof value !== "object" || value === null) {
98
+ return "row must be an object";
99
+ }
100
+ const formatVersion = Reflect.get(value, "formatVersion");
101
+ if (formatVersion !== TRUSTED_USER_IDENTITY_FORMAT_VERSION) {
102
+ return `formatVersion must be ${TRUSTED_USER_IDENTITY_FORMAT_VERSION}`;
103
+ }
104
+ for (const field of requiredStringFields) {
105
+ const fieldValue = Reflect.get(value, field);
106
+ if (typeof fieldValue !== "string" || fieldValue.trim().length === 0) {
107
+ return `${field} must be a non-empty string`;
108
+ }
109
+ }
110
+ if (Reflect.get(value, "signingSuite") !== TRUSTED_USER_IDENTITY_SIGNING_SUITE) {
111
+ return `signingSuite must be ${TRUSTED_USER_IDENTITY_SIGNING_SUITE}`;
112
+ }
113
+ if (Reflect.get(value, "encapsulationSuite") !==
114
+ TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE) {
115
+ return `encapsulationSuite must be ${TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE}`;
116
+ }
117
+ const firstSeenAt = Reflect.get(value, "firstSeenAt");
118
+ if (typeof firstSeenAt !== "string" ||
119
+ !Number.isFinite(Date.parse(firstSeenAt))) {
120
+ return "firstSeenAt must be a valid timestamp";
121
+ }
122
+ if (!isTrustedUserIdentityPinProvenance(Reflect.get(value, "provenance"))) {
123
+ return "provenance must be self, link, or observed";
124
+ }
125
+ return null;
126
+ }
127
+ function validatedStringField(value, field) {
128
+ const fieldValue = Reflect.get(value, field);
129
+ if (typeof fieldValue !== "string") {
130
+ throw new TypeError(`Validated pin field ${field} is not a string`);
131
+ }
132
+ return fieldValue;
133
+ }
134
+ function validatedFormatVersion(value) {
135
+ const formatVersion = Reflect.get(value, "formatVersion");
136
+ if (typeof formatVersion !== "number") {
137
+ throw new TypeError("Validated pin formatVersion is not a number");
138
+ }
139
+ return formatVersion;
140
+ }
141
+ function validatedProvenance(value) {
142
+ const provenance = Reflect.get(value, "provenance");
143
+ if (!isTrustedUserIdentityPinProvenance(provenance)) {
144
+ throw new TypeError("Validated pin provenance is not a provenance");
145
+ }
146
+ return provenance;
147
+ }
148
+ export function assertCandidatePin(pin) {
149
+ const failure = validationFailure(pin);
150
+ if (failure) {
151
+ throw new TrustedUserIdentityPinInputError(pinScope(pin), failure);
152
+ }
153
+ }
154
+ export function parseStoredPin(value, scope) {
155
+ const failure = validationFailure(value);
156
+ if (failure) {
157
+ throw new TrustedUserIdentityPinCorruptError(scope, failure);
158
+ }
159
+ if (typeof value !== "object" || value === null) {
160
+ throw new TrustedUserIdentityPinCorruptError(scope, "row must be an object");
161
+ }
162
+ const pin = {
163
+ identityTrustDomain: validatedStringField(value, "identityTrustDomain"),
164
+ userId: validatedStringField(value, "userId"),
165
+ formatVersion: validatedFormatVersion(value),
166
+ signingSuite: validatedStringField(value, "signingSuite"),
167
+ signingPublicKey: validatedStringField(value, "signingPublicKey"),
168
+ signingKeyFingerprint: validatedStringField(value, "signingKeyFingerprint"),
169
+ encapsulationSuite: validatedStringField(value, "encapsulationSuite"),
170
+ encapsulationPublicKey: validatedStringField(value, "encapsulationPublicKey"),
171
+ encapsulationKeyFingerprint: validatedStringField(value, "encapsulationKeyFingerprint"),
172
+ firstSeenAt: validatedStringField(value, "firstSeenAt"),
173
+ provenance: validatedProvenance(value),
174
+ };
175
+ if (pin.identityTrustDomain !== scope.identityTrustDomain ||
176
+ pin.userId !== scope.userId) {
177
+ throw new TrustedUserIdentityPinCorruptError(scope, "primary-key scope does not match the requested pin");
178
+ }
179
+ return pin;
180
+ }
68
181
  //# sourceMappingURL=trustedUserIdentityPinModel.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"trustedUserIdentityPinModel.js","sourceRoot":"","sources":["trustedUserIdentityPinModel.ts"],"names":[],"mappings":"AA+CA,MAAM,iBAAiB,GAAgC;IACrD,QAAQ;IACR,eAAe;IACf,cAAc;IACd,kBAAkB;IAClB,uBAAuB;IACvB,oBAAoB;IACpB,wBAAwB;IACxB,6BAA6B;CAC9B,CAAC;AAEF,SAAS,aAAa,CAAC,GAA2B;IAChD,OAAO;QACL,MAAM,EAAE,GAAG,CAAC,MAAM;QAClB,aAAa,EAAE,GAAG,CAAC,aAAa;QAChC,YAAY,EAAE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AK,CAAC,mBAAmB,CAAC;QACrD,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;QAC3B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAED,MAAM,OAAO,gCAAiC,SAAQ,KAAK;IAChD,IAAI,GAAG,yCAAyC,CAAC;IACjD,mBAAmB,CAAS;IAC5B,MAAM,CAAS;IACf,MAAM,CAAS;IAExB,YAAY,KAAe,EAAE,MAAc;QACzC,KAAK,CAAC,2CAA2C,MAAM,EAAE,CAAC,CAAC;QAC3D,IAAI,CAAC,IAAI,GAAG,kCAAkC,CAAC;QAC/C,IAAI,CAAC,mBAAmB,GAAG,KAAK,CAAC,mBAAmB,CAAC;QACrD,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;QAC3B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAED,MAAM,UAAU,kBAAkB,CAChC,QAAgC,EAChC,SAAiC;IAEjC,OAAO,iBAAiB,CAAC,MAAM,CAC7B,CAAC,KAAK,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,SAAS,CAAC,KAAK,CAAC,CAChD,CAAC;AACJ,CAAC","sourcesContent":["/**\n * How this device came to trust a pin. `self` is the user's own local keys,\n * `link` an independently exchanged identity link, and `observed` the first\n * server answer for a user already referenced by signed state. Only `self` and\n * `link` admit a user; provenance only ever rises, and never changes the keys.\n */\nexport type TrustedUserIdentityPinProvenance = \"self\" | \"link\" | \"observed\";\n\nexport interface TrustedUserIdentityPin {\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly formatVersion: number;\n readonly signingSuite: string;\n readonly signingPublicKey: string;\n readonly signingKeyFingerprint: string;\n readonly encapsulationSuite: string;\n readonly encapsulationPublicKey: string;\n readonly encapsulationKeyFingerprint: string;\n readonly firstSeenAt: string;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}\n\nexport type ComparedPinField =\n | \"userId\"\n | \"formatVersion\"\n | \"signingSuite\"\n | \"signingPublicKey\"\n | \"signingKeyFingerprint\"\n | \"encapsulationSuite\"\n | \"encapsulationPublicKey\"\n | \"encapsulationKeyFingerprint\";\n\ninterface PinDiagnostic {\n readonly userId: string;\n readonly formatVersion: number;\n readonly signingSuite: string;\n readonly signingKeyFingerprint: string;\n readonly encapsulationSuite: string;\n readonly encapsulationKeyFingerprint: string;\n readonly firstSeenAt: string;\n}\n\nexport interface PinScope {\n readonly identityTrustDomain: string;\n readonly userId: string;\n}\n\nconst comparedPinFields: readonly ComparedPinField[] = [\n \"userId\",\n \"formatVersion\",\n \"signingSuite\",\n \"signingPublicKey\",\n \"signingKeyFingerprint\",\n \"encapsulationSuite\",\n \"encapsulationPublicKey\",\n \"encapsulationKeyFingerprint\",\n];\n\nfunction pinDiagnostic(pin: TrustedUserIdentityPin): PinDiagnostic {\n return {\n userId: pin.userId,\n formatVersion: pin.formatVersion,\n signingSuite: pin.signingSuite,\n signingKeyFingerprint: pin.signingKeyFingerprint,\n encapsulationSuite: pin.encapsulationSuite,\n encapsulationKeyFingerprint: pin.encapsulationKeyFingerprint,\n firstSeenAt: pin.firstSeenAt,\n };\n}\n\nexport class TrustedUserIdentityPinMismatchError extends Error {\n readonly code = \"trusted_user_identity_pin_mismatch\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly existing: PinDiagnostic;\n readonly candidate: PinDiagnostic;\n readonly differingFields: readonly ComparedPinField[];\n\n constructor(\n existing: TrustedUserIdentityPin,\n candidate: TrustedUserIdentityPin,\n differingFields: readonly ComparedPinField[],\n ) {\n super(\n `Trusted identity pin mismatch for ${candidate.userId} in ${candidate.identityTrustDomain}: ${differingFields.join(\", \")}`,\n );\n this.name = \"TrustedUserIdentityPinMismatchError\";\n this.identityTrustDomain = candidate.identityTrustDomain;\n this.userId = candidate.userId;\n this.existing = pinDiagnostic(existing);\n this.candidate = pinDiagnostic(candidate);\n this.differingFields = differingFields;\n }\n}\n\nexport class TrustedUserIdentityPinCorruptError extends Error {\n readonly code = \"trusted_user_identity_pin_corrupt\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly reason: string;\n\n constructor(scope: PinScope, reason: string) {\n super(\n `Stored trusted identity pin is corrupt for ${scope.userId} in ${scope.identityTrustDomain}: ${reason}`,\n );\n this.name = \"TrustedUserIdentityPinCorruptError\";\n this.identityTrustDomain = scope.identityTrustDomain;\n this.userId = scope.userId;\n this.reason = reason;\n }\n}\n\nexport class TrustedUserIdentityPinInputError extends Error {\n readonly code = \"trusted_user_identity_pin_invalid_input\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly reason: string;\n\n constructor(scope: PinScope, reason: string) {\n super(`Invalid trusted identity pin candidate: ${reason}`);\n this.name = \"TrustedUserIdentityPinInputError\";\n this.identityTrustDomain = scope.identityTrustDomain;\n this.userId = scope.userId;\n this.reason = reason;\n }\n}\n\nexport function differingPinFields(\n existing: TrustedUserIdentityPin,\n candidate: TrustedUserIdentityPin,\n): readonly ComparedPinField[] {\n return comparedPinFields.filter(\n (field) => existing[field] !== candidate[field],\n );\n}\n"]}
1
+ {"version":3,"file":"trustedUserIdentityPinModel.js","sourceRoot":"","sources":["trustedUserIdentityPinModel.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yCAAyC,EACzC,oCAAoC,EACpC,mCAAmC,GACpC,MAAM,iCAAiC,CAAC;AAiDzC,MAAM,iBAAiB,GAAgC;IACrD,QAAQ;IACR,eAAe;IACf,cAAc;IACd,kBAAkB;IAClB,uBAAuB;IACvB,oBAAoB;IACpB,wBAAwB;IACxB,6BAA6B;CAC9B,CAAC;AAEF,SAAS,aAAa,CAAC,GAA2B;IAChD,OAAO;QACL,MAAM,EAAE,GAAG,CAAC,MAAM;QAClB,aAAa,EAAE,GAAG,CAAC,aAAa;QAChC,YAAY,EAAE,GAAG,CAAC,YAAY;QAC9B,qBAAqB,EAAE,GAAG,CAAC,qBAAqB;QAChD,kBAAkB,EAAE,GAAG,CAAC,kBA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,EAAE,oBAAoB,CAAC,KAAK,EAAE,aAAa,CAAC;QACvD,UAAU,EAAE,mBAAmB,CAAC,KAAK,CAAC;KACvC,CAAC;IACF,IACE,GAAG,CAAC,mBAAmB,KAAK,KAAK,CAAC,mBAAmB;QACrD,GAAG,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,EAC3B,CAAC;QACD,MAAM,IAAI,kCAAkC,CAC1C,KAAK,EACL,oDAAoD,CACrD,CAAC;IACJ,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import {\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n} from \"../../trustedUserIdentity/types\";\n\n/**\n * How this device came to trust a pin. `self` is the user's own local keys,\n * `link` an independently exchanged identity link, and `observed` the first\n * server answer for a user already referenced by signed state. Only `self` and\n * `link` admit a user; provenance only ever rises, and never changes the keys.\n */\nexport type TrustedUserIdentityPinProvenance = \"self\" | \"link\" | \"observed\";\n\nexport interface TrustedUserIdentityPin {\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly formatVersion: number;\n readonly signingSuite: string;\n readonly signingPublicKey: string;\n readonly signingKeyFingerprint: string;\n readonly encapsulationSuite: string;\n readonly encapsulationPublicKey: string;\n readonly encapsulationKeyFingerprint: string;\n readonly firstSeenAt: string;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}\n\nexport type ComparedPinField =\n | \"userId\"\n | \"formatVersion\"\n | \"signingSuite\"\n | \"signingPublicKey\"\n | \"signingKeyFingerprint\"\n | \"encapsulationSuite\"\n | \"encapsulationPublicKey\"\n | \"encapsulationKeyFingerprint\";\n\ninterface PinDiagnostic {\n readonly userId: string;\n readonly formatVersion: number;\n readonly signingSuite: string;\n readonly signingKeyFingerprint: string;\n readonly encapsulationSuite: string;\n readonly encapsulationKeyFingerprint: string;\n readonly firstSeenAt: string;\n}\n\nexport interface PinScope {\n readonly identityTrustDomain: string;\n readonly userId: string;\n}\n\nconst comparedPinFields: readonly ComparedPinField[] = [\n \"userId\",\n \"formatVersion\",\n \"signingSuite\",\n \"signingPublicKey\",\n \"signingKeyFingerprint\",\n \"encapsulationSuite\",\n \"encapsulationPublicKey\",\n \"encapsulationKeyFingerprint\",\n];\n\nfunction pinDiagnostic(pin: TrustedUserIdentityPin): PinDiagnostic {\n return {\n userId: pin.userId,\n formatVersion: pin.formatVersion,\n signingSuite: pin.signingSuite,\n signingKeyFingerprint: pin.signingKeyFingerprint,\n encapsulationSuite: pin.encapsulationSuite,\n encapsulationKeyFingerprint: pin.encapsulationKeyFingerprint,\n firstSeenAt: pin.firstSeenAt,\n };\n}\n\nexport class TrustedUserIdentityPinMismatchError extends Error {\n readonly code = \"trusted_user_identity_pin_mismatch\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly existing: PinDiagnostic;\n readonly candidate: PinDiagnostic;\n readonly differingFields: readonly ComparedPinField[];\n\n constructor(\n existing: TrustedUserIdentityPin,\n candidate: TrustedUserIdentityPin,\n differingFields: readonly ComparedPinField[],\n ) {\n super(\n `Trusted identity pin mismatch for ${candidate.userId} in ${candidate.identityTrustDomain}: ${differingFields.join(\", \")}`,\n );\n this.name = \"TrustedUserIdentityPinMismatchError\";\n this.identityTrustDomain = candidate.identityTrustDomain;\n this.userId = candidate.userId;\n this.existing = pinDiagnostic(existing);\n this.candidate = pinDiagnostic(candidate);\n this.differingFields = differingFields;\n }\n}\n\nexport class TrustedUserIdentityPinCorruptError extends Error {\n readonly code = \"trusted_user_identity_pin_corrupt\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly reason: string;\n\n constructor(scope: PinScope, reason: string) {\n super(\n `Stored trusted identity pin is corrupt for ${scope.userId} in ${scope.identityTrustDomain}: ${reason}`,\n );\n this.name = \"TrustedUserIdentityPinCorruptError\";\n this.identityTrustDomain = scope.identityTrustDomain;\n this.userId = scope.userId;\n this.reason = reason;\n }\n}\n\nexport class TrustedUserIdentityPinInputError extends Error {\n readonly code = \"trusted_user_identity_pin_invalid_input\";\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly reason: string;\n\n constructor(scope: PinScope, reason: string) {\n super(`Invalid trusted identity pin candidate: ${reason}`);\n this.name = \"TrustedUserIdentityPinInputError\";\n this.identityTrustDomain = scope.identityTrustDomain;\n this.userId = scope.userId;\n this.reason = reason;\n }\n}\n\nexport function differingPinFields(\n existing: TrustedUserIdentityPin,\n candidate: TrustedUserIdentityPin,\n): readonly ComparedPinField[] {\n return comparedPinFields.filter(\n (field) => existing[field] !== candidate[field],\n );\n}\n\nexport const provenanceRank: Readonly<\n Record<TrustedUserIdentityPinProvenance, number>\n> = { observed: 0, link: 1, self: 2 };\n\nfunction isTrustedUserIdentityPinProvenance(\n value: unknown,\n): value is TrustedUserIdentityPinProvenance {\n return value === \"self\" || value === \"link\" || value === \"observed\";\n}\n\nconst requiredStringFields = [\n \"identityTrustDomain\",\n \"userId\",\n \"signingSuite\",\n \"signingPublicKey\",\n \"signingKeyFingerprint\",\n \"encapsulationSuite\",\n \"encapsulationPublicKey\",\n \"encapsulationKeyFingerprint\",\n] as const satisfies readonly (keyof TrustedUserIdentityPin)[];\n\nfunction pinScope(value: unknown): PinScope {\n if (typeof value !== \"object\" || value === null) {\n return { identityTrustDomain: \"<invalid>\", userId: \"<invalid>\" };\n }\n const identityTrustDomain = Reflect.get(value, \"identityTrustDomain\");\n const userId = Reflect.get(value, \"userId\");\n return {\n identityTrustDomain:\n typeof identityTrustDomain === \"string\"\n ? identityTrustDomain\n : \"<invalid>\",\n userId: typeof userId === \"string\" ? userId : \"<invalid>\",\n };\n}\n\nexport function validationFailure(value: unknown): string | null {\n if (typeof value !== \"object\" || value === null) {\n return \"row must be an object\";\n }\n const formatVersion = Reflect.get(value, \"formatVersion\");\n if (formatVersion !== TRUSTED_USER_IDENTITY_FORMAT_VERSION) {\n return `formatVersion must be ${TRUSTED_USER_IDENTITY_FORMAT_VERSION}`;\n }\n for (const field of requiredStringFields) {\n const fieldValue = Reflect.get(value, field);\n if (typeof fieldValue !== \"string\" || fieldValue.trim().length === 0) {\n return `${field} must be a non-empty string`;\n }\n }\n if (\n Reflect.get(value, \"signingSuite\") !== TRUSTED_USER_IDENTITY_SIGNING_SUITE\n ) {\n return `signingSuite must be ${TRUSTED_USER_IDENTITY_SIGNING_SUITE}`;\n }\n if (\n Reflect.get(value, \"encapsulationSuite\") !==\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE\n ) {\n return `encapsulationSuite must be ${TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE}`;\n }\n const firstSeenAt = Reflect.get(value, \"firstSeenAt\");\n if (\n typeof firstSeenAt !== \"string\" ||\n !Number.isFinite(Date.parse(firstSeenAt))\n ) {\n return \"firstSeenAt must be a valid timestamp\";\n }\n if (!isTrustedUserIdentityPinProvenance(Reflect.get(value, \"provenance\"))) {\n return \"provenance must be self, link, or observed\";\n }\n return null;\n}\n\nfunction validatedStringField(\n value: object,\n field: (typeof requiredStringFields)[number] | \"firstSeenAt\",\n): string {\n const fieldValue = Reflect.get(value, field);\n if (typeof fieldValue !== \"string\") {\n throw new TypeError(`Validated pin field ${field} is not a string`);\n }\n return fieldValue;\n}\n\nfunction validatedFormatVersion(value: object): number {\n const formatVersion = Reflect.get(value, \"formatVersion\");\n if (typeof formatVersion !== \"number\") {\n throw new TypeError(\"Validated pin formatVersion is not a number\");\n }\n return formatVersion;\n}\n\nfunction validatedProvenance(value: object): TrustedUserIdentityPinProvenance {\n const provenance = Reflect.get(value, \"provenance\");\n if (!isTrustedUserIdentityPinProvenance(provenance)) {\n throw new TypeError(\"Validated pin provenance is not a provenance\");\n }\n return provenance;\n}\n\nexport function assertCandidatePin(pin: TrustedUserIdentityPin): void {\n const failure = validationFailure(pin);\n if (failure) {\n throw new TrustedUserIdentityPinInputError(pinScope(pin), failure);\n }\n}\n\nexport function parseStoredPin(\n value: unknown,\n scope: PinScope,\n): TrustedUserIdentityPin {\n const failure = validationFailure(value);\n if (failure) {\n throw new TrustedUserIdentityPinCorruptError(scope, failure);\n }\n if (typeof value !== \"object\" || value === null) {\n throw new TrustedUserIdentityPinCorruptError(\n scope,\n \"row must be an object\",\n );\n }\n const pin: TrustedUserIdentityPin = {\n identityTrustDomain: validatedStringField(value, \"identityTrustDomain\"),\n userId: validatedStringField(value, \"userId\"),\n formatVersion: validatedFormatVersion(value),\n signingSuite: validatedStringField(value, \"signingSuite\"),\n signingPublicKey: validatedStringField(value, \"signingPublicKey\"),\n signingKeyFingerprint: validatedStringField(value, \"signingKeyFingerprint\"),\n encapsulationSuite: validatedStringField(value, \"encapsulationSuite\"),\n encapsulationPublicKey: validatedStringField(\n value,\n \"encapsulationPublicKey\",\n ),\n encapsulationKeyFingerprint: validatedStringField(\n value,\n \"encapsulationKeyFingerprint\",\n ),\n firstSeenAt: validatedStringField(value, \"firstSeenAt\"),\n provenance: validatedProvenance(value),\n };\n if (\n pin.identityTrustDomain !== scope.identityTrustDomain ||\n pin.userId !== scope.userId\n ) {\n throw new TrustedUserIdentityPinCorruptError(\n scope,\n \"primary-key scope does not match the requested pin\",\n );\n }\n return pin;\n}\n"]}
@@ -0,0 +1,196 @@
1
+ import { and, eq, inArray, or } from "drizzle-orm";
2
+ import { trustedUserIdentityPins, trustedUserIdentityPinTables, } from "../../sqlite/schema/trustedUserIdentityPinSchema.js";
3
+ import { sqliteRowsPerStatement } from "../../sqlite/sqliteBindBudget.js";
4
+ import { registerClientSQLiteCommitGuard } from "../../sqlite/sqliteCommitGuards.js";
5
+ import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
6
+ import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
7
+ import { assertCandidatePin, differingPinFields, parseStoredPin, provenanceRank, TrustedUserIdentityPinCorruptError, TrustedUserIdentityPinMismatchError, validationFailure, } from "./trustedUserIdentityPinModel.js";
8
+ import { runTrustedUserIdentityPinTransaction } from "./trustedUserIdentityPinTransaction.js";
9
+ const pins = trustedUserIdentityPins;
10
+ // Each member binds one ID; the trust domain binds once per statement.
11
+ const PIN_READ_BATCH_SIZE = sqliteRowsPerStatement(1, 1);
12
+ /**
13
+ * Durable trusted identity pins on one SQLite executor. Callers build it from
14
+ * the executor in hand at each call; it holds no other state.
15
+ */
16
+ export class TrustedUserIdentityPinRepository {
17
+ execSql;
18
+ constructor(execSql) {
19
+ this.execSql = execSql;
20
+ }
21
+ async loadTrustedUserIdentityPin(input) {
22
+ const scope = {
23
+ identityTrustDomain: input.identityTrustDomain,
24
+ userId: input.userId,
25
+ };
26
+ await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);
27
+ return selectStoredPin(getClientSQLitePersistenceRuntime(this.execSql).db, scope);
28
+ }
29
+ /** Read immutable pins together, never exposing another adapter's uncommitted rows. */
30
+ async loadTrustedUserIdentityPins(input) {
31
+ const userIds = [...new Set(input.userIds)];
32
+ if (userIds.length === 0)
33
+ return new Map();
34
+ await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);
35
+ const runtime = getClientSQLitePersistenceRuntime(this.execSql);
36
+ return runTrustedUserIdentityPinTransaction(() => runtime.transaction(async (tx) => {
37
+ const loaded = new Map();
38
+ for (let start = 0; start < userIds.length; start += PIN_READ_BATCH_SIZE) {
39
+ const batch = userIds.slice(start, start + PIN_READ_BATCH_SIZE);
40
+ const rows = await tx
41
+ .select()
42
+ .from(pins)
43
+ .where(and(eq(pins.identityTrustDomain, input.identityTrustDomain), inArray(pins.userId, batch)));
44
+ for (const row of rows) {
45
+ const pin = parseStoredPin(row, {
46
+ identityTrustDomain: input.identityTrustDomain,
47
+ userId: row.userId,
48
+ });
49
+ loaded.set(pin.userId, pin);
50
+ }
51
+ }
52
+ return loaded;
53
+ }));
54
+ }
55
+ /**
56
+ * The user a signing key is already bound to in this trust domain, if any.
57
+ * Each key has at most one such user: the reverse binding is unique.
58
+ */
59
+ async loadTrustedUserIdForSigningKey(input) {
60
+ await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);
61
+ const rows = await getClientSQLitePersistenceRuntime(this.execSql)
62
+ .db.select({ userId: pins.userId })
63
+ .from(pins)
64
+ .where(and(eq(pins.identityTrustDomain, input.identityTrustDomain), eq(pins.signingKeyFingerprint, input.signingKeyFingerprint)))
65
+ .limit(1);
66
+ return rows[0]?.userId ?? null;
67
+ }
68
+ /**
69
+ * Atomically establishes or verifies a durable identity pin.
70
+ *
71
+ * The immediate transaction serializes first contact across SDK instances that
72
+ * share the SQLite database. Conflict handling never replaces the existing
73
+ * keys: the winning pin is re-read and every identity field is compared before
74
+ * this method returns. When the keys match and the candidate's provenance
75
+ * ranks higher (an identity link confirming an observed pin), only the
76
+ * provenance is raised; it is never lowered.
77
+ *
78
+ * `assertCurrent` is the caller's lifetime check. It guards the write
79
+ * transaction's COMMIT, so an operation whose account or database changed
80
+ * while it awaited SQLite rolls its pin back instead of committing it.
81
+ */
82
+ async compareOrInsertTrustedUserIdentityPin(input) {
83
+ const [stored] = await this.compareOrInsertTrustedUserIdentityPins({
84
+ assertCurrent: input.assertCurrent,
85
+ pins: [input.pin],
86
+ });
87
+ if (!stored)
88
+ throw new TrustedUserIdentityPinCorruptError(input.pin, "pin not stored");
89
+ return stored;
90
+ }
91
+ /**
92
+ * Compare-or-insert a set of pins in one write transaction: a conflict on any
93
+ * pin, or a failed `assertCurrent` at COMMIT, leaves none of them stored.
94
+ */
95
+ async compareOrInsertTrustedUserIdentityPins(input) {
96
+ const { assertCurrent = () => { } } = input;
97
+ for (const pin of input.pins)
98
+ assertCandidatePin(pin);
99
+ const runtime = getClientSQLitePersistenceRuntime(this.execSql);
100
+ return runTrustedUserIdentityPinTransaction(async () => {
101
+ await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);
102
+ // Like the write path's BEGIN, this read's BEGIN retries while any adapter
103
+ // holds the connection's transaction, so it never sees uncommitted pins.
104
+ const pinned = await runtime.transaction(async (tx) => {
105
+ const matched = [];
106
+ for (const pin of input.pins) {
107
+ const stored = await matchingPin(tx, pin);
108
+ if (!stored)
109
+ return null;
110
+ matched.push(stored);
111
+ }
112
+ return matched;
113
+ });
114
+ if (pinned)
115
+ return pinned;
116
+ return runtime.transaction(async (tx) => {
117
+ registerClientSQLiteCommitGuard(this.execSql, assertCurrent);
118
+ const stored = [];
119
+ for (const pin of input.pins)
120
+ stored.push(await writePin(tx, pin));
121
+ return stored;
122
+ }, { behavior: "immediate" });
123
+ });
124
+ }
125
+ }
126
+ async function selectStoredPin(db, scope) {
127
+ const rows = await db
128
+ .select()
129
+ .from(pins)
130
+ .where(and(eq(pins.identityTrustDomain, scope.identityTrustDomain), eq(pins.userId, scope.userId)))
131
+ .limit(1);
132
+ const row = rows[0];
133
+ return row ? parseStoredPin(row, scope) : null;
134
+ }
135
+ /**
136
+ * One read answers an exact repeat of a pin that alone holds its
137
+ * key and ranks at or above the candidate; anything else returns null for the
138
+ * write transaction. Pins are never deleted, keys never change, and
139
+ * provenance only rises, so a match is what the transaction would return.
140
+ */
141
+ async function matchingPin(db, pin) {
142
+ const [row, other] = await db
143
+ .select()
144
+ .from(pins)
145
+ .where(and(eq(pins.identityTrustDomain, pin.identityTrustDomain), or(eq(pins.userId, pin.userId), eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint))))
146
+ .limit(2);
147
+ if (other || row?.userId !== pin.userId || validationFailure(row))
148
+ return null;
149
+ const stored = parseStoredPin(row, pin);
150
+ const rank = provenanceRank;
151
+ if (differingPinFields(stored, pin).length > 0)
152
+ return null;
153
+ return rank[pin.provenance] <= rank[stored.provenance] ? stored : null;
154
+ }
155
+ async function writePin(tx, pin) {
156
+ const aliases = await tx
157
+ .select()
158
+ .from(pins)
159
+ .where(and(eq(pins.identityTrustDomain, pin.identityTrustDomain), eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint)))
160
+ .limit(1);
161
+ const alias = aliases[0];
162
+ if (alias && alias.userId !== pin.userId) {
163
+ throw new TrustedUserIdentityPinMismatchError(parseStoredPin(alias, {
164
+ identityTrustDomain: pin.identityTrustDomain,
165
+ userId: alias.userId,
166
+ }), pin, ["userId"]);
167
+ }
168
+ // Targets the primary key only: re-pinning the same user is a no-op,
169
+ // but a write that would bind this key to a second user must fail at
170
+ // the unique index rather than be silently skipped.
171
+ await tx
172
+ .insert(pins)
173
+ .values(pin)
174
+ .onConflictDoNothing({
175
+ target: [pins.identityTrustDomain, pins.userId],
176
+ })
177
+ .run();
178
+ const stored = await selectStoredPin(tx, pin);
179
+ if (!stored) {
180
+ throw new TrustedUserIdentityPinCorruptError(pin, "row is missing after compare-or-insert");
181
+ }
182
+ const differingFields = differingPinFields(stored, pin);
183
+ if (differingFields.length > 0) {
184
+ throw new TrustedUserIdentityPinMismatchError(stored, pin, differingFields);
185
+ }
186
+ if (provenanceRank[pin.provenance] <= provenanceRank[stored.provenance]) {
187
+ return stored;
188
+ }
189
+ await tx
190
+ .update(pins)
191
+ .set({ provenance: pin.provenance })
192
+ .where(and(eq(pins.identityTrustDomain, pin.identityTrustDomain), eq(pins.userId, pin.userId)))
193
+ .run();
194
+ return { ...stored, provenance: pin.provenance };
195
+ }
196
+ //# sourceMappingURL=trustedUserIdentityPinRepository.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trustedUserIdentityPinRepository.js","sourceRoot":"","sources":["trustedUserIdentityPinRepository.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAGL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EACL,kBAAkB,E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C,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,IAAI,CAAC,mBAAmB,EAAE,GAAG,CAAC,mBAAmB,CAAC,EACrD,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAC5B,CACF;SACA,GAAG,EAAE,CAAC;IACT,OAAO,EAAE,GAAG,MAAM,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,EAAE,CAAC;AACnD,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport {\n trustedUserIdentityPins,\n trustedUserIdentityPinTables,\n} from \"../../sqlite/schema/trustedUserIdentityPinSchema\";\nimport { sqliteRowsPerStatement } from \"../../sqlite/sqliteBindBudget\";\nimport { registerClientSQLiteCommitGuard } from \"../../sqlite/sqliteCommitGuards\";\nimport {\n type ClientSQLiteDatabase,\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n assertCandidatePin,\n differingPinFields,\n type PinScope,\n parseStoredPin,\n provenanceRank,\n type TrustedUserIdentityPin,\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n validationFailure,\n} from \"./trustedUserIdentityPinModel\";\nimport { runTrustedUserIdentityPinTransaction } from \"./trustedUserIdentityPinTransaction\";\n\nconst pins = trustedUserIdentityPins;\n\n// Each member binds one ID; the trust domain binds once per statement.\nconst PIN_READ_BATCH_SIZE = sqliteRowsPerStatement(1, 1);\n\n/**\n * Durable trusted identity pins on one SQLite executor. Callers build it from\n * the executor in hand at each call; it holds no other state.\n */\nexport class TrustedUserIdentityPinRepository {\n private readonly execSql: ExecSql;\n\n constructor(execSql: ExecSql) {\n this.execSql = execSql;\n }\n\n async loadTrustedUserIdentityPin(\n input: PinScope,\n ): Promise<TrustedUserIdentityPin | null> {\n const scope: PinScope = {\n identityTrustDomain: input.identityTrustDomain,\n userId: input.userId,\n };\n await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);\n return selectStoredPin(\n getClientSQLitePersistenceRuntime(this.execSql).db,\n scope,\n );\n }\n\n /** Read immutable pins together, never exposing another adapter's uncommitted rows. */\n async loadTrustedUserIdentityPins(input: {\n readonly identityTrustDomain: string;\n readonly userIds: readonly string[];\n }): Promise<ReadonlyMap<string, TrustedUserIdentityPin>> {\n const userIds = [...new Set(input.userIds)];\n if (userIds.length === 0) return new Map();\n await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n return runTrustedUserIdentityPinTransaction(() =>\n runtime.transaction(async (tx) => {\n const loaded = new Map<string, TrustedUserIdentityPin>();\n for (\n let start = 0;\n start < userIds.length;\n start += PIN_READ_BATCH_SIZE\n ) {\n const batch = userIds.slice(start, start + PIN_READ_BATCH_SIZE);\n const rows = await tx\n .select()\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, input.identityTrustDomain),\n inArray(pins.userId, batch),\n ),\n );\n for (const row of rows) {\n const pin = parseStoredPin(row, {\n identityTrustDomain: input.identityTrustDomain,\n userId: row.userId,\n });\n loaded.set(pin.userId, pin);\n }\n }\n return loaded;\n }),\n );\n }\n\n /**\n * The user a signing key is already bound to in this trust domain, if any.\n * Each key has at most one such user: the reverse binding is unique.\n */\n async loadTrustedUserIdForSigningKey(input: {\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n }): Promise<string | null> {\n await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ userId: pins.userId })\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, input.identityTrustDomain),\n eq(pins.signingKeyFingerprint, input.signingKeyFingerprint),\n ),\n )\n .limit(1);\n return rows[0]?.userId ?? null;\n }\n\n /**\n * Atomically establishes or verifies a durable identity pin.\n *\n * The immediate transaction serializes first contact across SDK instances that\n * share the SQLite database. Conflict handling never replaces the existing\n * keys: the winning pin is re-read and every identity field is compared before\n * this method returns. When the keys match and the candidate's provenance\n * ranks higher (an identity link confirming an observed pin), only the\n * provenance is raised; it is never lowered.\n *\n * `assertCurrent` is the caller's lifetime check. It guards the write\n * transaction's COMMIT, so an operation whose account or database changed\n * while it awaited SQLite rolls its pin back instead of committing it.\n */\n async compareOrInsertTrustedUserIdentityPin(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly pin: TrustedUserIdentityPin;\n }): Promise<TrustedUserIdentityPin> {\n const [stored] = await this.compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n pins: [input.pin],\n });\n if (!stored)\n throw new TrustedUserIdentityPinCorruptError(input.pin, \"pin not stored\");\n return stored;\n }\n\n /**\n * Compare-or-insert a set of pins in one write transaction: a conflict on any\n * pin, or a failed `assertCurrent` at COMMIT, leaves none of them stored.\n */\n async compareOrInsertTrustedUserIdentityPins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly pins: readonly TrustedUserIdentityPin[];\n }): Promise<TrustedUserIdentityPin[]> {\n const { assertCurrent = () => {} } = input;\n for (const pin of input.pins) assertCandidatePin(pin);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n return runTrustedUserIdentityPinTransaction(async () => {\n await ensureSqlTables(this.execSql, trustedUserIdentityPinTables);\n // Like the write path's BEGIN, this read's BEGIN retries while any adapter\n // holds the connection's transaction, so it never sees uncommitted pins.\n const pinned = await runtime.transaction(async (tx) => {\n const matched: TrustedUserIdentityPin[] = [];\n for (const pin of input.pins) {\n const stored = await matchingPin(tx, pin);\n if (!stored) return null;\n matched.push(stored);\n }\n return matched;\n });\n if (pinned) return pinned;\n return runtime.transaction(\n async (tx) => {\n registerClientSQLiteCommitGuard(this.execSql, assertCurrent);\n const stored: TrustedUserIdentityPin[] = [];\n for (const pin of input.pins) stored.push(await writePin(tx, pin));\n return stored;\n },\n { behavior: \"immediate\" },\n );\n });\n }\n}\n\nasync function selectStoredPin(\n db: ClientSQLiteDatabase | ClientSQLiteTransactionScope,\n scope: PinScope,\n): Promise<TrustedUserIdentityPin | null> {\n const rows = await db\n .select()\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, scope.identityTrustDomain),\n eq(pins.userId, scope.userId),\n ),\n )\n .limit(1);\n const row = rows[0];\n return row ? parseStoredPin(row, scope) : null;\n}\n\n/**\n * One read answers an exact repeat of a pin that alone holds its\n * key and ranks at or above the candidate; anything else returns null for the\n * write transaction. Pins are never deleted, keys never change, and\n * provenance only rises, so a match is what the transaction would return.\n */\nasync function matchingPin(\n db: ClientSQLiteTransactionScope,\n pin: TrustedUserIdentityPin,\n): Promise<TrustedUserIdentityPin | null> {\n const [row, other] = await db\n .select()\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, pin.identityTrustDomain),\n or(\n eq(pins.userId, pin.userId),\n eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint),\n ),\n ),\n )\n .limit(2);\n if (other || row?.userId !== pin.userId || validationFailure(row))\n return null;\n const stored = parseStoredPin(row, pin);\n const rank = provenanceRank;\n if (differingPinFields(stored, pin).length > 0) return null;\n return rank[pin.provenance] <= rank[stored.provenance] ? stored : null;\n}\n\nasync function writePin(\n tx: ClientSQLiteTransactionScope,\n pin: TrustedUserIdentityPin,\n): Promise<TrustedUserIdentityPin> {\n const aliases = await tx\n .select()\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, pin.identityTrustDomain),\n eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint),\n ),\n )\n .limit(1);\n const alias = aliases[0];\n if (alias && alias.userId !== pin.userId) {\n throw new TrustedUserIdentityPinMismatchError(\n parseStoredPin(alias, {\n identityTrustDomain: pin.identityTrustDomain,\n userId: alias.userId,\n }),\n pin,\n [\"userId\"],\n );\n }\n // Targets the primary key only: re-pinning the same user is a no-op,\n // but a write that would bind this key to a second user must fail at\n // the unique index rather than be silently skipped.\n await tx\n .insert(pins)\n .values(pin)\n .onConflictDoNothing({\n target: [pins.identityTrustDomain, pins.userId],\n })\n .run();\n\n const stored = await selectStoredPin(tx, pin);\n if (!stored) {\n throw new TrustedUserIdentityPinCorruptError(\n pin,\n \"row is missing after compare-or-insert\",\n );\n }\n\n const differingFields = differingPinFields(stored, pin);\n if (differingFields.length > 0) {\n throw new TrustedUserIdentityPinMismatchError(stored, pin, differingFields);\n }\n if (provenanceRank[pin.provenance] <= provenanceRank[stored.provenance]) {\n return stored;\n }\n await tx\n .update(pins)\n .set({ provenance: pin.provenance })\n .where(\n and(\n eq(pins.identityTrustDomain, pin.identityTrustDomain),\n eq(pins.userId, pin.userId),\n ),\n )\n .run();\n return { ...stored, provenance: pin.provenance };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type TrustedUserIdentityPinProvenance } from "../persistence/trustedUserIdentityPinPersistence.js";
1
+ import type { TrustedUserIdentityPinProvenance } from "../persistence/identity/trustedUserIdentityPinModel.js";
2
2
  import type { ExecSql } from "../sqlite/sqlSchema.js";
3
3
  import { type TrustedUserIdentity } from "./types.js";
4
4
  /**
@@ -1,5 +1,5 @@
1
1
  import { base64ToBytes } from "../../internal/encoding/index.js";
2
- import { loadTrustedUserIdentityPin, } from "../persistence/trustedUserIdentityPinPersistence.js";
2
+ import { TrustedUserIdentityPinRepository } from "../persistence/identity/trustedUserIdentityPinRepository.js";
3
3
  import { brandTrustedUserIdentity } from "./types.js";
4
4
  import { assertTrustedUserIdentityUserId, validateUserIdentityKeys, } from "./validation.js";
5
5
  /**
@@ -9,7 +9,7 @@ import { assertTrustedUserIdentityUserId, validateUserIdentityKeys, } from "./va
9
9
  */
10
10
  export async function loadPin(input) {
11
11
  assertTrustedUserIdentityUserId(input.userId);
12
- const pin = await loadTrustedUserIdentityPin(input);
12
+ const pin = await new TrustedUserIdentityPinRepository(input.execSql).loadTrustedUserIdentityPin(input);
13
13
  if (!pin)
14
14
  return null;
15
15
  const keys = await validateUserIdentityKeys({
@@ -1 +1 @@
1
- {"version":3,"file":"pinnedIdentity.js","sourceRoot":"","sources":["pinnedIdentity.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,0BAA0B,GAE3B,MAAM,kDAAkD,CAAC;AAE1D,OAAO,EAAE,wBAAwB,EAA4B,MAAM,SAAS,CAAC;AAC7E,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,GACzB,MAAM,cAAc,CAAC;AAEtB;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,KAI7B;IAIC,+BAA+B,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAC9C,MAAM,GAAG,GAAG,MAAM,0BAA0B,CAAC,KAAK,CAAC,CAAC;IACpD,IAAI,CAAC,GAAG;QAAE,OAAO,IAAI,CAAC;IACtB,MAAM,IAAI,GAAG,MAAM,wBAAwB,CAAC;QAC1C,SAAS,EAAE;YACT,sBAAsB,EAAE,aAAa,CAAC,GAAG,CAAC,sBAAsB,CAAC;YACjE,qBAAqB,EAAE,GAAG,CAAC,qBAAqB;YAChD,gBAAgB,EAAE,aAAa,CAAC,GAAG,CAAC,gBAAgB,CAAC;SACtD;QACD,2BAA2B,EAAE,GAAG,CAAC,2BAA2B;KAC7D,CAAC,CAAC;IACH,OAAO;QACL,QAAQ,EAAE,wBAAwB,CAAC;YACjC,GAAG,IAAI;YACP,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,MAAM,EAAE,KAAK,CAAC,MAAM;SACrB,CAAC;QACF,UAAU,EAAE,GAAG,CAAC,UAAU;KAC3B,CAAC;AACJ,CAAC;AAED,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,KAI5C;IACC,OAAO,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,IAAI,IAAI,CAAC;AAClD,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport {\n loadTrustedUserIdentityPin,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/trustedUserIdentityPinPersistence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { brandTrustedUserIdentity, type TrustedUserIdentity } from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateUserIdentityKeys,\n} from \"./validation\";\n\n/**\n * Read-only: the identity this trust store already pins for `userId` and how\n * it was established, or null. The stored keys must still match their stored\n * fingerprints. Never inserts, compares against or replaces a pin.\n */\nexport async function loadPin(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<{\n readonly identity: TrustedUserIdentity;\n readonly provenance: TrustedUserIdentityPinProvenance;\n} | null> {\n assertTrustedUserIdentityUserId(input.userId);\n const pin = await loadTrustedUserIdentityPin(input);\n if (!pin) return null;\n const keys = await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: base64ToBytes(pin.encapsulationPublicKey),\n signingKeyFingerprint: pin.signingKeyFingerprint,\n signingPublicKey: base64ToBytes(pin.signingPublicKey),\n },\n encapsulationKeyFingerprint: pin.encapsulationKeyFingerprint,\n });\n return {\n identity: brandTrustedUserIdentity({\n ...keys,\n identityTrustDomain: input.identityTrustDomain,\n userId: input.userId,\n }),\n provenance: pin.provenance,\n };\n}\n\n/** Read-only: the pinned identity for `userId` of any provenance, or null. */\nexport async function loadPinnedUserIdentity(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<TrustedUserIdentity | null> {\n return (await loadPin(input))?.identity ?? null;\n}\n"]}
1
+ {"version":3,"file":"pinnedIdentity.js","sourceRoot":"","sources":["pinnedIdentity.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAE5G,OAAO,EAAE,wBAAwB,EAA4B,MAAM,SAAS,CAAC;AAC7E,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,GACzB,MAAM,cAAc,CAAC;AAEtB;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,KAI7B;IAIC,+BAA+B,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAC9C,MAAM,GAAG,GAAG,MAAM,IAAI,gCAAgC,CACpD,KAAK,CAAC,OAAO,CACd,CAAC,0BAA0B,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,CAAC,GAAG;QAAE,OAAO,IAAI,CAAC;IACtB,MAAM,IAAI,GAAG,MAAM,wBAAwB,CAAC;QAC1C,SAAS,EAAE;YACT,sBAAsB,EAAE,aAAa,CAAC,GAAG,CAAC,sBAAsB,CAAC;YACjE,qBAAqB,EAAE,GAAG,CAAC,qBAAqB;YAChD,gBAAgB,EAAE,aAAa,CAAC,GAAG,CAAC,gBAAgB,CAAC;SACtD;QACD,2BAA2B,EAAE,GAAG,CAAC,2BAA2B;KAC7D,CAAC,CAAC;IACH,OAAO;QACL,QAAQ,EAAE,wBAAwB,CAAC;YACjC,GAAG,IAAI;YACP,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,MAAM,EAAE,KAAK,CAAC,MAAM;SACrB,CAAC;QACF,UAAU,EAAE,GAAG,CAAC,UAAU;KAC3B,CAAC;AACJ,CAAC;AAED,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,KAI5C;IACC,OAAO,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,IAAI,IAAI,CAAC;AAClD,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport type { TrustedUserIdentityPinProvenance } from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { brandTrustedUserIdentity, type TrustedUserIdentity } from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateUserIdentityKeys,\n} from \"./validation\";\n\n/**\n * Read-only: the identity this trust store already pins for `userId` and how\n * it was established, or null. The stored keys must still match their stored\n * fingerprints. Never inserts, compares against or replaces a pin.\n */\nexport async function loadPin(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<{\n readonly identity: TrustedUserIdentity;\n readonly provenance: TrustedUserIdentityPinProvenance;\n} | null> {\n assertTrustedUserIdentityUserId(input.userId);\n const pin = await new TrustedUserIdentityPinRepository(\n input.execSql,\n ).loadTrustedUserIdentityPin(input);\n if (!pin) return null;\n const keys = await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: base64ToBytes(pin.encapsulationPublicKey),\n signingKeyFingerprint: pin.signingKeyFingerprint,\n signingPublicKey: base64ToBytes(pin.signingPublicKey),\n },\n encapsulationKeyFingerprint: pin.encapsulationKeyFingerprint,\n });\n return {\n identity: brandTrustedUserIdentity({\n ...keys,\n identityTrustDomain: input.identityTrustDomain,\n userId: input.userId,\n }),\n provenance: pin.provenance,\n };\n}\n\n/** Read-only: the pinned identity for `userId` of any provenance, or null. */\nexport async function loadPinnedUserIdentity(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<TrustedUserIdentity | null> {\n return (await loadPin(input))?.identity ?? null;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
- import { loadTrustedUserIdentityPins } from "../persistence/identity/trustedUserIdentityPinBatch.js";
3
- import { TrustedUserIdentityPinCorruptError } from "../persistence/identity/trustedUserIdentityPinModel.js";
4
- import { TrustedUserIdentityPinContentionError } from "../persistence/trustedUserIdentityPinTransaction.js";
2
+ import { TrustedUserIdentityPinCorruptError, } from "../persistence/identity/trustedUserIdentityPinModel.js";
3
+ import { TrustedUserIdentityPinRepository } from "../persistence/identity/trustedUserIdentityPinRepository.js";
4
+ import { TrustedUserIdentityPinContentionError } from "../persistence/identity/trustedUserIdentityPinTransaction.js";
5
5
  import { DatabaseUnavailableError } from "../sync/databaseUnavailable.js";
6
6
  import { assertTrustedUserIdentityUserId, validateRemoteUserIdentity, } from "./validation.js";
7
7
  /** The trust store, account, and runtime generation one operation runs in. */
@@ -109,8 +109,7 @@ export function withPinnedIdentityResolution(dependencies, resolve, firstSight,
109
109
  let published = false;
110
110
  let completed = false;
111
111
  try {
112
- const pins = await loadTrustedUserIdentityPins({
113
- execSql: scope.execSql,
112
+ const pins = await new TrustedUserIdentityPinRepository(scope.execSql).loadTrustedUserIdentityPins({
114
113
  identityTrustDomain: scope.identityTrustDomain,
115
114
  // Self always rechecks the authoritative local keys and provenance.
116
115
  userIds: userIds.filter((userId) => userId !== scope.localUserId),
@@ -1 +1 @@
1
- {"version":3,"file":"pinnedResolution.js","sourceRoot":"","sources":["pinnedResolution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,qDAAqD,CAAC;AAClG,OAAO,EAAE,kCAAkC,EAAE,MAAM,qDAAqD,CAAC;AAEzG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAEzG,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAYvE,OAAO,EACL,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,cAAc,CAAC;AAyBtB,8EAA8E;AAC9E,SAAS,eAAe,CACtB,YAAoD;IAEpD,MAAM,mBAAmB,GAAG,YAAY,CAAC,mBAAmB,CAAC;IAC7D,IAAI,CAAC,mBAAmB;QACtB,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,qEAAqE,CACtE,CAAC;IACJ,MAAM,OAAO,GAAG,YAAY,CAAC,UAAU,EAAE,CAAC;IAC1C,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,wBAAwB,CAChC,sEAAsE,CACvE,CAAC;IACJ,MAAM,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,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 { loadTrustedUserIdentityPins } from \"../persistence/identity/trustedUserIdentityPinBatch\";\nimport { TrustedUserIdentityPinCorruptError } from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport type { TrustedUserIdentityPin } from \"../persistence/trustedUserIdentityPinPersistence\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/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 loadTrustedUserIdentityPins({\n execSql: scope.execSql,\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;AAElH,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAYvE,OAAO,EACL,+BAA+B,EAC/B,0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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,9 +1,8 @@
1
1
  import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
2
  import { bytesToBase64 } from "../../internal/encoding/index.js";
3
3
  import { TrustedUserIdentityPinCorruptError, TrustedUserIdentityPinMismatchError, } from "../persistence/identity/trustedUserIdentityPinModel.js";
4
- import { loadTrustedUserIdForSigningKey } from "../persistence/identity/trustedUserIdentitySigningKeyBinding.js";
5
- import { compareOrInsertTrustedUserIdentityPins, } from "../persistence/trustedUserIdentityPinPersistence.js";
6
- import { TrustedUserIdentityPinContentionError } from "../persistence/trustedUserIdentityPinTransaction.js";
4
+ import { TrustedUserIdentityPinRepository } from "../persistence/identity/trustedUserIdentityPinRepository.js";
5
+ import { TrustedUserIdentityPinContentionError } from "../persistence/identity/trustedUserIdentityPinTransaction.js";
7
6
  import { DatabaseUnavailableError } from "../sync/databaseUnavailable.js";
8
7
  import { UnverifiedUserIdentityError } from "./admission.js";
9
8
  import { assertIdentityLinkMatches, createIdentityLink, parseIdentityLink, } from "./identityLink.js";
@@ -50,9 +49,8 @@ function durablePin(identity, provenance, firstSeenAt) {
50
49
  async function compareWithDurablePins(input) {
51
50
  const userIds = input.identities.map((identity) => identity.userId);
52
51
  try {
53
- await compareOrInsertTrustedUserIdentityPins({
52
+ await new TrustedUserIdentityPinRepository(input.execSql).compareOrInsertTrustedUserIdentityPins({
54
53
  assertCurrent: input.assertCurrent,
55
- execSql: input.execSql,
56
54
  pins: input.identities.map((identity) => durablePin(identity, input.provenance, input.firstSeenAt)),
57
55
  });
58
56
  }
@@ -124,6 +122,14 @@ async function pinIdentity(input) {
124
122
  });
125
123
  return brandTrustedUserIdentity(input.identity);
126
124
  }
125
+ /** The user this trust store already binds to a signing key, if any. */
126
+ async function boundUserId(dependencies, signingKeyFingerprint) {
127
+ const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
128
+ return new TrustedUserIdentityPinRepository(execSql).loadTrustedUserIdForSigningKey({
129
+ identityTrustDomain,
130
+ signingKeyFingerprint,
131
+ });
132
+ }
127
133
  /** Compares an independently received link before pinning it as `link`. */
128
134
  async function verifyIdentityLink(dependencies, link) {
129
135
  const expectation = parseIdentityLink(link);
@@ -227,14 +233,7 @@ export function createTrustedUserIdentityService(input) {
227
233
  return identity ? createIdentityLink(identity, appUrl) : null;
228
234
  },
229
235
  verifyLink: (link) => verifyIdentityLink(dependencies, link),
230
- async boundUserId(signingKeyFingerprint) {
231
- const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
232
- return loadTrustedUserIdForSigningKey({
233
- execSql,
234
- identityTrustDomain,
235
- signingKeyFingerprint,
236
- });
237
- },
236
+ boundUserId: (signingKeyFingerprint) => boundUserId(dependencies, signingKeyFingerprint),
238
237
  async pinLocal(userId, candidate) {
239
238
  assertTrustedUserIdentityUserId(userId);
240
239
  const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
@@ -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,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,8BAA8B,EAAE,MAAM,8DAA8D,CAAC;AAC9G,OAAO,EACL,sCAAsC,GAEvC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAEzG,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,4BAA4B,EAAE,MAAM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ACD,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} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { loadTrustedUserIdForSigningKey } from \"../persistence/identity/trustedUserIdentitySigningKeyBinding\";\nimport {\n compareOrInsertTrustedUserIdentityPins,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/trustedUserIdentityPinPersistence\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/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 compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\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/** 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 async boundUserId(signingKeyFingerprint) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadTrustedUserIdForSigningKey({\n execSql,\n identityTrustDomain,\n signingKeyFingerprint,\n });\n },\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"],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,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 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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.198",
3
+ "version": "0.1.199",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1,36 +0,0 @@
1
- import { and, eq, inArray } from "drizzle-orm";
2
- import { trustedUserIdentityPins, trustedUserIdentityPinTables, } from "../../sqlite/schema/trustedUserIdentityPinSchema.js";
3
- import { sqliteRowsPerStatement } from "../../sqlite/sqliteBindBudget.js";
4
- import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
5
- import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
- import { parseStoredPin, } from "../trustedUserIdentityPinPersistence.js";
7
- import { runTrustedUserIdentityPinTransaction } from "../trustedUserIdentityPinTransaction.js";
8
- // Each member binds one ID; the trust domain binds once per statement.
9
- const PIN_READ_BATCH_SIZE = sqliteRowsPerStatement(1, 1);
10
- /** Read immutable pins together, never exposing another adapter's uncommitted rows. */
11
- export async function loadTrustedUserIdentityPins(input) {
12
- const userIds = [...new Set(input.userIds)];
13
- if (userIds.length === 0)
14
- return new Map();
15
- await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);
16
- const runtime = getClientSQLitePersistenceRuntime(input.execSql);
17
- return runTrustedUserIdentityPinTransaction(() => runtime.transaction(async (tx) => {
18
- const pins = new Map();
19
- for (let start = 0; start < userIds.length; start += PIN_READ_BATCH_SIZE) {
20
- const batch = userIds.slice(start, start + PIN_READ_BATCH_SIZE);
21
- const rows = await tx
22
- .select()
23
- .from(trustedUserIdentityPins)
24
- .where(and(eq(trustedUserIdentityPins.identityTrustDomain, input.identityTrustDomain), inArray(trustedUserIdentityPins.userId, batch)));
25
- for (const row of rows) {
26
- const pin = parseStoredPin(row, {
27
- identityTrustDomain: input.identityTrustDomain,
28
- userId: row.userId,
29
- });
30
- pins.set(pin.userId, pin);
31
- }
32
- }
33
- return pins;
34
- }));
35
- }
36
- //# sourceMappingURL=trustedUserIdentityPinBatch.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"trustedUserIdentityPinBatch.js","sourceRoot":"","sources":["trustedUserIdentityPinBatch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAu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CAAC;YACJ,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;gBACvB,MAAM,GAAG,GAAG,cAAc,CAAC,GAAG,EAAE;oBAC9B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;oBAC9C,MAAM,EAAE,GAAG,CAAC,MAAM;iBACnB,CAAC,CAAC;gBACH,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { and, eq, inArray } from \"drizzle-orm\";\nimport {\n trustedUserIdentityPins,\n trustedUserIdentityPinTables,\n} from \"../../sqlite/schema/trustedUserIdentityPinSchema\";\nimport { sqliteRowsPerStatement } from \"../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n parseStoredPin,\n type TrustedUserIdentityPin,\n} from \"../trustedUserIdentityPinPersistence\";\nimport { runTrustedUserIdentityPinTransaction } from \"../trustedUserIdentityPinTransaction\";\n\n// Each member binds one ID; the trust domain binds once per statement.\nconst PIN_READ_BATCH_SIZE = sqliteRowsPerStatement(1, 1);\n\n/** Read immutable pins together, never exposing another adapter's uncommitted rows. */\nexport async function loadTrustedUserIdentityPins(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userIds: readonly string[];\n}): Promise<ReadonlyMap<string, TrustedUserIdentityPin>> {\n const userIds = [...new Set(input.userIds)];\n if (userIds.length === 0) return new Map();\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n return runTrustedUserIdentityPinTransaction(() =>\n runtime.transaction(async (tx) => {\n const pins = new Map<string, TrustedUserIdentityPin>();\n for (\n let start = 0;\n start < userIds.length;\n start += PIN_READ_BATCH_SIZE\n ) {\n const batch = userIds.slice(start, start + PIN_READ_BATCH_SIZE);\n const rows = await tx\n .select()\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n input.identityTrustDomain,\n ),\n inArray(trustedUserIdentityPins.userId, batch),\n ),\n );\n for (const row of rows) {\n const pin = parseStoredPin(row, {\n identityTrustDomain: input.identityTrustDomain,\n userId: row.userId,\n });\n pins.set(pin.userId, pin);\n }\n }\n return pins;\n }),\n );\n}\n"]}
@@ -1,18 +0,0 @@
1
- import { and, eq } from "drizzle-orm";
2
- import { trustedUserIdentityPins, trustedUserIdentityPinTables, } from "../../sqlite/schema/trustedUserIdentityPinSchema.js";
3
- import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
4
- import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
5
- /**
6
- * The user a signing key is already bound to in this trust domain, if any.
7
- * Each key has at most one such user: the reverse binding is unique.
8
- */
9
- export async function loadTrustedUserIdForSigningKey(input) {
10
- await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);
11
- const rows = await getClientSQLitePersistenceRuntime(input.execSql)
12
- .db.select({ userId: trustedUserIdentityPins.userId })
13
- .from(trustedUserIdentityPins)
14
- .where(and(eq(trustedUserIdentityPins.identityTrustDomain, input.identityTrustDomain), eq(trustedUserIdentityPins.signingKeyFingerprint, input.signingKeyFingerprint)))
15
- .limit(1);
16
- return rows[0]?.userId ?? null;
17
- }
18
- //# sourceMappingURL=trustedUserIdentitySigningKeyBinding.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"trustedUserIdentitySigningKeyBinding.js","sourceRoot":"","sources":["trustedUserIdentitySigningKeyBinding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEvE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KAIpD;IACC,MAAM,eAAe,CAAC,KAAK,CAAC,OAAO,EAAE,4BAA4B,CAAC,CAAC;IACnE,MAAM,IAAI,GAAG,MAAM,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC;SAChE,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,uBAAuB,CAAC,MAAM,EAAE,CAAC;SACrD,IAAI,CAAC,uBAAuB,CAAC;SAC7B,KAAK,CACJ,GAAG,CACD,EAAE,CACA,uBAAuB,CAAC,mBAAmB,EAC3C,KAAK,CAAC,mBAAmB,CAC1B,EACD,EAAE,CACA,uBAAuB,CAAC,qBAAqB,EAC7C,KAAK,CAAC,qBAAqB,CAC5B,CACF,CACF;SACA,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,MAAM,IAAI,IAAI,CAAC;AACjC,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n trustedUserIdentityPins,\n trustedUserIdentityPinTables,\n} from \"../../sqlite/schema/trustedUserIdentityPinSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\n\n/**\n * The user a signing key is already bound to in this trust domain, if any.\n * Each key has at most one such user: the reverse binding is unique.\n */\nexport async function loadTrustedUserIdForSigningKey(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n}): Promise<string | null> {\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n const rows = await getClientSQLitePersistenceRuntime(input.execSql)\n .db.select({ userId: trustedUserIdentityPins.userId })\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n input.identityTrustDomain,\n ),\n eq(\n trustedUserIdentityPins.signingKeyFingerprint,\n input.signingKeyFingerprint,\n ),\n ),\n )\n .limit(1);\n return rows[0]?.userId ?? null;\n}\n"]}
@@ -1,37 +0,0 @@
1
- import { type ExecSql } from "../sqlite/sqlSchema.js";
2
- import { type PinScope, type TrustedUserIdentityPin } from "./identity/trustedUserIdentityPinModel.js";
3
- export type { TrustedUserIdentityPin, TrustedUserIdentityPinProvenance, } from "./identity/trustedUserIdentityPinModel.js";
4
- export declare function parseStoredPin(value: unknown, scope: PinScope): TrustedUserIdentityPin;
5
- export declare function loadTrustedUserIdentityPin(input: {
6
- readonly execSql: ExecSql;
7
- readonly identityTrustDomain: string;
8
- readonly userId: string;
9
- }): Promise<TrustedUserIdentityPin | null>;
10
- /**
11
- * Atomically establishes or verifies a durable identity pin.
12
- *
13
- * The immediate transaction serializes first contact across SDK instances that
14
- * share the SQLite database. Conflict handling never replaces the existing
15
- * keys: the winning pin is re-read and every identity field is compared before
16
- * this function returns. When the keys match and the candidate's provenance
17
- * ranks higher (an identity link confirming an observed pin), only the
18
- * provenance is raised; it is never lowered.
19
- *
20
- * `assertCurrent` is the caller's lifetime check. It guards the write
21
- * transaction's COMMIT, so an operation whose account or database changed
22
- * while it awaited SQLite rolls its pin back instead of committing it.
23
- */
24
- export declare function compareOrInsertTrustedUserIdentityPin(input: {
25
- readonly assertCurrent?: (() => void) | undefined;
26
- readonly execSql: ExecSql;
27
- readonly pin: TrustedUserIdentityPin;
28
- }): Promise<TrustedUserIdentityPin>;
29
- /**
30
- * Compare-or-insert a set of pins in one write transaction: a conflict on any
31
- * pin, or a failed `assertCurrent` at COMMIT, leaves none of them stored.
32
- */
33
- export declare function compareOrInsertTrustedUserIdentityPins(input: {
34
- readonly assertCurrent?: (() => void) | undefined;
35
- readonly execSql: ExecSql;
36
- readonly pins: readonly TrustedUserIdentityPin[];
37
- }): Promise<TrustedUserIdentityPin[]>;
@@ -1,258 +0,0 @@
1
- import { and, eq, or } from "drizzle-orm";
2
- import { trustedUserIdentityPins, trustedUserIdentityPinTables, } from "../sqlite/schema/trustedUserIdentityPinSchema.js";
3
- import { registerClientSQLiteCommitGuard } from "../sqlite/sqliteCommitGuards.js";
4
- import { getClientSQLitePersistenceRuntime, } from "../sqlite/sqlitePersistenceRuntime.js";
5
- import { ensureSqlTables } from "../sqlite/sqlSchema.js";
6
- import { TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE, TRUSTED_USER_IDENTITY_FORMAT_VERSION, TRUSTED_USER_IDENTITY_SIGNING_SUITE, } from "../trustedUserIdentity/types.js";
7
- import { differingPinFields, TrustedUserIdentityPinCorruptError, TrustedUserIdentityPinInputError, TrustedUserIdentityPinMismatchError, } from "./identity/trustedUserIdentityPinModel.js";
8
- import { runTrustedUserIdentityPinTransaction } from "./trustedUserIdentityPinTransaction.js";
9
- const provenanceRank = { observed: 0, link: 1, self: 2 };
10
- function isTrustedUserIdentityPinProvenance(value) {
11
- return value === "self" || value === "link" || value === "observed";
12
- }
13
- const requiredStringFields = [
14
- "identityTrustDomain",
15
- "userId",
16
- "signingSuite",
17
- "signingPublicKey",
18
- "signingKeyFingerprint",
19
- "encapsulationSuite",
20
- "encapsulationPublicKey",
21
- "encapsulationKeyFingerprint",
22
- ];
23
- function pinScope(value) {
24
- if (typeof value !== "object" || value === null) {
25
- return { identityTrustDomain: "<invalid>", userId: "<invalid>" };
26
- }
27
- const identityTrustDomain = Reflect.get(value, "identityTrustDomain");
28
- const userId = Reflect.get(value, "userId");
29
- return {
30
- identityTrustDomain: typeof identityTrustDomain === "string"
31
- ? identityTrustDomain
32
- : "<invalid>",
33
- userId: typeof userId === "string" ? userId : "<invalid>",
34
- };
35
- }
36
- function validationFailure(value) {
37
- if (typeof value !== "object" || value === null) {
38
- return "row must be an object";
39
- }
40
- const formatVersion = Reflect.get(value, "formatVersion");
41
- if (formatVersion !== TRUSTED_USER_IDENTITY_FORMAT_VERSION) {
42
- return `formatVersion must be ${TRUSTED_USER_IDENTITY_FORMAT_VERSION}`;
43
- }
44
- for (const field of requiredStringFields) {
45
- const fieldValue = Reflect.get(value, field);
46
- if (typeof fieldValue !== "string" || fieldValue.trim().length === 0) {
47
- return `${field} must be a non-empty string`;
48
- }
49
- }
50
- if (Reflect.get(value, "signingSuite") !== TRUSTED_USER_IDENTITY_SIGNING_SUITE) {
51
- return `signingSuite must be ${TRUSTED_USER_IDENTITY_SIGNING_SUITE}`;
52
- }
53
- if (Reflect.get(value, "encapsulationSuite") !==
54
- TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE) {
55
- return `encapsulationSuite must be ${TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE}`;
56
- }
57
- const firstSeenAt = Reflect.get(value, "firstSeenAt");
58
- if (typeof firstSeenAt !== "string" ||
59
- !Number.isFinite(Date.parse(firstSeenAt))) {
60
- return "firstSeenAt must be a valid timestamp";
61
- }
62
- if (!isTrustedUserIdentityPinProvenance(Reflect.get(value, "provenance"))) {
63
- return "provenance must be self, link, or observed";
64
- }
65
- return null;
66
- }
67
- function validatedStringField(value, field) {
68
- const fieldValue = Reflect.get(value, field);
69
- if (typeof fieldValue !== "string") {
70
- throw new TypeError(`Validated pin field ${field} is not a string`);
71
- }
72
- return fieldValue;
73
- }
74
- function validatedFormatVersion(value) {
75
- const formatVersion = Reflect.get(value, "formatVersion");
76
- if (typeof formatVersion !== "number") {
77
- throw new TypeError("Validated pin formatVersion is not a number");
78
- }
79
- return formatVersion;
80
- }
81
- function validatedProvenance(value) {
82
- const provenance = Reflect.get(value, "provenance");
83
- if (!isTrustedUserIdentityPinProvenance(provenance)) {
84
- throw new TypeError("Validated pin provenance is not a provenance");
85
- }
86
- return provenance;
87
- }
88
- function assertCandidatePin(pin) {
89
- const failure = validationFailure(pin);
90
- if (failure) {
91
- throw new TrustedUserIdentityPinInputError(pinScope(pin), failure);
92
- }
93
- }
94
- export function parseStoredPin(value, scope) {
95
- const failure = validationFailure(value);
96
- if (failure) {
97
- throw new TrustedUserIdentityPinCorruptError(scope, failure);
98
- }
99
- if (typeof value !== "object" || value === null) {
100
- throw new TrustedUserIdentityPinCorruptError(scope, "row must be an object");
101
- }
102
- const pin = {
103
- identityTrustDomain: validatedStringField(value, "identityTrustDomain"),
104
- userId: validatedStringField(value, "userId"),
105
- formatVersion: validatedFormatVersion(value),
106
- signingSuite: validatedStringField(value, "signingSuite"),
107
- signingPublicKey: validatedStringField(value, "signingPublicKey"),
108
- signingKeyFingerprint: validatedStringField(value, "signingKeyFingerprint"),
109
- encapsulationSuite: validatedStringField(value, "encapsulationSuite"),
110
- encapsulationPublicKey: validatedStringField(value, "encapsulationPublicKey"),
111
- encapsulationKeyFingerprint: validatedStringField(value, "encapsulationKeyFingerprint"),
112
- firstSeenAt: validatedStringField(value, "firstSeenAt"),
113
- provenance: validatedProvenance(value),
114
- };
115
- if (pin.identityTrustDomain !== scope.identityTrustDomain ||
116
- pin.userId !== scope.userId) {
117
- throw new TrustedUserIdentityPinCorruptError(scope, "primary-key scope does not match the requested pin");
118
- }
119
- return pin;
120
- }
121
- async function selectStoredPin(db, scope) {
122
- const rows = await db
123
- .select()
124
- .from(trustedUserIdentityPins)
125
- .where(and(eq(trustedUserIdentityPins.identityTrustDomain, scope.identityTrustDomain), eq(trustedUserIdentityPins.userId, scope.userId)))
126
- .limit(1);
127
- const row = rows[0];
128
- return row ? parseStoredPin(row, scope) : null;
129
- }
130
- export async function loadTrustedUserIdentityPin(input) {
131
- const scope = {
132
- identityTrustDomain: input.identityTrustDomain,
133
- userId: input.userId,
134
- };
135
- await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);
136
- return selectStoredPin(getClientSQLitePersistenceRuntime(input.execSql).db, scope);
137
- }
138
- /**
139
- * One read answers an exact repeat of a pin that alone holds its
140
- * key and ranks at or above the candidate; anything else returns null for the
141
- * write transaction. Pins are never deleted, keys never change, and
142
- * provenance only rises, so a match is what the transaction would return.
143
- */
144
- const pins = trustedUserIdentityPins;
145
- async function matchingPin(db, pin) {
146
- const [row, other] = await db
147
- .select()
148
- .from(pins)
149
- .where(and(eq(pins.identityTrustDomain, pin.identityTrustDomain), or(eq(pins.userId, pin.userId), eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint))))
150
- .limit(2);
151
- if (other || row?.userId !== pin.userId || validationFailure(row))
152
- return null;
153
- const stored = parseStoredPin(row, pin);
154
- const rank = provenanceRank;
155
- if (differingPinFields(stored, pin).length > 0)
156
- return null;
157
- return rank[pin.provenance] <= rank[stored.provenance] ? stored : null;
158
- }
159
- /**
160
- * Atomically establishes or verifies a durable identity pin.
161
- *
162
- * The immediate transaction serializes first contact across SDK instances that
163
- * share the SQLite database. Conflict handling never replaces the existing
164
- * keys: the winning pin is re-read and every identity field is compared before
165
- * this function returns. When the keys match and the candidate's provenance
166
- * ranks higher (an identity link confirming an observed pin), only the
167
- * provenance is raised; it is never lowered.
168
- *
169
- * `assertCurrent` is the caller's lifetime check. It guards the write
170
- * transaction's COMMIT, so an operation whose account or database changed
171
- * while it awaited SQLite rolls its pin back instead of committing it.
172
- */
173
- export async function compareOrInsertTrustedUserIdentityPin(input) {
174
- const [stored] = await compareOrInsertTrustedUserIdentityPins({
175
- assertCurrent: input.assertCurrent,
176
- execSql: input.execSql,
177
- pins: [input.pin],
178
- });
179
- if (!stored)
180
- throw new TrustedUserIdentityPinCorruptError(input.pin, "pin not stored");
181
- return stored;
182
- }
183
- /**
184
- * Compare-or-insert a set of pins in one write transaction: a conflict on any
185
- * pin, or a failed `assertCurrent` at COMMIT, leaves none of them stored.
186
- */
187
- export async function compareOrInsertTrustedUserIdentityPins(input) {
188
- const { assertCurrent = () => { } } = input;
189
- for (const pin of input.pins)
190
- assertCandidatePin(pin);
191
- const runtime = getClientSQLitePersistenceRuntime(input.execSql);
192
- return runTrustedUserIdentityPinTransaction(async () => {
193
- await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);
194
- // Like the write path's BEGIN, this read's BEGIN retries while any adapter
195
- // holds the connection's transaction, so it never sees uncommitted pins.
196
- const pinned = await runtime.transaction(async (tx) => {
197
- const matched = [];
198
- for (const pin of input.pins) {
199
- const stored = await matchingPin(tx, pin);
200
- if (!stored)
201
- return null;
202
- matched.push(stored);
203
- }
204
- return matched;
205
- });
206
- if (pinned)
207
- return pinned;
208
- return runtime.transaction(async (tx) => {
209
- registerClientSQLiteCommitGuard(input.execSql, assertCurrent);
210
- const stored = [];
211
- for (const pin of input.pins)
212
- stored.push(await writePin(tx, pin));
213
- return stored;
214
- }, { behavior: "immediate" });
215
- });
216
- }
217
- async function writePin(tx, pin) {
218
- const aliases = await tx
219
- .select()
220
- .from(pins)
221
- .where(and(eq(pins.identityTrustDomain, pin.identityTrustDomain), eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint)))
222
- .limit(1);
223
- const alias = aliases[0];
224
- if (alias && alias.userId !== pin.userId) {
225
- throw new TrustedUserIdentityPinMismatchError(parseStoredPin(alias, {
226
- identityTrustDomain: pin.identityTrustDomain,
227
- userId: alias.userId,
228
- }), pin, ["userId"]);
229
- }
230
- // Targets the primary key only: re-pinning the same user is a no-op,
231
- // but a write that would bind this key to a second user must fail at
232
- // the unique index rather than be silently skipped.
233
- await tx
234
- .insert(pins)
235
- .values(pin)
236
- .onConflictDoNothing({
237
- target: [pins.identityTrustDomain, pins.userId],
238
- })
239
- .run();
240
- const stored = await selectStoredPin(tx, pin);
241
- if (!stored) {
242
- throw new TrustedUserIdentityPinCorruptError(pin, "row is missing after compare-or-insert");
243
- }
244
- const differingFields = differingPinFields(stored, pin);
245
- if (differingFields.length > 0) {
246
- throw new TrustedUserIdentityPinMismatchError(stored, pin, differingFields);
247
- }
248
- if (provenanceRank[pin.provenance] <= provenanceRank[stored.provenance]) {
249
- return stored;
250
- }
251
- await tx
252
- .update(pins)
253
- .set({ provenance: pin.provenance })
254
- .where(and(eq(pins.identityTrustDomain, pin.identityTrustDomain), eq(pins.userId, pin.userId)))
255
- .run();
256
- return { ...stored, provenance: pin.provenance };
257
- }
258
- //# sourceMappingURL=trustedUserIdentityPinPersistence.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"trustedUserIdentityPinPersistence.js","sourceRoot":"","sources":["trustedUserIdentityPinPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAC/E,OAAO,EAGL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EACL,yCAAyC,EACzC,oCAAoC,EACpC,mCAAmC,GACpC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,kBAAkB,EAGlB,kCAAkC,EAClC,gCAAgC,EAChC,mCAAmC,GAEpC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,oCAAoC,EAAE,MAAM,qCAAqC,CAAC;AAO3F,MAAM,cAAc,GAEhB,EAAE,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AAEtC,SAAS,kCAAkC,CACzC,KAAc;IAEd,OAAO,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,UAAU,CAAC;AACtE,CAAC;AAED,MAAM,oBAAoB,GAAG;IAC3B,qBAAqB;IACrB,QAAQ;IACR,cAAc;IACd,kBAAkB;IAClB,uBAAuB;IACvB,oBAAoB;IACpB,wBAAwB;IACxB,6BAA6B;CAC+B,CAAC;AAE/D,SAAS,QAAQ,CAAC,KAAc;IAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QAChD,OAAO,EAAE,mBAA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IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,kCAAkC,CAC1C,GAAG,EACH,wCAAwC,CACzC,CAAC;IACJ,CAAC;IAED,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACxD,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,mCAAmC,CAAC,MAAM,EAAE,GAAG,EAAE,eAAe,CAAC,CAAC;IAC9E,CAAC;IACD,IAAI,cAAc,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,cAAc,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC;QACxE,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,EAAE;SACL,MAAM,CAAC,IAAI,CAAC;SACZ,GAAG,CAAC,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,EAAE,CAAC;SACnC,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,IAAI,CAAC,mBAAmB,EAAE,GAAG,CAAC,mBAAmB,CAAC,EACrD,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAC5B,CACF;SACA,GAAG,EAAE,CAAC;IACT,OAAO,EAAE,GAAG,MAAM,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,EAAE,CAAC;AACnD,CAAC","sourcesContent":["import { and, eq, or } from \"drizzle-orm\";\nimport {\n trustedUserIdentityPins,\n trustedUserIdentityPinTables,\n} from \"../sqlite/schema/trustedUserIdentityPinSchema\";\nimport { registerClientSQLiteCommitGuard } from \"../sqlite/sqliteCommitGuards\";\nimport {\n type ClientSQLiteDatabase,\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n} from \"../trustedUserIdentity/types\";\nimport {\n differingPinFields,\n type PinScope,\n type TrustedUserIdentityPin,\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinInputError,\n TrustedUserIdentityPinMismatchError,\n type TrustedUserIdentityPinProvenance,\n} from \"./identity/trustedUserIdentityPinModel\";\nimport { runTrustedUserIdentityPinTransaction } from \"./trustedUserIdentityPinTransaction\";\n\nexport type {\n TrustedUserIdentityPin,\n TrustedUserIdentityPinProvenance,\n} from \"./identity/trustedUserIdentityPinModel\";\n\nconst provenanceRank: Readonly<\n Record<TrustedUserIdentityPinProvenance, number>\n> = { observed: 0, link: 1, self: 2 };\n\nfunction isTrustedUserIdentityPinProvenance(\n value: unknown,\n): value is TrustedUserIdentityPinProvenance {\n return value === \"self\" || value === \"link\" || value === \"observed\";\n}\n\nconst requiredStringFields = [\n \"identityTrustDomain\",\n \"userId\",\n \"signingSuite\",\n \"signingPublicKey\",\n \"signingKeyFingerprint\",\n \"encapsulationSuite\",\n \"encapsulationPublicKey\",\n \"encapsulationKeyFingerprint\",\n] as const satisfies readonly (keyof TrustedUserIdentityPin)[];\n\nfunction pinScope(value: unknown): PinScope {\n if (typeof value !== \"object\" || value === null) {\n return { identityTrustDomain: \"<invalid>\", userId: \"<invalid>\" };\n }\n const identityTrustDomain = Reflect.get(value, \"identityTrustDomain\");\n const userId = Reflect.get(value, \"userId\");\n return {\n identityTrustDomain:\n typeof identityTrustDomain === \"string\"\n ? identityTrustDomain\n : \"<invalid>\",\n userId: typeof userId === \"string\" ? userId : \"<invalid>\",\n };\n}\n\nfunction validationFailure(value: unknown): string | null {\n if (typeof value !== \"object\" || value === null) {\n return \"row must be an object\";\n }\n const formatVersion = Reflect.get(value, \"formatVersion\");\n if (formatVersion !== TRUSTED_USER_IDENTITY_FORMAT_VERSION) {\n return `formatVersion must be ${TRUSTED_USER_IDENTITY_FORMAT_VERSION}`;\n }\n for (const field of requiredStringFields) {\n const fieldValue = Reflect.get(value, field);\n if (typeof fieldValue !== \"string\" || fieldValue.trim().length === 0) {\n return `${field} must be a non-empty string`;\n }\n }\n if (\n Reflect.get(value, \"signingSuite\") !== TRUSTED_USER_IDENTITY_SIGNING_SUITE\n ) {\n return `signingSuite must be ${TRUSTED_USER_IDENTITY_SIGNING_SUITE}`;\n }\n if (\n Reflect.get(value, \"encapsulationSuite\") !==\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE\n ) {\n return `encapsulationSuite must be ${TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE}`;\n }\n const firstSeenAt = Reflect.get(value, \"firstSeenAt\");\n if (\n typeof firstSeenAt !== \"string\" ||\n !Number.isFinite(Date.parse(firstSeenAt))\n ) {\n return \"firstSeenAt must be a valid timestamp\";\n }\n if (!isTrustedUserIdentityPinProvenance(Reflect.get(value, \"provenance\"))) {\n return \"provenance must be self, link, or observed\";\n }\n return null;\n}\n\nfunction validatedStringField(\n value: object,\n field: (typeof requiredStringFields)[number] | \"firstSeenAt\",\n): string {\n const fieldValue = Reflect.get(value, field);\n if (typeof fieldValue !== \"string\") {\n throw new TypeError(`Validated pin field ${field} is not a string`);\n }\n return fieldValue;\n}\n\nfunction validatedFormatVersion(value: object): number {\n const formatVersion = Reflect.get(value, \"formatVersion\");\n if (typeof formatVersion !== \"number\") {\n throw new TypeError(\"Validated pin formatVersion is not a number\");\n }\n return formatVersion;\n}\n\nfunction validatedProvenance(value: object): TrustedUserIdentityPinProvenance {\n const provenance = Reflect.get(value, \"provenance\");\n if (!isTrustedUserIdentityPinProvenance(provenance)) {\n throw new TypeError(\"Validated pin provenance is not a provenance\");\n }\n return provenance;\n}\n\nfunction assertCandidatePin(pin: TrustedUserIdentityPin): void {\n const failure = validationFailure(pin);\n if (failure) {\n throw new TrustedUserIdentityPinInputError(pinScope(pin), failure);\n }\n}\n\nexport function parseStoredPin(\n value: unknown,\n scope: PinScope,\n): TrustedUserIdentityPin {\n const failure = validationFailure(value);\n if (failure) {\n throw new TrustedUserIdentityPinCorruptError(scope, failure);\n }\n if (typeof value !== \"object\" || value === null) {\n throw new TrustedUserIdentityPinCorruptError(\n scope,\n \"row must be an object\",\n );\n }\n const pin: TrustedUserIdentityPin = {\n identityTrustDomain: validatedStringField(value, \"identityTrustDomain\"),\n userId: validatedStringField(value, \"userId\"),\n formatVersion: validatedFormatVersion(value),\n signingSuite: validatedStringField(value, \"signingSuite\"),\n signingPublicKey: validatedStringField(value, \"signingPublicKey\"),\n signingKeyFingerprint: validatedStringField(value, \"signingKeyFingerprint\"),\n encapsulationSuite: validatedStringField(value, \"encapsulationSuite\"),\n encapsulationPublicKey: validatedStringField(\n value,\n \"encapsulationPublicKey\",\n ),\n encapsulationKeyFingerprint: validatedStringField(\n value,\n \"encapsulationKeyFingerprint\",\n ),\n firstSeenAt: validatedStringField(value, \"firstSeenAt\"),\n provenance: validatedProvenance(value),\n };\n if (\n pin.identityTrustDomain !== scope.identityTrustDomain ||\n pin.userId !== scope.userId\n ) {\n throw new TrustedUserIdentityPinCorruptError(\n scope,\n \"primary-key scope does not match the requested pin\",\n );\n }\n return pin;\n}\n\nasync function selectStoredPin(\n db: ClientSQLiteDatabase | ClientSQLiteTransactionScope,\n scope: PinScope,\n): Promise<TrustedUserIdentityPin | null> {\n const rows = await db\n .select()\n .from(trustedUserIdentityPins)\n .where(\n and(\n eq(\n trustedUserIdentityPins.identityTrustDomain,\n scope.identityTrustDomain,\n ),\n eq(trustedUserIdentityPins.userId, scope.userId),\n ),\n )\n .limit(1);\n const row = rows[0];\n return row ? parseStoredPin(row, scope) : null;\n}\n\nexport async function loadTrustedUserIdentityPin(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<TrustedUserIdentityPin | null> {\n const scope: PinScope = {\n identityTrustDomain: input.identityTrustDomain,\n userId: input.userId,\n };\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n return selectStoredPin(\n getClientSQLitePersistenceRuntime(input.execSql).db,\n scope,\n );\n}\n\n/**\n * One read answers an exact repeat of a pin that alone holds its\n * key and ranks at or above the candidate; anything else returns null for the\n * write transaction. Pins are never deleted, keys never change, and\n * provenance only rises, so a match is what the transaction would return.\n */\nconst pins = trustedUserIdentityPins;\n\nasync function matchingPin(\n db: ClientSQLiteTransactionScope,\n pin: TrustedUserIdentityPin,\n): Promise<TrustedUserIdentityPin | null> {\n const [row, other] = await db\n .select()\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, pin.identityTrustDomain),\n or(\n eq(pins.userId, pin.userId),\n eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint),\n ),\n ),\n )\n .limit(2);\n if (other || row?.userId !== pin.userId || validationFailure(row))\n return null;\n const stored = parseStoredPin(row, pin);\n const rank = provenanceRank;\n if (differingPinFields(stored, pin).length > 0) return null;\n return rank[pin.provenance] <= rank[stored.provenance] ? stored : null;\n}\n\n/**\n * Atomically establishes or verifies a durable identity pin.\n *\n * The immediate transaction serializes first contact across SDK instances that\n * share the SQLite database. Conflict handling never replaces the existing\n * keys: the winning pin is re-read and every identity field is compared before\n * this function returns. When the keys match and the candidate's provenance\n * ranks higher (an identity link confirming an observed pin), only the\n * provenance is raised; it is never lowered.\n *\n * `assertCurrent` is the caller's lifetime check. It guards the write\n * transaction's COMMIT, so an operation whose account or database changed\n * while it awaited SQLite rolls its pin back instead of committing it.\n */\nexport async function compareOrInsertTrustedUserIdentityPin(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: ExecSql;\n readonly pin: TrustedUserIdentityPin;\n}): Promise<TrustedUserIdentityPin> {\n const [stored] = await compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n pins: [input.pin],\n });\n if (!stored)\n throw new TrustedUserIdentityPinCorruptError(input.pin, \"pin not stored\");\n return stored;\n}\n\n/**\n * Compare-or-insert a set of pins in one write transaction: a conflict on any\n * pin, or a failed `assertCurrent` at COMMIT, leaves none of them stored.\n */\nexport async function compareOrInsertTrustedUserIdentityPins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: ExecSql;\n readonly pins: readonly TrustedUserIdentityPin[];\n}): Promise<TrustedUserIdentityPin[]> {\n const { assertCurrent = () => {} } = input;\n for (const pin of input.pins) assertCandidatePin(pin);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n return runTrustedUserIdentityPinTransaction(async () => {\n await ensureSqlTables(input.execSql, trustedUserIdentityPinTables);\n // Like the write path's BEGIN, this read's BEGIN retries while any adapter\n // holds the connection's transaction, so it never sees uncommitted pins.\n const pinned = await runtime.transaction(async (tx) => {\n const matched: TrustedUserIdentityPin[] = [];\n for (const pin of input.pins) {\n const stored = await matchingPin(tx, pin);\n if (!stored) return null;\n matched.push(stored);\n }\n return matched;\n });\n if (pinned) return pinned;\n return runtime.transaction(\n async (tx) => {\n registerClientSQLiteCommitGuard(input.execSql, assertCurrent);\n const stored: TrustedUserIdentityPin[] = [];\n for (const pin of input.pins) stored.push(await writePin(tx, pin));\n return stored;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nasync function writePin(\n tx: ClientSQLiteTransactionScope,\n pin: TrustedUserIdentityPin,\n): Promise<TrustedUserIdentityPin> {\n const aliases = await tx\n .select()\n .from(pins)\n .where(\n and(\n eq(pins.identityTrustDomain, pin.identityTrustDomain),\n eq(pins.signingKeyFingerprint, pin.signingKeyFingerprint),\n ),\n )\n .limit(1);\n const alias = aliases[0];\n if (alias && alias.userId !== pin.userId) {\n throw new TrustedUserIdentityPinMismatchError(\n parseStoredPin(alias, {\n identityTrustDomain: pin.identityTrustDomain,\n userId: alias.userId,\n }),\n pin,\n [\"userId\"],\n );\n }\n // Targets the primary key only: re-pinning the same user is a no-op,\n // but a write that would bind this key to a second user must fail at\n // the unique index rather than be silently skipped.\n await tx\n .insert(pins)\n .values(pin)\n .onConflictDoNothing({\n target: [pins.identityTrustDomain, pins.userId],\n })\n .run();\n\n const stored = await selectStoredPin(tx, pin);\n if (!stored) {\n throw new TrustedUserIdentityPinCorruptError(\n pin,\n \"row is missing after compare-or-insert\",\n );\n }\n\n const differingFields = differingPinFields(stored, pin);\n if (differingFields.length > 0) {\n throw new TrustedUserIdentityPinMismatchError(stored, pin, differingFields);\n }\n if (provenanceRank[pin.provenance] <= provenanceRank[stored.provenance]) {\n return stored;\n }\n await tx\n .update(pins)\n .set({ provenance: pin.provenance })\n .where(\n and(\n eq(pins.identityTrustDomain, pin.identityTrustDomain),\n eq(pins.userId, pin.userId),\n ),\n )\n .run();\n return { ...stored, provenance: pin.provenance };\n}\n"]}