@astratra/security 1.9.1 → 1.11.0
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/README.md +267 -0
- package/package.json +1 -1
- package/src/index.d.ts +387 -0
- package/src/index.js +5 -1
- package/src/loginDevices.js +298 -0
- package/src/privateFileLinks.js +327 -0
- package/src/refreshTokens.js +214 -0
- package/src/trustedDevices.js +390 -0
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Staying signed in, without leaving a skeleton key lying around.
|
|
3
|
+
*
|
|
4
|
+
* An access token is deliberately short-lived — that brevity is what limits
|
|
5
|
+
* the damage of a theft. The price is that something has to renew it, and that
|
|
6
|
+
* something is a long-lived credential. Get it wrong and you have replaced a
|
|
7
|
+
* one-hour risk with a one-month one.
|
|
8
|
+
*
|
|
9
|
+
* Four decisions carry this module.
|
|
10
|
+
*
|
|
11
|
+
* IT IS NOT A JWT. A refresh token proves nothing by itself and carries no
|
|
12
|
+
* claims: it is an opaque random string, meaningful only as a row in a store.
|
|
13
|
+
* That is what makes it REVOCABLE — a signed token is valid until it expires,
|
|
14
|
+
* whatever you would prefer.
|
|
15
|
+
*
|
|
16
|
+
* IT IS STORED AS A FINGERPRINT, NEVER IN THE CLEAR. A stolen database then
|
|
17
|
+
* yields no sessions at all. The token has full entropy, so a plain SHA-256 is
|
|
18
|
+
* the right hash here: there is nothing to brute-force, and a slow hash on
|
|
19
|
+
* every refresh would only be a denial-of-service surface.
|
|
20
|
+
*
|
|
21
|
+
* IT ROTATES ON EVERY USE. The token presented is SPENT, and a new one takes
|
|
22
|
+
* its place. A token seen twice is therefore an anomaly, not a normal case —
|
|
23
|
+
* which is the whole point of the next rule.
|
|
24
|
+
*
|
|
25
|
+
* A REPLAY KILLS THE FAMILY. When a spent token comes back, someone kept a
|
|
26
|
+
* copy: the legitimate client has already moved on. Refusing just that one
|
|
27
|
+
* token would leave the thief holding the CURRENT one, so the entire chain
|
|
28
|
+
* descending from that sign-in is revoked. The real person signs in again —
|
|
29
|
+
* an inconvenience that is the correct price for a stolen session.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
const crypto = require('crypto');
|
|
33
|
+
|
|
34
|
+
const DEFAULT_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
35
|
+
|
|
36
|
+
class RefreshTokenError extends Error {
|
|
37
|
+
/**
|
|
38
|
+
* @param {string} message
|
|
39
|
+
* @param {'REFRESH_TOKEN_INVALID'|'REFRESH_TOKEN_EXPIRED'|'REFRESH_TOKEN_REUSED'} code
|
|
40
|
+
*/
|
|
41
|
+
constructor(message, code) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.name = 'RefreshTokenError';
|
|
44
|
+
this.code = code;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function fingerprint(token) {
|
|
49
|
+
return crypto.createHash('sha256').update(String(token)).digest('hex');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The store contract, in memory. Dev and tests only: sessions vanish on
|
|
54
|
+
* restart, which means everyone is signed out by a deploy.
|
|
55
|
+
*/
|
|
56
|
+
function createMemoryRefreshTokenStore() {
|
|
57
|
+
const records = new Map();
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
async save(record) {
|
|
61
|
+
records.set(record.id, { ...record });
|
|
62
|
+
return { ...record };
|
|
63
|
+
},
|
|
64
|
+
async findByHash(hash) {
|
|
65
|
+
for (const record of records.values()) {
|
|
66
|
+
if (record.hash === hash) return { ...record };
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
},
|
|
70
|
+
async markConsumed(id, at) {
|
|
71
|
+
const record = records.get(id);
|
|
72
|
+
if (record) record.consumedAt = at;
|
|
73
|
+
},
|
|
74
|
+
async revokeFamily(familyId, at) {
|
|
75
|
+
for (const record of records.values()) {
|
|
76
|
+
if (record.familyId === familyId) record.revokedAt = record.revokedAt || at;
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
async revokeAllForUser(userId, at) {
|
|
80
|
+
for (const record of records.values()) {
|
|
81
|
+
if (record.userId === userId) record.revokedAt = record.revokedAt || at;
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
async deleteExpired(before) {
|
|
85
|
+
let removed = 0;
|
|
86
|
+
for (const [id, record] of records) {
|
|
87
|
+
if (record.expiresAt <= before) {
|
|
88
|
+
records.delete(id);
|
|
89
|
+
removed += 1;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return removed;
|
|
93
|
+
},
|
|
94
|
+
/** Test and inspection helper — not part of the contract adapters must meet. */
|
|
95
|
+
async all() {
|
|
96
|
+
return [...records.values()].map((record) => ({ ...record }));
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* @param {object} options
|
|
103
|
+
* @param {object} options.store save/findByHash/markConsumed/revokeFamily/
|
|
104
|
+
* revokeAllForUser/deleteExpired. The memory one above, or your database.
|
|
105
|
+
* @param {number} [options.ttlMs] Lifetime of each token. Default 30 days.
|
|
106
|
+
* @param {Function} [options.now] Clock, for tests.
|
|
107
|
+
* @param {Function} [options.randomToken] Token factory, for tests.
|
|
108
|
+
*/
|
|
109
|
+
function createRefreshTokenService(options = {}) {
|
|
110
|
+
const store = options.store;
|
|
111
|
+
if (!store || typeof store.findByHash !== 'function' || typeof store.save !== 'function') {
|
|
112
|
+
throw new Error('createRefreshTokenService requires options.store.');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const ttlMs = options.ttlMs || DEFAULT_TTL_MS;
|
|
116
|
+
const now = options.now || Date.now;
|
|
117
|
+
/*
|
|
118
|
+
* HEX, not base64url — and this cost a real bug to learn.
|
|
119
|
+
*
|
|
120
|
+
* base64url contains '-', so roughly one token in 130 carried a '--'
|
|
121
|
+
* somewhere. The WAF reads '--' in a request body as an SQL comment and
|
|
122
|
+
* answers 403, so that session could NEVER be renewed: the client retries
|
|
123
|
+
* the same token, gets blocked again, and the person is signed out for
|
|
124
|
+
* reasons nobody can reproduce.
|
|
125
|
+
*
|
|
126
|
+
* A credential must never be readable as content. Hex has no character any
|
|
127
|
+
* filter takes an interest in, and 32 random bytes carry the same entropy
|
|
128
|
+
* whichever alphabet prints them.
|
|
129
|
+
*/
|
|
130
|
+
const randomToken = options.randomToken || (() => crypto.randomBytes(32).toString('hex'));
|
|
131
|
+
|
|
132
|
+
async function mint({ userId, familyId }) {
|
|
133
|
+
const token = randomToken();
|
|
134
|
+
const issuedAt = now();
|
|
135
|
+
const record = {
|
|
136
|
+
id: crypto.randomUUID(),
|
|
137
|
+
familyId: familyId || crypto.randomUUID(),
|
|
138
|
+
userId: String(userId),
|
|
139
|
+
hash: fingerprint(token),
|
|
140
|
+
createdAt: issuedAt,
|
|
141
|
+
/* Counted from NOW on every rotation: an active session should not die
|
|
142
|
+
because it was first opened a month ago. */
|
|
143
|
+
expiresAt: issuedAt + ttlMs,
|
|
144
|
+
consumedAt: null,
|
|
145
|
+
revokedAt: null
|
|
146
|
+
};
|
|
147
|
+
await store.save(record);
|
|
148
|
+
return { token, id: record.id, familyId: record.familyId, userId: record.userId, expiresAt: record.expiresAt };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A fresh sign-in: a new family of its own. */
|
|
152
|
+
async function issue({ userId } = {}) {
|
|
153
|
+
if (!userId) throw new Error('issue requires userId.');
|
|
154
|
+
return mint({ userId });
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Exchange a token for the next one.
|
|
159
|
+
* @throws {RefreshTokenError} invalid, expired, or replayed.
|
|
160
|
+
*/
|
|
161
|
+
async function rotate(token) {
|
|
162
|
+
if (typeof token !== 'string' || !token) {
|
|
163
|
+
throw new RefreshTokenError('Unknown refresh token.', 'REFRESH_TOKEN_INVALID');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const record = await store.findByHash(fingerprint(token));
|
|
167
|
+
if (!record) throw new RefreshTokenError('Unknown refresh token.', 'REFRESH_TOKEN_INVALID');
|
|
168
|
+
|
|
169
|
+
if (record.revokedAt) {
|
|
170
|
+
throw new RefreshTokenError('This session has been revoked.', 'REFRESH_TOKEN_INVALID');
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/* Checked BEFORE expiry: a replayed token that also happens to have
|
|
174
|
+
expired is still a theft, and must still kill the family. */
|
|
175
|
+
if (record.consumedAt) {
|
|
176
|
+
await store.revokeFamily(record.familyId, now());
|
|
177
|
+
throw new RefreshTokenError(
|
|
178
|
+
'Refresh token replayed — every session from this sign-in has been revoked.',
|
|
179
|
+
'REFRESH_TOKEN_REUSED'
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (record.expiresAt <= now()) {
|
|
184
|
+
throw new RefreshTokenError('This session has expired.', 'REFRESH_TOKEN_EXPIRED');
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
await store.markConsumed(record.id, now());
|
|
188
|
+
return mint({ userId: record.userId, familyId: record.familyId });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Sign out one device: that chain, and nothing else. */
|
|
192
|
+
async function revokeFamily(familyId) {
|
|
193
|
+
await store.revokeFamily(familyId, now());
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Password changed, account recovered: everything this person holds dies. */
|
|
197
|
+
async function revokeAllForUser(userId) {
|
|
198
|
+
await store.revokeAllForUser(String(userId), now());
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Housekeeping — call it on a timer. Returns how many rows were dropped. */
|
|
202
|
+
async function prune() {
|
|
203
|
+
if (typeof store.deleteExpired !== 'function') return 0;
|
|
204
|
+
return store.deleteExpired(now());
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return { issue, rotate, revokeFamily, revokeAllForUser, prune, fingerprint };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
module.exports = {
|
|
211
|
+
RefreshTokenError,
|
|
212
|
+
createMemoryRefreshTokenStore,
|
|
213
|
+
createRefreshTokenService
|
|
214
|
+
};
|
|
@@ -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
|
+
};
|