@nodii/dsar 0.31.0 → 0.32.1
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/dist/bind-pattern-a.d.ts +54 -2
- package/dist/bind-pattern-a.d.ts.map +1 -1
- package/dist/bind-pattern-a.js +502 -100
- package/dist/bind-pattern-a.js.map +1 -1
- package/dist/generated/embedded-proto-source.d.ts +1 -1
- package/dist/generated/embedded-proto-source.d.ts.map +1 -1
- package/dist/generated/embedded-proto-source.js +1 -1
- package/dist/generated/embedded-proto-source.js.map +1 -1
- package/dist/generated/package-version.d.ts +1 -1
- package/dist/generated/package-version.js +1 -1
- package/dist/grpc/dsar-service.d.ts +15 -5
- package/dist/grpc/dsar-service.d.ts.map +1 -1
- package/dist/grpc/dsar-service.js +9 -3
- package/dist/grpc/dsar-service.js.map +1 -1
- package/dist/handler-status.d.ts +24 -0
- package/dist/handler-status.d.ts.map +1 -0
- package/dist/handler-status.js +37 -0
- package/dist/handler-status.js.map +1 -0
- package/dist/hold-failure-mode.d.ts +6 -0
- package/dist/hold-failure-mode.d.ts.map +1 -1
- package/dist/hold-failure-mode.js +31 -1
- package/dist/hold-failure-mode.js.map +1 -1
- package/dist/identity.d.ts +278 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +876 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +15 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15 -3
- package/dist/index.js.map +1 -1
- package/dist/migrations/index.d.ts +9 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/migrations/index.js +57 -0
- package/dist/migrations/index.js.map +1 -1
- package/dist/orchestrator.d.ts +11 -3
- package/dist/orchestrator.d.ts.map +1 -1
- package/dist/orchestrator.js +97 -20
- package/dist/orchestrator.js.map +1 -1
- package/dist/rectify.d.ts +87 -0
- package/dist/rectify.d.ts.map +1 -0
- package/dist/rectify.js +194 -0
- package/dist/rectify.js.map +1 -0
- package/dist/register.d.ts.map +1 -1
- package/dist/register.js +15 -2
- package/dist/register.js.map +1 -1
- package/dist/retention.d.ts.map +1 -1
- package/dist/retention.js +6 -2
- package/dist/retention.js.map +1 -1
- package/dist/s3-artifact.d.ts +30 -1
- package/dist/s3-artifact.d.ts.map +1 -1
- package/dist/s3-artifact.js +34 -0
- package/dist/s3-artifact.js.map +1 -1
- package/dist/types.d.ts +57 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +47 -1
- package/dist/types.js.map +1 -1
- package/package.json +3 -3
- package/proto/nodii/dsar/v1/dsar.proto +158 -9
- package/src/migrations/001-lifecycle-requests.sql +81 -2
- package/src/migrations/002-retention-schedules-own-table-checks.sql +56 -0
package/dist/identity.js
ADDED
|
@@ -0,0 +1,876 @@
|
|
|
1
|
+
// Subject identity for DSAR intake: MatchSubject, VerifySubjectFactors,
|
|
2
|
+
// SendSubjectCode (DSAR-FIX-4).
|
|
3
|
+
//
|
|
4
|
+
// Intake asks each participant two questions: "which of your subjects do these
|
|
5
|
+
// identifiers belong to?" and "do these typed details match that subject?". A
|
|
6
|
+
// participant answers with subject ids, per-factor results and a verdict, and
|
|
7
|
+
// NOTHING ELSE. The library keeps that promise for the participant:
|
|
8
|
+
//
|
|
9
|
+
// - The participant's `loadFactors` hands the HELD values to the library,
|
|
10
|
+
// which compares them here, so they never leave the process.
|
|
11
|
+
// - The one-time code is generated, hashed and checked here; only its hash
|
|
12
|
+
// is stored, and the participant's `sendCode` is the only place it goes.
|
|
13
|
+
// - No identifier, factor value, code or contact address is ever returned,
|
|
14
|
+
// logged, audited or put in an error. Every failure answers a fixed token.
|
|
15
|
+
// There are no audit rows or log lines for these three RPCs at all: intake
|
|
16
|
+
// records the verdict.
|
|
17
|
+
//
|
|
18
|
+
// Twins: python `nodii_dsar.identity`, go `identity.go`. Fixture:
|
|
19
|
+
// identity-parity/cases.json `score` + `compare`.
|
|
20
|
+
import { createHash, createHmac, randomInt, timingSafeEqual, } from "node:crypto";
|
|
21
|
+
import { subjectKindFromProto } from "./grpc/dsar-service.js";
|
|
22
|
+
import { isSubjectKind, UNKNOWN_SUBJECT_KIND_REASON } from "./subject-kinds.js";
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
// Vocabulary
|
|
25
|
+
// ---------------------------------------------------------------------------
|
|
26
|
+
/** The verification factors, in proto `FactorKind` order. Aadhaar is not one. */
|
|
27
|
+
export const FACTOR_KINDS = [
|
|
28
|
+
"date_of_birth",
|
|
29
|
+
"first_name",
|
|
30
|
+
"last_name",
|
|
31
|
+
"pan",
|
|
32
|
+
"onfile_code",
|
|
33
|
+
];
|
|
34
|
+
/** The identifier fields of the proto `SubjectIdentifiers`. */
|
|
35
|
+
export const SUBJECT_IDENTIFIER_KEYS = [
|
|
36
|
+
"employee_id",
|
|
37
|
+
"work_email",
|
|
38
|
+
"account_number",
|
|
39
|
+
"phone",
|
|
40
|
+
"email",
|
|
41
|
+
];
|
|
42
|
+
/** How many verify attempts one subject allows in a rolling hour. */
|
|
43
|
+
export const VERIFY_ATTEMPTS_PER_HOUR = 10;
|
|
44
|
+
/** How many codes one subject can be sent in a rolling hour. */
|
|
45
|
+
export const SEND_CODE_ATTEMPTS_PER_HOUR = 3;
|
|
46
|
+
/** A sent code is good for 15 minutes. */
|
|
47
|
+
export const SUBJECT_CODE_TTL_SECONDS = 15 * 60;
|
|
48
|
+
/** A code is dead after this many wrong tries. */
|
|
49
|
+
export const SUBJECT_CODE_MAX_ATTEMPTS = 5;
|
|
50
|
+
/** Reason tokens. Stable; a value never rides one. */
|
|
51
|
+
export const IDENTITY_REASONS = {
|
|
52
|
+
noIdentifiers: "no_identifiers",
|
|
53
|
+
matcherNotConfigured: "matcher_not_configured",
|
|
54
|
+
matchLookupFailed: "match_lookup_failed",
|
|
55
|
+
matcherAnswerInvalid: "matcher_answer_invalid",
|
|
56
|
+
noFactors: "no_factors",
|
|
57
|
+
rateLimited: "rate_limited",
|
|
58
|
+
factorLookupFailed: "factor_lookup_failed",
|
|
59
|
+
codeSenderNotConfigured: "code_sender_not_configured",
|
|
60
|
+
codeSendFailed: "code_send_failed",
|
|
61
|
+
codeSenderAnswerUnknown: "code_sender_answer_unknown",
|
|
62
|
+
/** The attempts or codes table could not be read or written. */
|
|
63
|
+
identityStoreUnavailable: "identity_store_unavailable",
|
|
64
|
+
/**
|
|
65
|
+
* The code was delivered but could not be activated (it expired during a
|
|
66
|
+
* slow delivery, or the store failed): it will never work, so the subject
|
|
67
|
+
* should not wait for it. Their earlier code, if any, still works.
|
|
68
|
+
*/
|
|
69
|
+
codeActivationFailed: "code_activation_failed",
|
|
70
|
+
/**
|
|
71
|
+
* The request named no tenant, a tenant that is not a UUID, or no subject:
|
|
72
|
+
* nothing is checked or sent.
|
|
73
|
+
*/
|
|
74
|
+
noSubject: "no_tenant_or_subject",
|
|
75
|
+
};
|
|
76
|
+
// The same tokens as single constants, named as in Python and Go.
|
|
77
|
+
export const NO_IDENTIFIERS_REASON = IDENTITY_REASONS.noIdentifiers;
|
|
78
|
+
export const MATCHER_NOT_CONFIGURED_REASON = IDENTITY_REASONS.matcherNotConfigured;
|
|
79
|
+
export const MATCH_LOOKUP_FAILED_REASON = IDENTITY_REASONS.matchLookupFailed;
|
|
80
|
+
export const MATCHER_ANSWER_INVALID_REASON = IDENTITY_REASONS.matcherAnswerInvalid;
|
|
81
|
+
export const NO_FACTORS_REASON = IDENTITY_REASONS.noFactors;
|
|
82
|
+
export const RATE_LIMITED_REASON = IDENTITY_REASONS.rateLimited;
|
|
83
|
+
export const FACTOR_LOOKUP_FAILED_REASON = IDENTITY_REASONS.factorLookupFailed;
|
|
84
|
+
export const CODE_SENDER_NOT_CONFIGURED_REASON = IDENTITY_REASONS.codeSenderNotConfigured;
|
|
85
|
+
export const CODE_SEND_FAILED_REASON = IDENTITY_REASONS.codeSendFailed;
|
|
86
|
+
export const CODE_SENDER_ANSWER_UNKNOWN_REASON = IDENTITY_REASONS.codeSenderAnswerUnknown;
|
|
87
|
+
export const IDENTITY_STORE_UNAVAILABLE_REASON = IDENTITY_REASONS.identityStoreUnavailable;
|
|
88
|
+
export const NO_SUBJECT_REASON = IDENTITY_REASONS.noSubject;
|
|
89
|
+
export const CODE_ACTIVATION_FAILED_REASON = IDENTITY_REASONS.codeActivationFailed;
|
|
90
|
+
// The vocabulary values, named as in Python and Go.
|
|
91
|
+
export const FACTOR_KIND_DATE_OF_BIRTH = "date_of_birth";
|
|
92
|
+
export const FACTOR_KIND_FIRST_NAME = "first_name";
|
|
93
|
+
export const FACTOR_KIND_LAST_NAME = "last_name";
|
|
94
|
+
export const FACTOR_KIND_PAN = "pan";
|
|
95
|
+
export const FACTOR_KIND_ONFILE_CODE = "onfile_code";
|
|
96
|
+
export const FACTOR_RESULT_MATCH = "match";
|
|
97
|
+
export const FACTOR_RESULT_NO_MATCH = "no_match";
|
|
98
|
+
export const FACTOR_RESULT_UNAVAILABLE = "unavailable";
|
|
99
|
+
export const FACTOR_RESULT_NOT_HELD = "not_held";
|
|
100
|
+
export const VERDICT_VERIFIED = "verified";
|
|
101
|
+
export const VERDICT_NEEDS_REVIEW = "needs_review";
|
|
102
|
+
export const VERDICT_INCONCLUSIVE = "inconclusive";
|
|
103
|
+
export const MATCH_OUTCOME_MATCHED = "MATCH_OUTCOME_MATCHED";
|
|
104
|
+
export const MATCH_OUTCOME_NO_MATCH = "MATCH_OUTCOME_NO_MATCH";
|
|
105
|
+
export const MATCH_OUTCOME_UNSUPPORTED = "MATCH_OUTCOME_UNSUPPORTED";
|
|
106
|
+
export const MATCH_OUTCOME_UNAVAILABLE = "MATCH_OUTCOME_UNAVAILABLE";
|
|
107
|
+
export const SEND_CODE_OUTCOME_SENT = "SEND_CODE_OUTCOME_SENT";
|
|
108
|
+
export const SEND_CODE_OUTCOME_NO_CONTACT_ON_FILE = "SEND_CODE_OUTCOME_NO_CONTACT_ON_FILE";
|
|
109
|
+
export const SEND_CODE_OUTCOME_UNSUPPORTED = "SEND_CODE_OUTCOME_UNSUPPORTED";
|
|
110
|
+
export const SEND_CODE_OUTCOME_UNAVAILABLE = "SEND_CODE_OUTCOME_UNAVAILABLE";
|
|
111
|
+
/** The two identity tables (fixed names; only these get services-only RLS). */
|
|
112
|
+
export const DEFAULT_IDENTITY_ATTEMPTS_TABLE = "dsar_identity_attempts";
|
|
113
|
+
export const DEFAULT_SUBJECT_CODES_TABLE = "dsar_subject_codes";
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
// Pure functions (parity-fixtured)
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
const PAN_RE = /^[A-Z]{5}[0-9]{4}[A-Z]$/;
|
|
118
|
+
/** An id made only of phone characters (digits, space, + - ( ) .). */
|
|
119
|
+
const PHONE_SHAPED = /^[0-9 +().-]+$/;
|
|
120
|
+
const DATE_RE = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
|
|
121
|
+
/**
|
|
122
|
+
* One explicit whitespace class, the same in every port (a language's own
|
|
123
|
+
* `\s` differs: JS counts U+FEFF, Go and Python count U+0085).
|
|
124
|
+
*/
|
|
125
|
+
const IDENTITY_WS =
|
|
126
|
+
// eslint-disable-next-line no-control-regex -- U+001C..U+001F are whitespace in Python and Go; matching them keeps the ports identical
|
|
127
|
+
/[\t\n\v\f\r \x1c-\x1f\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/g;
|
|
128
|
+
/** A tenant id: a lower-case UUID (tenant ids are lower-cased on the way in). */
|
|
129
|
+
const TENANT_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
130
|
+
/** {@link IDENTITY_WS} at either end of a string. */
|
|
131
|
+
const IDENTITY_WS_EDGES =
|
|
132
|
+
// eslint-disable-next-line no-control-regex -- the same class as IDENTITY_WS
|
|
133
|
+
/^[\t\n\v\f\r \x1c-\x1f\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+|[\t\n\v\f\r \x1c-\x1f\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+$/g;
|
|
134
|
+
/**
|
|
135
|
+
* Trim {@link IDENTITY_WS} from both ends only, the same in every port. The
|
|
136
|
+
* inside of the string is untouched: `emp\u00a0001` and `emp 001` stay two
|
|
137
|
+
* different ids.
|
|
138
|
+
*/
|
|
139
|
+
export function wsTrim(s) {
|
|
140
|
+
return s.replace(IDENTITY_WS_EDGES, "");
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* NFKC, collapse whitespace runs to one space, trim, lower-case, then fold
|
|
144
|
+
* the two lower-casing differences between ports: final sigma to sigma, and
|
|
145
|
+
* `i` + U+0307 (JS and Python lower-case U+0130 to it, Go to `i`) to `i`.
|
|
146
|
+
*/
|
|
147
|
+
function normaliseName(s) {
|
|
148
|
+
return s
|
|
149
|
+
.normalize("NFKC")
|
|
150
|
+
.replace(IDENTITY_WS, " ")
|
|
151
|
+
.replace(/^ +| +$/g, "")
|
|
152
|
+
.toLowerCase()
|
|
153
|
+
.replace(/\u03c2/g, "\u03c3")
|
|
154
|
+
.replace(/i\u0307/g, "i");
|
|
155
|
+
}
|
|
156
|
+
function normalisePan(s) {
|
|
157
|
+
const v = s.normalize("NFKC").replace(IDENTITY_WS, "").toUpperCase();
|
|
158
|
+
return PAN_RE.test(v) ? v : null;
|
|
159
|
+
}
|
|
160
|
+
/** `s` if it is a YYYY-MM-DD that names a real calendar date, else null. */
|
|
161
|
+
function calendarDate(s) {
|
|
162
|
+
const m = DATE_RE.exec(s);
|
|
163
|
+
if (!m)
|
|
164
|
+
return null;
|
|
165
|
+
const y = Number(m[1]);
|
|
166
|
+
const mo = Number(m[2]);
|
|
167
|
+
const d = Number(m[3]);
|
|
168
|
+
if (mo < 1 || mo > 12 || d < 1)
|
|
169
|
+
return null;
|
|
170
|
+
const leap = (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
|
|
171
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
172
|
+
return d <= days[mo - 1] ? s : null;
|
|
173
|
+
}
|
|
174
|
+
function digestEqual(a, b) {
|
|
175
|
+
const da = createHash("sha256").update(a, "utf8").digest();
|
|
176
|
+
const db = createHash("sha256").update(b, "utf8").digest();
|
|
177
|
+
return timingSafeEqual(da, db);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Compare one typed factor with the held value. The values are normalised,
|
|
181
|
+
* then their SHA-256 digests are compared in constant time.
|
|
182
|
+
*
|
|
183
|
+
* - held absent or blank → `not_held`.
|
|
184
|
+
* - names: NFKC, trim, whitespace runs to one space, lower case.
|
|
185
|
+
* - PAN: NFKC, all whitespace removed, upper case, must be AAAAA9999A
|
|
186
|
+
* (a malformed value never matches).
|
|
187
|
+
* - date of birth: typed must be a real YYYY-MM-DD; held is compared by its
|
|
188
|
+
* first 10 characters, which must be one too.
|
|
189
|
+
*/
|
|
190
|
+
/**
|
|
191
|
+
* The calendar day a Date stands for. node-postgres decodes a `date` column
|
|
192
|
+
* to LOCAL midnight, porsager/postgres to UTC midnight: a Date exactly on
|
|
193
|
+
* local midnight is its local day, any other its UTC day, so both drivers
|
|
194
|
+
* give the right day in every timezone. An invalid Date is not held.
|
|
195
|
+
*/
|
|
196
|
+
function calendarDayOf(d) {
|
|
197
|
+
if (Number.isNaN(d.getTime()))
|
|
198
|
+
return null;
|
|
199
|
+
const localMidnight = d.getHours() === 0 &&
|
|
200
|
+
d.getMinutes() === 0 &&
|
|
201
|
+
d.getSeconds() === 0 &&
|
|
202
|
+
d.getMilliseconds() === 0;
|
|
203
|
+
if (!localMidnight)
|
|
204
|
+
return d.toISOString().slice(0, 10);
|
|
205
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
206
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
207
|
+
}
|
|
208
|
+
export function compareFactor(kind, heldValue, typed) {
|
|
209
|
+
// A Postgres `date` column decodes to a Date, as Python's driver decodes
|
|
210
|
+
// it to a date: compare it by its calendar day.
|
|
211
|
+
const held = heldValue instanceof Date ? calendarDayOf(heldValue) : heldValue;
|
|
212
|
+
if (typeof held !== "string" || wsTrim(held) === "")
|
|
213
|
+
return "not_held";
|
|
214
|
+
const t = typeof typed === "string" ? typed : "";
|
|
215
|
+
let a;
|
|
216
|
+
let b;
|
|
217
|
+
switch (kind) {
|
|
218
|
+
case "first_name":
|
|
219
|
+
case "last_name":
|
|
220
|
+
a = normaliseName(held);
|
|
221
|
+
b = normaliseName(t);
|
|
222
|
+
// Empty once normalised (e.g. only U+FEFF): nothing held, nothing typed.
|
|
223
|
+
if (a === "")
|
|
224
|
+
return "not_held";
|
|
225
|
+
if (b === "")
|
|
226
|
+
return "no_match";
|
|
227
|
+
break;
|
|
228
|
+
case "pan":
|
|
229
|
+
a = normalisePan(held);
|
|
230
|
+
b = normalisePan(t);
|
|
231
|
+
// A held PAN of the wrong shape is the service's data fault: the check
|
|
232
|
+
// could not run, which is not the requester's mismatch.
|
|
233
|
+
if (a === null)
|
|
234
|
+
return "unavailable";
|
|
235
|
+
break;
|
|
236
|
+
case "date_of_birth":
|
|
237
|
+
a = calendarDate(wsTrim(held).slice(0, 10));
|
|
238
|
+
b = calendarDate(wsTrim(t));
|
|
239
|
+
// A held date that is not a real YYYY-MM-DD: the check could not run.
|
|
240
|
+
if (a === null)
|
|
241
|
+
return "unavailable";
|
|
242
|
+
break;
|
|
243
|
+
case "onfile_code":
|
|
244
|
+
a = wsTrim(held);
|
|
245
|
+
b = wsTrim(t);
|
|
246
|
+
break;
|
|
247
|
+
default:
|
|
248
|
+
return "no_match";
|
|
249
|
+
}
|
|
250
|
+
if (a === null || b === null || b === "")
|
|
251
|
+
return "no_match";
|
|
252
|
+
return digestEqual(a, b) ? "match" : "no_match";
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Score the per-factor results (operator ruling 6).
|
|
256
|
+
*
|
|
257
|
+
* Any `no_match` → needs_review. Otherwise a strong match (PAN or the on-file
|
|
258
|
+
* code) or two weak ones (date of birth, and first + last name together) →
|
|
259
|
+
* verified. One weak match, or only one of first/last name → needs_review.
|
|
260
|
+
* Nothing matched → inconclusive. `unavailable` and `not_held` count for
|
|
261
|
+
* nothing either way.
|
|
262
|
+
*/
|
|
263
|
+
export function scoreFactorChecks(checks) {
|
|
264
|
+
if (checks.some((c) => c.result === "no_match"))
|
|
265
|
+
return "needs_review";
|
|
266
|
+
const matched = new Set(checks.filter((c) => c.result === "match").map((c) => c.kind));
|
|
267
|
+
const strong = matched.has("pan") || matched.has("onfile_code");
|
|
268
|
+
const first = matched.has("first_name");
|
|
269
|
+
const last = matched.has("last_name");
|
|
270
|
+
const weak = (matched.has("date_of_birth") ? 1 : 0) + (first && last ? 1 : 0);
|
|
271
|
+
if (strong || weak >= 2)
|
|
272
|
+
return "verified";
|
|
273
|
+
if (weak === 1 || first !== last)
|
|
274
|
+
return "needs_review";
|
|
275
|
+
return "inconclusive";
|
|
276
|
+
}
|
|
277
|
+
/** The shortest `codeHashKey` accepted (characters). */
|
|
278
|
+
export const CODE_HASH_KEY_MIN_LENGTH = 32;
|
|
279
|
+
/**
|
|
280
|
+
* The stored hash of a one-time code: hex HMAC-SHA256, under the service's
|
|
281
|
+
* secret `codeHashKey`, of `tenant_id \n subject_kind \n subject_id \n code`.
|
|
282
|
+
* Only this is stored. The key is what keeps a 6-digit code from falling to an
|
|
283
|
+
* offline search by anyone who can read the table (an owner session, a backup
|
|
284
|
+
* or a replica).
|
|
285
|
+
*/
|
|
286
|
+
export function subjectCodeHash(key, tenantId, subjectKind, subjectId, code) {
|
|
287
|
+
return createHmac("sha256", key)
|
|
288
|
+
.update(`${tenantId}\n${subjectKind}\n${subjectId}\n${code}`, "utf8")
|
|
289
|
+
.digest("hex");
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* `identity.loadFactors` or `identity.sendCode` is wired on a client that can
|
|
293
|
+
* open its own transaction, without `identity.trustRequestTenant` set either
|
|
294
|
+
* way.
|
|
295
|
+
*/
|
|
296
|
+
export class MissingTenantTrustError extends Error {
|
|
297
|
+
code = "MISSING_TENANT_TRUST";
|
|
298
|
+
constructor() {
|
|
299
|
+
super("MISSING_TENANT_TRUST: the identity RPCs run in the library's own transaction on a fresh connection. Set identity.trustRequestTenant: true to scope it to the request's tenant (only when the gRPC auth layer restricts these RPCs to tenant's orchestrator), or false when your client is the owner or already bound to the tenant.");
|
|
300
|
+
this.name = "MissingTenantTrustError";
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* `identity.loadFactors` or `identity.sendCode` is wired on a client without
|
|
305
|
+
* `begin`, and `identity.callerOwnsTransaction` is not set.
|
|
306
|
+
*/
|
|
307
|
+
export class MissingTransactionRunnerError extends Error {
|
|
308
|
+
code = "MISSING_TRANSACTION_RUNNER";
|
|
309
|
+
constructor() {
|
|
310
|
+
super("MISSING_TRANSACTION_RUNNER: the identity RPCs serialise each subject's rate limit and code activation with a transaction-scoped lock. Pass a client with begin (porsager sql), or set identity.callerOwnsTransaction: true when every request already runs inside your own transaction.");
|
|
311
|
+
this.name = "MissingTransactionRunnerError";
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/** `identity.sendCode` is wired without a usable `identity.codeHashKey`. */
|
|
315
|
+
export class MissingCodeHashKeyError extends Error {
|
|
316
|
+
code = "MISSING_CODE_HASH_KEY";
|
|
317
|
+
constructor() {
|
|
318
|
+
super(`MISSING_CODE_HASH_KEY: identity.sendCode needs identity.codeHashKey, a secret of at least ${CODE_HASH_KEY_MIN_LENGTH} characters from the service's secret store. The one-time code is stored only as an HMAC under it.`);
|
|
319
|
+
this.name = "MissingCodeHashKeyError";
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function factorKindName(kind) {
|
|
323
|
+
return `FACTOR_KIND_${kind.toUpperCase()}`;
|
|
324
|
+
}
|
|
325
|
+
function factorResultName(result) {
|
|
326
|
+
return `FACTOR_RESULT_${result.toUpperCase()}`;
|
|
327
|
+
}
|
|
328
|
+
function verdictName(verdict) {
|
|
329
|
+
return `VERDICT_${verdict.toUpperCase()}`;
|
|
330
|
+
}
|
|
331
|
+
/** The given (non-blank) typed factors, in `FactorKind` order. */
|
|
332
|
+
function givenFactors(raw) {
|
|
333
|
+
const obj = raw !== null && typeof raw === "object"
|
|
334
|
+
? raw
|
|
335
|
+
: {};
|
|
336
|
+
const out = [];
|
|
337
|
+
for (const kind of FACTOR_KINDS) {
|
|
338
|
+
const v = obj[kind];
|
|
339
|
+
if (typeof v === "string" && wsTrim(v) !== "")
|
|
340
|
+
out.push({ kind, typed: v });
|
|
341
|
+
}
|
|
342
|
+
return out;
|
|
343
|
+
}
|
|
344
|
+
/** The given identifiers, trimmed, blanks dropped. */
|
|
345
|
+
function givenIdentifiers(raw) {
|
|
346
|
+
const obj = raw !== null && typeof raw === "object"
|
|
347
|
+
? raw
|
|
348
|
+
: {};
|
|
349
|
+
const out = {};
|
|
350
|
+
for (const key of SUBJECT_IDENTIFIER_KEYS) {
|
|
351
|
+
const v = obj[key];
|
|
352
|
+
if (typeof v === "string" && wsTrim(v) !== "")
|
|
353
|
+
out[key] = wsTrim(v);
|
|
354
|
+
}
|
|
355
|
+
return out;
|
|
356
|
+
}
|
|
357
|
+
/** The subject kind of a request, or null when it is not a known kind. */
|
|
358
|
+
function decodeKind(raw) {
|
|
359
|
+
const decoded = subjectKindFromProto(raw);
|
|
360
|
+
return isSubjectKind(decoded) ? decoded : null;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Build the three identity RPCs. Used by `bindPatternA`; exported so a
|
|
364
|
+
* participant with its own binder can serve them the same way.
|
|
365
|
+
*/
|
|
366
|
+
export function bindIdentityRpcs(opts) {
|
|
367
|
+
// Fixed names: only these two tables get the migrations' services-only RLS
|
|
368
|
+
// (no `authenticated`), which keeps code hashes and limits away from a
|
|
369
|
+
// tenant user session.
|
|
370
|
+
const attempts = DEFAULT_IDENTITY_ATTEMPTS_TABLE;
|
|
371
|
+
const codes = DEFAULT_SUBJECT_CODES_TABLE;
|
|
372
|
+
const sql = opts.sqlClient;
|
|
373
|
+
const identity = opts.identity ?? {};
|
|
374
|
+
const codeHashKey = identity.codeHashKey ?? "";
|
|
375
|
+
if (typeof identity.sendCode === "function" &&
|
|
376
|
+
(typeof codeHashKey !== "string" ||
|
|
377
|
+
codeHashKey.length < CODE_HASH_KEY_MIN_LENGTH)) {
|
|
378
|
+
throw new MissingCodeHashKeyError();
|
|
379
|
+
}
|
|
380
|
+
// The library's own transaction takes a fresh pooled connection: say at
|
|
381
|
+
// bind whose tenant it carries, so a nodii_services pool cannot fail every
|
|
382
|
+
// request at runtime instead (LIBS-96).
|
|
383
|
+
if ((typeof identity.loadFactors === "function" ||
|
|
384
|
+
typeof identity.sendCode === "function") &&
|
|
385
|
+
typeof sql.begin === "function" &&
|
|
386
|
+
typeof identity.trustRequestTenant !== "boolean") {
|
|
387
|
+
throw new MissingTenantTrustError();
|
|
388
|
+
}
|
|
389
|
+
// Without `begin`, the per-subject lock only serialises inside the
|
|
390
|
+
// caller's own transaction: refuse an autocommit client unless the caller
|
|
391
|
+
// says each request already runs in one.
|
|
392
|
+
if ((typeof identity.loadFactors === "function" ||
|
|
393
|
+
typeof identity.sendCode === "function") &&
|
|
394
|
+
typeof sql.begin !== "function" &&
|
|
395
|
+
identity.callerOwnsTransaction !== true) {
|
|
396
|
+
throw new MissingTransactionRunnerError();
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Inside a transaction the library opened: set `app.tenant_id` (local to
|
|
400
|
+
* it) to the request's tenant, run `fn`, and put the previous value back
|
|
401
|
+
* before the commit. A GUC set with is_local survives a RELEASE SAVEPOINT,
|
|
402
|
+
* so when `begin` only nests (a savepoint inside the caller's transaction)
|
|
403
|
+
* the caller's tenant is still the one in force afterwards. A throw rolls
|
|
404
|
+
* back, which undoes the change on its own. An unset setting comes back as
|
|
405
|
+
* '' (Postgres has no "unset" for a custom setting once one is assigned);
|
|
406
|
+
* the platform's `auth.get_tenant_id()`, which every policy reads, treats
|
|
407
|
+
* '' as no tenant (`nullif(..., '')`).
|
|
408
|
+
*/
|
|
409
|
+
const withTenant = async (tx, tenantId, fn) => {
|
|
410
|
+
// Without the opt-in the transaction keeps the client's own tenant
|
|
411
|
+
// context (LIBS-96): the request's tenant is not authenticated here.
|
|
412
|
+
if (identity.trustRequestTenant !== true)
|
|
413
|
+
return fn();
|
|
414
|
+
const before = (await tx.unsafe(`SELECT coalesce(current_setting('app.tenant_id', true), '') AS t`));
|
|
415
|
+
await tx.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [tenantId]);
|
|
416
|
+
const result = await fn();
|
|
417
|
+
await tx.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [
|
|
418
|
+
before[0]?.t ?? "",
|
|
419
|
+
]);
|
|
420
|
+
return result;
|
|
421
|
+
};
|
|
422
|
+
/**
|
|
423
|
+
* The rolling-hour rate limit for one action. With a transaction runner:
|
|
424
|
+
* under a per-subject advisory lock, count the subject's attempts in the
|
|
425
|
+
* last hour; at `limit` refuse (false), else record one (true), so exactly
|
|
426
|
+
* `limit` concurrent calls are admitted. Without one: record the attempt
|
|
427
|
+
* FIRST, then count including it, and delete it and refuse when over, so
|
|
428
|
+
* concurrent calls can never all be admitted past the limit (a burst may
|
|
429
|
+
* refuse a few more). Rows older than a day are dropped on the way. Throws
|
|
430
|
+
* only on a database error.
|
|
431
|
+
*/
|
|
432
|
+
const takeAttempt = async (tenantId, kind, subjectId, action, limit) => {
|
|
433
|
+
if (typeof sql.begin === "function") {
|
|
434
|
+
return sql.begin(async (tx) => withTenant(tx, tenantId, async () => {
|
|
435
|
+
// The library opened this transaction, so it carries the tenant
|
|
436
|
+
// itself: the RLS policies read app.tenant_id (local to the tx, put
|
|
437
|
+
// back before the commit).
|
|
438
|
+
// One subject's attempts are counted one at a time.
|
|
439
|
+
await tx.unsafe(`SELECT pg_advisory_xact_lock(hashtext($1))`, [
|
|
440
|
+
`${attempts}\n${tenantId}\n${kind}\n${subjectId}`,
|
|
441
|
+
]);
|
|
442
|
+
const counted = (await tx.unsafe(`SELECT count(*)::int AS n FROM ${attempts}
|
|
443
|
+
WHERE tenant_id = $1 AND subject_kind = $2 AND subject_id = $3
|
|
444
|
+
AND action = $4 AND attempted_at > now() - interval '1 hour'`, [tenantId, kind, subjectId, action]));
|
|
445
|
+
if (Number(counted[0]?.n ?? 0) >= limit)
|
|
446
|
+
return false;
|
|
447
|
+
await tx.unsafe(`DELETE FROM ${attempts}
|
|
448
|
+
WHERE tenant_id = $1 AND subject_kind = $2 AND subject_id = $3
|
|
449
|
+
AND attempted_at < now() - interval '1 day'`, [tenantId, kind, subjectId]);
|
|
450
|
+
await tx.unsafe(`INSERT INTO ${attempts} (tenant_id, subject_kind, subject_id, action)
|
|
451
|
+
VALUES ($1, $2, $3, $4)`, [tenantId, kind, subjectId, action]);
|
|
452
|
+
return true;
|
|
453
|
+
}));
|
|
454
|
+
}
|
|
455
|
+
// No transaction runner: these statements run on the caller's own client,
|
|
456
|
+
// which carries the caller's tenant context, the same contract as
|
|
457
|
+
// lifecycle_requests. Only the transaction above is the library's to scope.
|
|
458
|
+
// The per-subject lock is taken here too: when that client is an open
|
|
459
|
+
// transaction (a caller's tx or savepoint) it holds to the tx's end, so
|
|
460
|
+
// concurrent transactions are counted one at a time; in autocommit it
|
|
461
|
+
// ends with its statement and insert-then-count bounds the burst.
|
|
462
|
+
await sql.unsafe(`SELECT pg_advisory_xact_lock(hashtext($1))`, [
|
|
463
|
+
`${attempts}\n${tenantId}\n${kind}\n${subjectId}`,
|
|
464
|
+
]);
|
|
465
|
+
await sql.unsafe(`DELETE FROM ${attempts}
|
|
466
|
+
WHERE tenant_id = $1 AND subject_kind = $2 AND subject_id = $3
|
|
467
|
+
AND attempted_at < now() - interval '1 day'`, [tenantId, kind, subjectId]);
|
|
468
|
+
const inserted = (await sql.unsafe(`INSERT INTO ${attempts} (tenant_id, subject_kind, subject_id, action)
|
|
469
|
+
VALUES ($1, $2, $3, $4) RETURNING id::text AS id`, [tenantId, kind, subjectId, action]));
|
|
470
|
+
const rows = (await sql.unsafe(`SELECT count(*)::int AS n FROM ${attempts}
|
|
471
|
+
WHERE tenant_id = $1 AND subject_kind = $2 AND subject_id = $3
|
|
472
|
+
AND action = $4 AND attempted_at > now() - interval '1 hour'`, [tenantId, kind, subjectId, action]));
|
|
473
|
+
if (Number(rows[0]?.n ?? 0) <= limit)
|
|
474
|
+
return true;
|
|
475
|
+
await sql.unsafe(`DELETE FROM ${attempts} WHERE id = $1::uuid`, [
|
|
476
|
+
inserted[0]?.id,
|
|
477
|
+
]);
|
|
478
|
+
return false;
|
|
479
|
+
};
|
|
480
|
+
/**
|
|
481
|
+
* Run `fn` scoped to the request's tenant: with a transaction runner, in a
|
|
482
|
+
* transaction that sets `app.tenant_id` (local to it), which the RLS
|
|
483
|
+
* policies read; without one, on the caller's own client and its tenant
|
|
484
|
+
* context, the same contract as lifecycle_requests.
|
|
485
|
+
*/
|
|
486
|
+
const scoped = async (tenantId, fn) => {
|
|
487
|
+
if (typeof sql.begin === "function") {
|
|
488
|
+
return sql.begin(async (tx) => withTenant(tx, tenantId, () => fn(tx)));
|
|
489
|
+
}
|
|
490
|
+
return fn(sql);
|
|
491
|
+
};
|
|
492
|
+
const consumeCode = async (tenantId, id) => {
|
|
493
|
+
await scoped(tenantId, (q) => q.unsafe(`UPDATE ${codes} SET consumed_at = now()
|
|
494
|
+
WHERE id = $1 AND consumed_at IS NULL`, [id]));
|
|
495
|
+
};
|
|
496
|
+
/** Check a typed on-file code against the newest live code for the subject. */
|
|
497
|
+
const checkCode = async (tenantId, kind, subjectId, typed) => {
|
|
498
|
+
return scoped(tenantId, async (q) => {
|
|
499
|
+
// Spend one guess atomically on the NEWEST live code only: concurrent
|
|
500
|
+
// guesses cannot get past the cap, and an exhausted newest code never
|
|
501
|
+
// falls back to an older one that a concurrent send left live.
|
|
502
|
+
const rows = (await q.unsafe(`UPDATE ${codes} SET attempts = attempts + 1
|
|
503
|
+
WHERE id = (SELECT id FROM ${codes}
|
|
504
|
+
WHERE tenant_id = $1 AND subject_kind = $2 AND subject_id = $3
|
|
505
|
+
AND consumed_at IS NULL AND expires_at > now()
|
|
506
|
+
ORDER BY created_at DESC LIMIT 1)
|
|
507
|
+
AND consumed_at IS NULL AND expires_at > now() AND attempts < $4
|
|
508
|
+
RETURNING id::text AS id, code_hash`, [tenantId, kind, subjectId, SUBJECT_CODE_MAX_ATTEMPTS]));
|
|
509
|
+
const row = rows[0];
|
|
510
|
+
// No live code to compare (never sent, expired, used, or out of guesses):
|
|
511
|
+
// nothing is held, which is not a mismatch.
|
|
512
|
+
if (!row)
|
|
513
|
+
return "not_held";
|
|
514
|
+
const want = Buffer.from(String(row.code_hash), "utf8");
|
|
515
|
+
const got = Buffer.from(subjectCodeHash(codeHashKey, tenantId, kind, subjectId, wsTrim(typed)), "utf8");
|
|
516
|
+
if (want.length === got.length && timingSafeEqual(want, got)) {
|
|
517
|
+
const used = (await q.unsafe(`UPDATE ${codes} SET consumed_at = now()
|
|
518
|
+
WHERE id = $1 AND consumed_at IS NULL RETURNING 1 AS used`, [row.id]));
|
|
519
|
+
// Another request consumed it first: a code works once.
|
|
520
|
+
// Another request used it first: no live code was left to compare,
|
|
521
|
+
// which is not the requester's mismatch.
|
|
522
|
+
return Array.isArray(used) && used.length === 1 ? "match" : "not_held";
|
|
523
|
+
}
|
|
524
|
+
return "no_match";
|
|
525
|
+
});
|
|
526
|
+
};
|
|
527
|
+
const MatchSubject = async (request) => {
|
|
528
|
+
const requestId = String(request.request_id ?? "");
|
|
529
|
+
const answer = (outcome, reason, subjectIds = []) => ({
|
|
530
|
+
request_id: requestId,
|
|
531
|
+
outcome,
|
|
532
|
+
subject_ids: subjectIds,
|
|
533
|
+
reason,
|
|
534
|
+
});
|
|
535
|
+
const kind = decodeKind(request.subject_kind);
|
|
536
|
+
if (kind === null) {
|
|
537
|
+
return answer("MATCH_OUTCOME_UNSUPPORTED", UNKNOWN_SUBJECT_KIND_REASON);
|
|
538
|
+
}
|
|
539
|
+
const identifiers = givenIdentifiers(request.identifiers);
|
|
540
|
+
const values = Object.values(identifiers);
|
|
541
|
+
if (values.length === 0) {
|
|
542
|
+
return answer("MATCH_OUTCOME_NO_MATCH", IDENTITY_REASONS.noIdentifiers);
|
|
543
|
+
}
|
|
544
|
+
const matchTenantId = wsTrim(String(request.tenant_id ?? "")).toLowerCase();
|
|
545
|
+
if (!TENANT_UUID_RE.test(matchTenantId)) {
|
|
546
|
+
return answer("MATCH_OUTCOME_UNAVAILABLE", IDENTITY_REASONS.noSubject);
|
|
547
|
+
}
|
|
548
|
+
if (typeof identity.match !== "function") {
|
|
549
|
+
return answer("MATCH_OUTCOME_UNSUPPORTED", IDENTITY_REASONS.matcherNotConfigured);
|
|
550
|
+
}
|
|
551
|
+
let ids;
|
|
552
|
+
try {
|
|
553
|
+
ids = await identity.match({
|
|
554
|
+
tenant_id: matchTenantId,
|
|
555
|
+
subject_kind: kind,
|
|
556
|
+
identifiers,
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
return answer("MATCH_OUTCOME_UNAVAILABLE", IDENTITY_REASONS.matchLookupFailed);
|
|
561
|
+
}
|
|
562
|
+
if (!Array.isArray(ids) || ids.some((id) => typeof id !== "string")) {
|
|
563
|
+
return answer("MATCH_OUTCOME_UNAVAILABLE", IDENTITY_REASONS.matcherAnswerInvalid);
|
|
564
|
+
}
|
|
565
|
+
// A matcher that hands back a CONTACT identifier it was given (an email, a
|
|
566
|
+
// phone number) instead of an id would put that value on the wire. An
|
|
567
|
+
// employee id or account number may well BE the subject id, so it is not
|
|
568
|
+
// refused.
|
|
569
|
+
// Compared in a normal form, so a reformatted echo (another phone layout,
|
|
570
|
+
// full-width letters) is still caught: emails after NFKC + lower case,
|
|
571
|
+
// phones by their digits (one ending with the other, 7+ digits).
|
|
572
|
+
const emails = ["email", "work_email"]
|
|
573
|
+
.map((k) => identifiers[k])
|
|
574
|
+
.filter((v) => typeof v === "string" && v !== "")
|
|
575
|
+
.map((v) => v.normalize("NFKC").toLowerCase());
|
|
576
|
+
const digitsOf = (v) => v.normalize("NFKC").replace(/[^0-9]/g, "");
|
|
577
|
+
const phoneDigits = typeof identifiers.phone === "string" ? digitsOf(identifiers.phone) : "";
|
|
578
|
+
const echoes = (id) => {
|
|
579
|
+
if (emails.includes(id.normalize("NFKC").toLowerCase()))
|
|
580
|
+
return true;
|
|
581
|
+
// Only an id made of phone characters can echo the phone: an account
|
|
582
|
+
// number such as "ACC-0002345678" is an id, whatever its digits end in.
|
|
583
|
+
if (!PHONE_SHAPED.test(id.normalize("NFKC")))
|
|
584
|
+
return false;
|
|
585
|
+
const d = digitsOf(id);
|
|
586
|
+
return (phoneDigits.length >= 7 &&
|
|
587
|
+
d.length >= 7 &&
|
|
588
|
+
(phoneDigits.endsWith(d) || d.endsWith(phoneDigits)));
|
|
589
|
+
};
|
|
590
|
+
const trimmed = ids.map((id) => wsTrim(id));
|
|
591
|
+
if (trimmed.some(echoes)) {
|
|
592
|
+
return answer("MATCH_OUTCOME_UNAVAILABLE", IDENTITY_REASONS.matcherAnswerInvalid);
|
|
593
|
+
}
|
|
594
|
+
const unique = [...new Set(trimmed.filter((id) => id !== ""))];
|
|
595
|
+
if (unique.length === 0)
|
|
596
|
+
return answer("MATCH_OUTCOME_NO_MATCH", "");
|
|
597
|
+
return answer("MATCH_OUTCOME_MATCHED", "", unique);
|
|
598
|
+
};
|
|
599
|
+
const VerifySubjectFactors = async (request) => {
|
|
600
|
+
const requestId = String(request.request_id ?? "");
|
|
601
|
+
const given = givenFactors(request.factors);
|
|
602
|
+
const answer = (checks, reason, verdict = scoreFactorChecks(checks)) => ({
|
|
603
|
+
request_id: requestId,
|
|
604
|
+
verdict: verdictName(verdict),
|
|
605
|
+
checks: checks.map((c) => ({
|
|
606
|
+
kind: factorKindName(c.kind),
|
|
607
|
+
result: factorResultName(c.result),
|
|
608
|
+
})),
|
|
609
|
+
reason,
|
|
610
|
+
});
|
|
611
|
+
const allUnavailable = (reason) => answer(given.map((g) => ({ kind: g.kind, result: "unavailable" })), reason, "inconclusive");
|
|
612
|
+
const kind = decodeKind(request.subject_kind);
|
|
613
|
+
if (kind === null) {
|
|
614
|
+
return answer([], UNKNOWN_SUBJECT_KIND_REASON, "inconclusive");
|
|
615
|
+
}
|
|
616
|
+
if (given.length === 0) {
|
|
617
|
+
return answer([], IDENTITY_REASONS.noFactors, "inconclusive");
|
|
618
|
+
}
|
|
619
|
+
// Trimmed once, so whitespace variants of one subject share one rate
|
|
620
|
+
// limit and reach the hooks in one form.
|
|
621
|
+
// A tenant id is a UUID: one spelling for the code hash and the lock.
|
|
622
|
+
const tenantId = wsTrim(String(request.tenant_id ?? "")).toLowerCase();
|
|
623
|
+
const subjectId = wsTrim(String(request.subject_id ?? ""));
|
|
624
|
+
if (!TENANT_UUID_RE.test(tenantId) || subjectId === "") {
|
|
625
|
+
return answer([], IDENTITY_REASONS.noSubject, "inconclusive");
|
|
626
|
+
}
|
|
627
|
+
// Nothing given can be checked (no loadFactors for the plain factors, no
|
|
628
|
+
// sendCode for the on-file code): every factor is not held, and no
|
|
629
|
+
// attempt is spent on a request that could check nothing.
|
|
630
|
+
const checkable = given.some((g) => g.kind === "onfile_code"
|
|
631
|
+
? typeof identity.sendCode === "function"
|
|
632
|
+
: typeof identity.loadFactors === "function");
|
|
633
|
+
if (!checkable) {
|
|
634
|
+
return answer(given.map((g) => ({ kind: g.kind, result: "not_held" })), "");
|
|
635
|
+
}
|
|
636
|
+
try {
|
|
637
|
+
const allowed = await takeAttempt(tenantId, kind, subjectId, "verify", VERIFY_ATTEMPTS_PER_HOUR);
|
|
638
|
+
if (!allowed)
|
|
639
|
+
return allUnavailable(IDENTITY_REASONS.rateLimited);
|
|
640
|
+
}
|
|
641
|
+
catch {
|
|
642
|
+
return allUnavailable(IDENTITY_REASONS.identityStoreUnavailable);
|
|
643
|
+
}
|
|
644
|
+
const results = new Map();
|
|
645
|
+
let reason = "";
|
|
646
|
+
const plain = given.filter((g) => g.kind !== "onfile_code");
|
|
647
|
+
if (plain.length > 0) {
|
|
648
|
+
if (typeof identity.loadFactors !== "function") {
|
|
649
|
+
for (const g of plain)
|
|
650
|
+
results.set(g.kind, "not_held");
|
|
651
|
+
}
|
|
652
|
+
else {
|
|
653
|
+
let held = null;
|
|
654
|
+
try {
|
|
655
|
+
const got = await identity.loadFactors({
|
|
656
|
+
tenant_id: tenantId,
|
|
657
|
+
subject_kind: kind,
|
|
658
|
+
subject_id: subjectId,
|
|
659
|
+
kinds: plain.map((g) => g.kind),
|
|
660
|
+
});
|
|
661
|
+
// null / undefined holds nothing (every kind not held), as a nil map
|
|
662
|
+
// in Go and None in Python. A plain object or a Map (its string
|
|
663
|
+
// keys) is the answer, as any Mapping is in Python; a throw or any
|
|
664
|
+
// other answer is a lookup failure.
|
|
665
|
+
if (got === null || got === undefined) {
|
|
666
|
+
held = {};
|
|
667
|
+
}
|
|
668
|
+
else if (got instanceof Map) {
|
|
669
|
+
held = Object.fromEntries([...got].filter(([k]) => typeof k === "string"));
|
|
670
|
+
}
|
|
671
|
+
else if (typeof got === "object") {
|
|
672
|
+
const proto = Object.getPrototypeOf(got);
|
|
673
|
+
if (proto === Object.prototype || proto === null) {
|
|
674
|
+
held = got;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
catch {
|
|
679
|
+
held = null;
|
|
680
|
+
}
|
|
681
|
+
if (held === null) {
|
|
682
|
+
for (const g of plain)
|
|
683
|
+
results.set(g.kind, "unavailable");
|
|
684
|
+
reason = IDENTITY_REASONS.factorLookupFailed;
|
|
685
|
+
}
|
|
686
|
+
else {
|
|
687
|
+
for (const g of plain) {
|
|
688
|
+
results.set(g.kind, compareFactor(g.kind, held[g.kind], g.typed));
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
const code = given.find((g) => g.kind === "onfile_code");
|
|
694
|
+
if (code) {
|
|
695
|
+
if (typeof identity.sendCode !== "function") {
|
|
696
|
+
results.set("onfile_code", "not_held");
|
|
697
|
+
}
|
|
698
|
+
else {
|
|
699
|
+
try {
|
|
700
|
+
results.set("onfile_code", await checkCode(tenantId, kind, subjectId, code.typed));
|
|
701
|
+
}
|
|
702
|
+
catch {
|
|
703
|
+
results.set("onfile_code", "unavailable");
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
const checks = given.map((g) => ({
|
|
708
|
+
kind: g.kind,
|
|
709
|
+
result: results.get(g.kind) ?? "unavailable",
|
|
710
|
+
}));
|
|
711
|
+
return answer(checks, reason);
|
|
712
|
+
};
|
|
713
|
+
const SendSubjectCode = async (request) => {
|
|
714
|
+
const requestId = String(request.request_id ?? "");
|
|
715
|
+
const answer = (outcome, reason) => ({ request_id: requestId, outcome, reason });
|
|
716
|
+
const kind = decodeKind(request.subject_kind);
|
|
717
|
+
if (kind === null) {
|
|
718
|
+
return answer("SEND_CODE_OUTCOME_UNSUPPORTED", UNKNOWN_SUBJECT_KIND_REASON);
|
|
719
|
+
}
|
|
720
|
+
const sendCode = identity.sendCode;
|
|
721
|
+
if (typeof sendCode !== "function") {
|
|
722
|
+
return answer("SEND_CODE_OUTCOME_UNSUPPORTED", IDENTITY_REASONS.codeSenderNotConfigured);
|
|
723
|
+
}
|
|
724
|
+
// Trimmed once, so whitespace variants of one subject share one rate
|
|
725
|
+
// limit and reach the hooks in one form.
|
|
726
|
+
// A tenant id is a UUID: one spelling for the code hash and the lock.
|
|
727
|
+
const tenantId = wsTrim(String(request.tenant_id ?? "")).toLowerCase();
|
|
728
|
+
const subjectId = wsTrim(String(request.subject_id ?? ""));
|
|
729
|
+
if (!TENANT_UUID_RE.test(tenantId) || subjectId === "") {
|
|
730
|
+
return answer("SEND_CODE_OUTCOME_UNAVAILABLE", IDENTITY_REASONS.noSubject);
|
|
731
|
+
}
|
|
732
|
+
let rowId;
|
|
733
|
+
const code = String(randomInt(0, 1_000_000)).padStart(6, "0");
|
|
734
|
+
const expiresAt = new Date(Date.now() + SUBJECT_CODE_TTL_SECONDS * 1000).toISOString();
|
|
735
|
+
try {
|
|
736
|
+
const allowed = await takeAttempt(tenantId, kind, subjectId, "send_code", SEND_CODE_ATTEMPTS_PER_HOUR);
|
|
737
|
+
if (!allowed) {
|
|
738
|
+
return answer("SEND_CODE_OUTCOME_UNAVAILABLE", IDENTITY_REASONS.rateLimited);
|
|
739
|
+
}
|
|
740
|
+
// Store the new code INACTIVE (consumed_at set), so no guess can reach
|
|
741
|
+
// it before it is delivered; it is activated below once sent. Codes
|
|
742
|
+
// that expired over a day ago are pruned in the same statement.
|
|
743
|
+
const rows = (await scoped(tenantId, (q) => q.unsafe(`WITH pruned AS (
|
|
744
|
+
DELETE FROM ${codes}
|
|
745
|
+
WHERE tenant_id = $1 AND subject_kind = $2 AND subject_id = $3
|
|
746
|
+
AND expires_at < now() - interval '1 day'
|
|
747
|
+
)
|
|
748
|
+
INSERT INTO ${codes}
|
|
749
|
+
(tenant_id, subject_kind, subject_id, request_id, code_hash, expires_at,
|
|
750
|
+
consumed_at)
|
|
751
|
+
VALUES ($1, $2, $3, $4, $5, $6::timestamptz, now())
|
|
752
|
+
RETURNING id::text AS id`, [
|
|
753
|
+
tenantId,
|
|
754
|
+
kind,
|
|
755
|
+
subjectId,
|
|
756
|
+
requestId,
|
|
757
|
+
subjectCodeHash(codeHashKey, tenantId, kind, subjectId, code),
|
|
758
|
+
expiresAt,
|
|
759
|
+
])));
|
|
760
|
+
const id = rows[0]?.id;
|
|
761
|
+
if (typeof id !== "string")
|
|
762
|
+
throw new Error("no code row");
|
|
763
|
+
rowId = id;
|
|
764
|
+
}
|
|
765
|
+
catch {
|
|
766
|
+
return answer("SEND_CODE_OUTCOME_UNAVAILABLE", IDENTITY_REASONS.identityStoreUnavailable);
|
|
767
|
+
}
|
|
768
|
+
const retire = async () => {
|
|
769
|
+
try {
|
|
770
|
+
await consumeCode(tenantId, rowId);
|
|
771
|
+
}
|
|
772
|
+
catch {
|
|
773
|
+
// The answer is already a refusal; a code that could not be retired
|
|
774
|
+
// still expires in 15 minutes.
|
|
775
|
+
}
|
|
776
|
+
};
|
|
777
|
+
let sent;
|
|
778
|
+
try {
|
|
779
|
+
sent = await sendCode({
|
|
780
|
+
tenant_id: tenantId,
|
|
781
|
+
subject_kind: kind,
|
|
782
|
+
subject_id: subjectId,
|
|
783
|
+
code,
|
|
784
|
+
expires_at: expiresAt,
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
catch {
|
|
788
|
+
await retire();
|
|
789
|
+
return answer("SEND_CODE_OUTCOME_UNAVAILABLE", IDENTITY_REASONS.codeSendFailed);
|
|
790
|
+
}
|
|
791
|
+
if (sent === "sent") {
|
|
792
|
+
// Delivered: activate the new code and retire every OTHER live one, in
|
|
793
|
+
// one statement, so the code delivered last is the one that works.
|
|
794
|
+
try {
|
|
795
|
+
await scoped(tenantId, async (q) => {
|
|
796
|
+
// One activation per subject at a time, so each sees the last one
|
|
797
|
+
// and the code delivered last is the one left live. This holds in
|
|
798
|
+
// the library's own transaction (a client with `begin`); on the
|
|
799
|
+
// caller's client each statement autocommits and the lock ends with
|
|
800
|
+
// it, so two racing deliveries may both stay live. A guess only ever
|
|
801
|
+
// targets the newest live code and never falls back to an older
|
|
802
|
+
// one, so the guess budget is not doubled; the older code is dead.
|
|
803
|
+
await q.unsafe(`SELECT pg_advisory_xact_lock(hashtext($1))`, [
|
|
804
|
+
`${codes}\n${tenantId}\n${kind}\n${subjectId}`,
|
|
805
|
+
]);
|
|
806
|
+
const rows = (await q.unsafe(`WITH activated AS (
|
|
807
|
+
UPDATE ${codes} SET consumed_at = NULL
|
|
808
|
+
WHERE id = $4::uuid AND expires_at > now() RETURNING id
|
|
809
|
+
), retired AS (
|
|
810
|
+
UPDATE ${codes} SET consumed_at = now()
|
|
811
|
+
WHERE tenant_id = $1 AND subject_kind = $2 AND subject_id = $3
|
|
812
|
+
AND consumed_at IS NULL AND id <> $4::uuid
|
|
813
|
+
AND EXISTS (SELECT 1 FROM activated)
|
|
814
|
+
RETURNING id
|
|
815
|
+
)
|
|
816
|
+
SELECT count(*)::int AS n FROM activated`, [tenantId, kind, subjectId, rowId]));
|
|
817
|
+
// The new row not activated (not visible, e.g. a wrong tenant
|
|
818
|
+
// context): the delivered code cannot work, so this is no "sent".
|
|
819
|
+
if (Number(rows[0]?.n ?? 0) !== 1) {
|
|
820
|
+
throw new Error("code not activated");
|
|
821
|
+
}
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
catch {
|
|
825
|
+
// The code went out but cannot be activated: it will never work, so
|
|
826
|
+
// say so distinctly; the subject's earlier code (if any) still works.
|
|
827
|
+
return answer("SEND_CODE_OUTCOME_UNAVAILABLE", IDENTITY_REASONS.codeActivationFailed);
|
|
828
|
+
}
|
|
829
|
+
return answer("SEND_CODE_OUTCOME_SENT", "");
|
|
830
|
+
}
|
|
831
|
+
await retire();
|
|
832
|
+
if (sent === "no_contact_on_file") {
|
|
833
|
+
return answer("SEND_CODE_OUTCOME_NO_CONTACT_ON_FILE", "");
|
|
834
|
+
}
|
|
835
|
+
return answer("SEND_CODE_OUTCOME_UNAVAILABLE", IDENTITY_REASONS.codeSenderAnswerUnknown);
|
|
836
|
+
};
|
|
837
|
+
return { MatchSubject, VerifySubjectFactors, SendSubjectCode };
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* The identity RPCs of a participant that holds no subjects (Pattern B/C):
|
|
841
|
+
* match and send are unsupported, and every given factor is not held.
|
|
842
|
+
*/
|
|
843
|
+
export function noDataIdentityImpl(reason) {
|
|
844
|
+
return {
|
|
845
|
+
MatchSubject: async (request) => ({
|
|
846
|
+
request_id: String(request.request_id ?? ""),
|
|
847
|
+
outcome: "MATCH_OUTCOME_UNSUPPORTED",
|
|
848
|
+
subject_ids: [],
|
|
849
|
+
reason: decodeKind(request.subject_kind) === null
|
|
850
|
+
? UNKNOWN_SUBJECT_KIND_REASON
|
|
851
|
+
: reason,
|
|
852
|
+
}),
|
|
853
|
+
VerifySubjectFactors: async (request) => {
|
|
854
|
+
const known = decodeKind(request.subject_kind) !== null;
|
|
855
|
+
return {
|
|
856
|
+
request_id: String(request.request_id ?? ""),
|
|
857
|
+
verdict: "VERDICT_INCONCLUSIVE",
|
|
858
|
+
checks: known
|
|
859
|
+
? givenFactors(request.factors).map((g) => ({
|
|
860
|
+
kind: factorKindName(g.kind),
|
|
861
|
+
result: "FACTOR_RESULT_NOT_HELD",
|
|
862
|
+
}))
|
|
863
|
+
: [],
|
|
864
|
+
reason: known ? reason : UNKNOWN_SUBJECT_KIND_REASON,
|
|
865
|
+
};
|
|
866
|
+
},
|
|
867
|
+
SendSubjectCode: async (request) => ({
|
|
868
|
+
request_id: String(request.request_id ?? ""),
|
|
869
|
+
outcome: "SEND_CODE_OUTCOME_UNSUPPORTED",
|
|
870
|
+
reason: decodeKind(request.subject_kind) === null
|
|
871
|
+
? UNKNOWN_SUBJECT_KIND_REASON
|
|
872
|
+
: reason,
|
|
873
|
+
}),
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
//# sourceMappingURL=identity.js.map
|