@tearleads/client-sdk 0.1.197 → 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.
- package/data/persistence/identity/trustedUserIdentityPinModel.d.ts +4 -0
- package/data/persistence/identity/trustedUserIdentityPinModel.js +113 -0
- package/data/persistence/identity/trustedUserIdentityPinModel.js.map +1 -1
- package/data/persistence/identity/trustedUserIdentityPinRepository.js +196 -0
- package/data/persistence/identity/trustedUserIdentityPinRepository.js.map +1 -0
- package/data/trustedUserIdentity/pinnedIdentity.d.ts +1 -1
- package/data/trustedUserIdentity/pinnedIdentity.js +2 -2
- package/data/trustedUserIdentity/pinnedIdentity.js.map +1 -1
- package/data/trustedUserIdentity/pinnedResolution.js +4 -5
- package/data/trustedUserIdentity/pinnedResolution.js.map +1 -1
- package/data/trustedUserIdentity/service.js +12 -13
- package/data/trustedUserIdentity/service.js.map +1 -1
- package/internal/loro/changeTimestamps.d.ts +26 -0
- package/internal/loro/changeTimestamps.js +29 -0
- package/internal/loro/changeTimestamps.js.map +1 -0
- package/internal/loro/document.js +2 -0
- package/internal/loro/document.js.map +1 -1
- package/internal/loro/index.d.ts +1 -0
- package/internal/loro/index.js +1 -0
- package/internal/loro/index.js.map +1 -1
- package/package.json +1 -1
- package/data/persistence/identity/trustedUserIdentityPinBatch.js +0 -36
- package/data/persistence/identity/trustedUserIdentityPinBatch.js.map +0 -1
- package/data/persistence/identity/trustedUserIdentitySigningKeyBinding.js +0 -18
- package/data/persistence/identity/trustedUserIdentitySigningKeyBinding.js.map +0 -1
- package/data/persistence/trustedUserIdentityPinPersistence.d.ts +0 -37
- package/data/persistence/trustedUserIdentityPinPersistence.js +0 -258
- package/data/persistence/trustedUserIdentityPinPersistence.js.map +0 -1
- /package/data/persistence/{trustedUserIdentityPinTransaction.js → identity/trustedUserIdentityPinTransaction.js} +0 -0
- /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,GAAG,CAAC,YAAY;QAC9B,qBAAqB,EAAE,GAAG,CAAC,qBAAqB;QAChD,kBAAkB,EAAE,GAAG,CAAC,kBAAkB;QAC1C,2BAA2B,EAAE,GAAG,CAAC,2BAA2B;Q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AM,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,kBAAkB;QAC1C,2BAA2B,EAAE,GAAG,CAAC,2BAA2B;QAC5D,WAAW,EAAE,GAAG,CAAC,WAAW;KAC7B,CAAC;AACJ,CAAC;AAED,MAAM,OAAO,mCAAoC,SAA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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,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C;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, 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 {
|
|
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 {
|
|
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;
|
|
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 {
|
|
3
|
-
import {
|
|
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,CAA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adTrustedUserIdentityPins } 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,0BAA0B,GAC3B,MAAM,cAAc,CAAC;AAyBtB,8EAA8E;AAC9E,SAAS,eAAe,CACtB,YAAoD;IAEpD,MAAM,mBAAmB,GAAG,YAAY,CAAC,mBAAmB,CAAC;IAC7D,IAAI,CAAC,mBAAmB;QACtB,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,qEAAqE,CACtE,CAAC;IACJ,MAAM,OAAO,GAAG,YAAY,CAAC,UAAU,EAAE,CAAC;IAC1C,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,wBAAwB,CAChC,sEAAsE,CACvE,CAAC;IACJ,MAAM,WAAW,GAAG,YAAY,CAAC,cAAc,EAAE,CAAC;IAClD,MAAM,UAAU,GAAG,YAAY,CAAC,kBAAkB,EAAE,EAAE,CAAC;IACvD,OAAO;QACL,OAAO;QACP,UAAU;QACV,mBAAmB;QACnB,WAAW;QACX,aAAa;YACX,IACE,YAAY,CAAC,UAAU,EAAE,KAAK,OAAO;gBACrC,YAAY,CAAC,cAAc,EAAE,KAAK,WAAW;gBAC7C,YAA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,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 {
|
|
5
|
-
import {
|
|
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
|
-
|
|
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);
|