@astratra/security 1.10.0 → 1.11.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.
@@ -0,0 +1,390 @@
1
+ /**
2
+ * Signing back in with the phone's own lock — Face ID, a fingerprint, the
3
+ * device code — instead of the password, on a device that already signed in.
4
+ *
5
+ * WHY A ROTATED SECRET AND NOT A KEY PAIR. A key pair only helps if the
6
+ * private key stays inside the phone's secure chip and signs only after the
7
+ * biometric check — which needs a native module. In JavaScript the private key
8
+ * would sit in the same keystore as a secret, and be stolen the same way. A
9
+ * secret rotated on every use gives something a pair does not: a copied
10
+ * secret that is replayed SHOWS, because one of the two uses presents a
11
+ * fingerprint that was already spent.
12
+ *
13
+ * The guarantees, each one a rule below:
14
+ *
15
+ * - the server keeps an HMAC fingerprint only (server-side pepper): a copy of
16
+ * the database signs nobody in;
17
+ * - a device is enrolled from a COMPLETE session only — second factor
18
+ * included when the account requires it;
19
+ * - each exchange spends the secret ATOMICALLY (safe across a cluster, no
20
+ * in-process state) and hands back a new one;
21
+ * - a spent secret coming back kills the device and — through `onReplay` —
22
+ * every session of the account: we cannot tell which of the two holders is
23
+ * the owner, so both lose;
24
+ * - the device is bound to the credential in force at enrolment: a password
25
+ * changed by ANY path, even one written later that forgets to revoke,
26
+ * switches it off;
27
+ * - it dies after `idleTtlMs` without use, on revocation, on removal;
28
+ * - attempts per device are bounded;
29
+ * - every failure is the SAME error, so a prober learns nothing.
30
+ */
31
+
32
+ const crypto = require('crypto');
33
+
34
+ const DEFAULT_IDLE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
35
+ const DEFAULT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
36
+ const DEFAULT_MAX_DEVICES = 5;
37
+ /* Enough to recognise the replay of a secret stolen weeks ago, without the row
38
+ growing on every sign-in. */
39
+ const DEFAULT_KEPT_FINGERPRINTS = 30;
40
+ const DEFAULT_MAX_ATTEMPTS = 10;
41
+ const DEFAULT_ATTEMPT_WINDOW_MS = 15 * 60 * 1000;
42
+
43
+ const DEVICE_ID_PATTERN = /^[a-f0-9]{32}$/;
44
+ const SECRET_PATTERN = /^[a-f0-9]{64}$/;
45
+ const PLATFORMS = ['ios', 'android', 'web'];
46
+
47
+ class TrustedDeviceError extends Error {
48
+ /**
49
+ * @param {'TRUSTED_DEVICE_REJECTED'|'TRUSTED_DEVICE_THROTTLED'|'SECOND_FACTOR_REQUIRED'} code
50
+ */
51
+ constructor(code, extra = {}) {
52
+ super(code);
53
+ this.name = 'TrustedDeviceError';
54
+ this.code = code;
55
+ this.statusCode = code === 'TRUSTED_DEVICE_THROTTLED' ? 429 : code === 'SECOND_FACTOR_REQUIRED' ? 403 : 401;
56
+ Object.assign(this, extra);
57
+ }
58
+ }
59
+
60
+ const rejected = () => new TrustedDeviceError('TRUSTED_DEVICE_REJECTED');
61
+
62
+ function sameText(a, b) {
63
+ const left = Buffer.from(String(a || ''), 'utf8');
64
+ const right = Buffer.from(String(b || ''), 'utf8');
65
+ return left.length === right.length && crypto.timingSafeEqual(left, right);
66
+ }
67
+
68
+ /* Shown back to the owner in a list and in an alert: no control characters,
69
+ no markup, bounded. */
70
+ const cleanName = (value) => [...String(value ?? '')]
71
+ .filter((char) => char.charCodeAt(0) > 0x1f && char.charCodeAt(0) !== 0x7f && char !== '<' && char !== '>')
72
+ .join('').trim().slice(0, 80);
73
+ const cleanPlatform = (value) => (PLATFORMS.includes(value) ? value : 'other');
74
+
75
+ /**
76
+ * In-memory store. Dev and tests only.
77
+ *
78
+ * `consume` is the one method that must be atomic in a real store: it swaps
79
+ * the current fingerprint ONLY if it is still the expected one. With MongoDB:
80
+ * updateOne({ _id, secretHash: expected, revokedAt: null }, { $set, $push:
81
+ * { previousHashes: { $each: [expected], $slice: -kept } } }) and
82
+ * `modifiedCount === 1`.
83
+ */
84
+ function createMemoryTrustedDeviceStore() {
85
+ const rows = new Map();
86
+ const copy = (row) => (row ? { ...row, previousHashes: [...row.previousHashes] } : null);
87
+ return {
88
+ async create(record) {
89
+ rows.set(record.id, { ...record, previousHashes: [] });
90
+ return copy(rows.get(record.id));
91
+ },
92
+ async findByDeviceId(deviceId) {
93
+ for (const row of rows.values()) if (row.deviceId === deviceId) return copy(row);
94
+ return null;
95
+ },
96
+ async consume(id, expectedHash, next) {
97
+ const row = rows.get(id);
98
+ if (!row || row.revokedAt || row.secretHash !== expectedHash) return false;
99
+ row.previousHashes = [...row.previousHashes, expectedHash].slice(-next.keep);
100
+ row.secretHash = next.secretHash;
101
+ row.lastUsedAt = next.lastUsedAt;
102
+ row.expiresAt = next.expiresAt;
103
+ return true;
104
+ },
105
+ async revoke(filter, reason, at, keepUntil) {
106
+ let count = 0;
107
+ for (const row of rows.values()) {
108
+ if (row.revokedAt) continue;
109
+ if (filter.id !== undefined && ![].concat(filter.id).includes(row.id)) continue;
110
+ if (filter.accountId !== undefined && row.accountId !== filter.accountId) continue;
111
+ if (filter.deviceId !== undefined && row.deviceId !== filter.deviceId) continue;
112
+ if (filter.secretHash !== undefined && row.secretHash !== filter.secretHash) continue;
113
+ row.revokedAt = at;
114
+ row.revokedReason = reason;
115
+ row.expiresAt = keepUntil;
116
+ count += 1;
117
+ }
118
+ return count;
119
+ },
120
+ async listActive(accountId) {
121
+ return [...rows.values()].filter((row) => row.accountId === accountId && !row.revokedAt).map(copy);
122
+ },
123
+ async all() {
124
+ return [...rows.values()].map(copy);
125
+ }
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Fixed-window attempt counter. Memory version for tests and single-process
131
+ * dev; in a cluster, back it with Redis (INCR + PEXPIRE) so four processes do
132
+ * not grant four times the attempts.
133
+ */
134
+ function createMemoryAttemptCounter() {
135
+ const windows = new Map();
136
+ return {
137
+ async hit(key, windowMs, at) {
138
+ const current = windows.get(key);
139
+ if (!current || current.resetAt <= at) {
140
+ windows.set(key, { count: 1, resetAt: at + windowMs });
141
+ return { count: 1, resetAt: at + windowMs };
142
+ }
143
+ current.count += 1;
144
+ return { ...current };
145
+ }
146
+ };
147
+ }
148
+
149
+ /**
150
+ * @param {object} options
151
+ * @param {object} options.store createMemoryTrustedDeviceStore() or yours.
152
+ * @param {string} options.pepper server-side HMAC key, dedicated, >= 32 chars.
153
+ * @param {object} [options.attempts] hit(key, windowMs, at) — default in memory.
154
+ * @param {number} [options.maxAttempts=10] exchanges per device per window.
155
+ * @param {number} [options.attemptWindowMs=15 min]
156
+ * @param {number} [options.idleTtlMs=30 days]
157
+ * @param {number} [options.maxDevices=5]
158
+ * @param {number} [options.keptFingerprints=30]
159
+ * @param {number} [options.retentionAfterRevokeMs=30 days] revoked rows are
160
+ * kept that long — a replay of their old secret is then still recognised.
161
+ * @param {(event: {accountId: string, id: string, at: number}) => Promise<void>} [options.onReplay]
162
+ * Revoke every session of the account and alert. Awaited; a failure is
163
+ * reported through onError and does not un-revoke the device.
164
+ * @param {(error: Error) => void} [options.onError]
165
+ * @param {() => number} [options.now]
166
+ */
167
+ function createTrustedDeviceService(options = {}) {
168
+ const store = options.store;
169
+ for (const method of ['create', 'findByDeviceId', 'consume', 'revoke', 'listActive']) {
170
+ if (!store || typeof store[method] !== 'function') throw new Error(`createTrustedDeviceService requires store.${method}.`);
171
+ }
172
+ const pepper = options.pepper;
173
+ if (typeof pepper !== 'string' || pepper.length < 32) {
174
+ throw new Error('createTrustedDeviceService requires options.pepper (at least 32 characters).');
175
+ }
176
+ const attempts = options.attempts || createMemoryAttemptCounter();
177
+ const maxAttempts = options.maxAttempts || DEFAULT_MAX_ATTEMPTS;
178
+ const attemptWindowMs = options.attemptWindowMs || DEFAULT_ATTEMPT_WINDOW_MS;
179
+ const idleTtlMs = options.idleTtlMs || DEFAULT_IDLE_TTL_MS;
180
+ const maxDevices = options.maxDevices || DEFAULT_MAX_DEVICES;
181
+ const keep = options.keptFingerprints || DEFAULT_KEPT_FINGERPRINTS;
182
+ const retentionMs = options.retentionAfterRevokeMs || DEFAULT_RETENTION_MS;
183
+ const onReplay = options.onReplay || (async () => {});
184
+ const onError = options.onError || (() => {});
185
+ const now = options.now || Date.now;
186
+
187
+ /* Two domains under one pepper: a secret's fingerprint can never be
188
+ confused with a credential stamp. */
189
+ const fingerprint = (secret) => crypto.createHmac('sha256', pepper).update(`device:${secret}`).digest('hex');
190
+ const credentialBinding = (stamp) => crypto.createHmac('sha256', pepper).update(`credential:${String(stamp ?? '')}`).digest('hex');
191
+
192
+ const revoke = (filter, reason, at = now()) => store.revoke(filter, reason, at, at + retentionMs);
193
+
194
+ /**
195
+ * Enrol THIS device for the signed-in account.
196
+ *
197
+ * @param {object} input
198
+ * @param {string} input.accountId
199
+ * @param {string} input.credentialStamp something that changes whenever the
200
+ * password changes — the stored password HASH is the natural choice.
201
+ * @param {boolean} [input.requireSecondFactor] the account's policy.
202
+ * @param {boolean} [input.secondFactorVerified] what THIS session proved.
203
+ * @param {string} [input.deviceName]
204
+ * @param {string} [input.platform] ios | android | web
205
+ * @returns {Promise<{id: string, deviceId: string, secret: string, expiresAt: number}>}
206
+ * Hand deviceId + secret to the device ONCE; they are never shown again.
207
+ */
208
+ async function enroll(input = {}) {
209
+ const accountId = String(input.accountId || '');
210
+ if (!accountId) throw new Error('enroll requires accountId.');
211
+ if (input.credentialStamp === undefined || input.credentialStamp === null || input.credentialStamp === '') {
212
+ throw new Error('enroll requires credentialStamp.');
213
+ }
214
+ /* A door that lasts a month is not opened by a half-finished session,
215
+ even if a middleware upstream is supposed to have refused it already. */
216
+ if (input.requireSecondFactor && input.secondFactorVerified !== true) {
217
+ throw new TrustedDeviceError('SECOND_FACTOR_REQUIRED');
218
+ }
219
+
220
+ const at = now();
221
+ const deviceId = crypto.randomBytes(16).toString('hex');
222
+ const secret = crypto.randomBytes(32).toString('hex');
223
+ const record = {
224
+ id: crypto.randomUUID(),
225
+ accountId,
226
+ deviceId,
227
+ secretHash: fingerprint(secret),
228
+ secondFactorVerified: input.secondFactorVerified === true,
229
+ credentialBinding: credentialBinding(input.credentialStamp),
230
+ deviceName: cleanName(input.deviceName),
231
+ platform: cleanPlatform(input.platform),
232
+ createdAt: at,
233
+ lastUsedAt: at,
234
+ expiresAt: at + idleTtlMs,
235
+ revokedAt: null,
236
+ revokedReason: null
237
+ };
238
+ await store.create(record);
239
+
240
+ /* Bounded: a stolen session cannot seed devices without limit. The least
241
+ recently used leaves first. */
242
+ const active = (await store.listActive(accountId)).sort((a, b) => b.lastUsedAt - a.lastUsedAt);
243
+ const excess = active.slice(maxDevices).map((row) => row.id);
244
+ if (excess.length) await revoke({ id: excess }, 'limit', at);
245
+
246
+ return { id: record.id, deviceId, secret, expiresAt: record.expiresAt };
247
+ }
248
+
249
+ /**
250
+ * Trade the device's secret for a new one. On success, issue the session
251
+ * yourself — with the same checks as a password sign-in (suspended account,
252
+ * pending deletion…) — and, if you refuse it, call revoke(result.id,
253
+ * 'session-refused').
254
+ *
255
+ * @param {{deviceId: string, secret: string}} proof
256
+ * @param {object} context
257
+ * @param {(accountId: string) => Promise<{credentialStamp: *, disabled?: boolean}|null>} context.loadAccount
258
+ * @returns {Promise<{id: string, accountId: string, deviceId: string, secret: string,
259
+ * secondFactorVerified: boolean, expiresAt: number}>}
260
+ * @throws {TrustedDeviceError} REJECTED for every failure, THROTTLED past the limit.
261
+ */
262
+ async function exchange(proof = {}, { loadAccount } = {}) {
263
+ if (typeof loadAccount !== 'function') throw new Error('exchange requires context.loadAccount.');
264
+ const { deviceId, secret } = proof || {};
265
+ if (typeof deviceId !== 'string' || typeof secret !== 'string'
266
+ || !DEVICE_ID_PATTERN.test(deviceId) || !SECRET_PATTERN.test(secret)) throw rejected();
267
+
268
+ const at = now();
269
+ /* Counted BEFORE any lookup, success or not: the secret is 256 bits, the
270
+ bound is there so a script cannot hammer one device to trigger
271
+ revocations or flood the audit log. */
272
+ const hit = await attempts.hit(`trusted-device:${deviceId}`, attemptWindowMs, at);
273
+ if (hit.count > maxAttempts) {
274
+ throw new TrustedDeviceError('TRUSTED_DEVICE_THROTTLED', { retryAfterMs: Math.max(0, hit.resetAt - at) });
275
+ }
276
+
277
+ const device = await store.findByDeviceId(deviceId);
278
+ if (!device) throw rejected();
279
+
280
+ const presented = fingerprint(secret);
281
+ const current = sameText(presented, device.secretHash);
282
+ const spent = !current && (device.previousHashes || []).some((hash) => sameText(hash, presented));
283
+
284
+ if (device.revokedAt || !(device.expiresAt > at)) throw rejected();
285
+
286
+ if (spent) {
287
+ await replayDetected(device, at);
288
+ throw rejected();
289
+ }
290
+ if (!current) throw rejected();
291
+
292
+ const account = await loadAccount(device.accountId);
293
+ if (!account || account.disabled || !sameText(device.credentialBinding, credentialBinding(account.credentialStamp))) {
294
+ await revoke({ id: device.id }, account ? 'account-changed' : 'account-missing', at);
295
+ throw rejected();
296
+ }
297
+
298
+ /* Spend the secret ONCE, before anything is issued. Two simultaneous
299
+ exchanges of the same secret: one wins, the other is a replay. */
300
+ const nextSecret = crypto.randomBytes(32).toString('hex');
301
+ const won = await store.consume(device.id, device.secretHash, {
302
+ secretHash: fingerprint(nextSecret),
303
+ lastUsedAt: at,
304
+ expiresAt: at + idleTtlMs,
305
+ keep
306
+ });
307
+ if (!won) {
308
+ await replayDetected(device, at);
309
+ throw rejected();
310
+ }
311
+
312
+ return {
313
+ id: device.id,
314
+ accountId: device.accountId,
315
+ deviceId: device.deviceId,
316
+ secret: nextSecret,
317
+ secondFactorVerified: device.secondFactorVerified === true,
318
+ expiresAt: at + idleTtlMs
319
+ };
320
+ }
321
+
322
+ async function replayDetected(device, at) {
323
+ await revoke({ id: device.id }, 'replay', at);
324
+ try {
325
+ await onReplay({ accountId: device.accountId, id: device.id, at });
326
+ } catch (error) {
327
+ onError(error);
328
+ }
329
+ }
330
+
331
+ /**
332
+ * "Forget this account on this device", with no session: the secret is the
333
+ * proof. Silent either way — the answer never says whether anything matched.
334
+ */
335
+ async function forget(proof = {}) {
336
+ const { deviceId, secret } = proof || {};
337
+ if (typeof deviceId !== 'string' || typeof secret !== 'string'
338
+ || !DEVICE_ID_PATTERN.test(deviceId) || !SECRET_PATTERN.test(secret)) return;
339
+ await revoke({ deviceId, secretHash: fingerprint(secret) }, 'forgotten');
340
+ }
341
+
342
+ /** What the owner sees: never the secret, its fingerprint, nor the lookup key. */
343
+ async function list(accountId) {
344
+ const at = now();
345
+ const rows = await store.listActive(String(accountId));
346
+ return rows
347
+ .filter((row) => row.expiresAt > at)
348
+ .sort((a, b) => b.lastUsedAt - a.lastUsedAt)
349
+ .map((row) => ({
350
+ id: row.id,
351
+ deviceName: row.deviceName || '',
352
+ platform: row.platform || 'other',
353
+ createdAt: row.createdAt,
354
+ lastUsedAt: row.lastUsedAt,
355
+ expiresAt: row.expiresAt
356
+ }));
357
+ }
358
+
359
+ /** Remove ONE device of the signed-in account. False if it is not theirs. */
360
+ async function remove(accountId, id) {
361
+ if (!accountId || !id) return false;
362
+ const count = await revoke({ id: String(id), accountId: String(accountId) }, 'removed');
363
+ return Number(count) > 0;
364
+ }
365
+
366
+ /** Every device of the account falls: password changed, sessions revoked, account closing. */
367
+ function revokeAll(accountId, reason = 'revoked') {
368
+ return revoke({ accountId: String(accountId) }, reason);
369
+ }
370
+
371
+ return {
372
+ enroll,
373
+ exchange,
374
+ forget,
375
+ list,
376
+ remove,
377
+ revokeAll,
378
+ revoke: (id, reason = 'revoked') => revoke({ id: String(id) }, reason),
379
+ fingerprint
380
+ };
381
+ }
382
+
383
+ module.exports = {
384
+ TrustedDeviceError,
385
+ createTrustedDeviceService,
386
+ createMemoryTrustedDeviceStore,
387
+ createMemoryAttemptCounter,
388
+ TRUSTED_DEVICE_ID_PATTERN: DEVICE_ID_PATTERN,
389
+ TRUSTED_DEVICE_SECRET_PATTERN: SECRET_PATTERN
390
+ };