@basaltkit/auth 3.1.0 → 4.0.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 +159 -24
- package/dist/apikeys-plugin.d.ts +11 -1
- package/dist/apikeys-plugin.js +22 -2
- package/dist/auth.d.ts +108 -20
- package/dist/auth.js +170 -41
- package/dist/hashing.d.ts +3 -1
- package/dist/hashing.js +29 -7
- package/dist/index.d.ts +6 -5
- package/dist/index.js +6 -5
- package/dist/jwt.js +13 -1
- package/dist/oauth-plugin.d.ts +12 -1
- package/dist/oauth-plugin.js +6 -5
- package/dist/oauth.d.ts +81 -2
- package/dist/oauth.js +221 -40
- package/dist/plugin.d.ts +6 -1
- package/dist/secret-box.d.ts +80 -8
- package/dist/secret-box.js +178 -27
- package/dist/stores.d.ts +60 -0
- package/dist/stores.js +52 -0
- package/dist/throttle.d.ts +12 -4
- package/dist/throttle.js +16 -4
- package/dist/webauthn-plugin.js +1 -1
- package/dist/webauthn.d.ts +49 -8
- package/dist/webauthn.js +70 -11
- package/package.json +4 -4
package/dist/secret-box.js
CHANGED
|
@@ -1,38 +1,189 @@
|
|
|
1
|
-
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from 'node:crypto';
|
|
2
|
+
import { BasaltError } from '@basaltkit/core';
|
|
2
3
|
/**
|
|
3
4
|
* Authenticated encryption (AES-256-GCM) for secrets stored at rest — used to
|
|
4
5
|
* encrypt TOTP secrets so a database leak doesn't hand the attacker every
|
|
5
6
|
* user's live second factor.
|
|
6
7
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
8
|
+
* ## Envelope
|
|
9
|
+
*
|
|
10
|
+
* bka2.<keyId>.<iv>.<tag>.<ciphertext>
|
|
11
|
+
*
|
|
12
|
+
* all but the version and key id base64url. Compared with the `v1:` format it
|
|
13
|
+
* replaces:
|
|
14
|
+
*
|
|
15
|
+
* - **Key ring with ids.** The first key is the active one; every other key
|
|
16
|
+
* stays readable, so rotation is rolling ({@link SecretBox.reseal}) instead
|
|
17
|
+
* of a flag day. The key id travels in the clear and is covered by the tag.
|
|
18
|
+
* - **HKDF-SHA256**, domain-separated by a label, instead of a bare SHA-256 of
|
|
19
|
+
* the key material.
|
|
20
|
+
* - **AAD binding.** Every ciphertext is bound to its record (a purpose and a
|
|
21
|
+
* subject — the user id for TOTP secrets): a blob copied into another user's
|
|
22
|
+
* row fails the tag check instead of decrypting there.
|
|
23
|
+
* - **No plaintext path.** A value that is not an envelope is refused. Legacy
|
|
24
|
+
* `v1:` envelopes and plaintext values are readable only through an explicit
|
|
25
|
+
* {@link SecretBoxLegacyOptions} opt-in, meant for the migration window.
|
|
26
|
+
*
|
|
27
|
+
* Without the last point, anyone able to write the column could replace an
|
|
28
|
+
* encrypted TOTP secret with a plaintext one they know (a downgrade), and the
|
|
29
|
+
* box would hand it back as if it were genuine.
|
|
30
|
+
*/
|
|
31
|
+
const VERSION = 'bka2';
|
|
32
|
+
const LEGACY_PREFIX = 'v1:';
|
|
33
|
+
/** Mixed into HKDF so key material reused elsewhere derives a different box key. */
|
|
34
|
+
const HKDF_INFO = 'basalt:auth:secret-box:v2';
|
|
35
|
+
const KEY_ID = /^[A-Za-z0-9_-]{1,64}$/;
|
|
36
|
+
const MIN_KEY_BYTES = 32;
|
|
37
|
+
/** GCM's full tag; anything shorter is refused (a short tag is cheaper to forge). */
|
|
38
|
+
const TAG_BYTES = 16;
|
|
39
|
+
/** A secret-box key or its value could not be used (configuration error). */
|
|
40
|
+
export class SecretBoxKeyError extends BasaltError {
|
|
41
|
+
status = 500;
|
|
42
|
+
expose = false;
|
|
43
|
+
constructor(detail) {
|
|
44
|
+
super('AUTH_SECRET_BOX_KEY_INVALID', `Invalid secret-box key configuration: ${detail}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A stored secret could not be opened: not an envelope (and no legacy opt-in),
|
|
49
|
+
* an unknown key id, tampering, or a blob that belongs to another record. One
|
|
50
|
+
* error for every case, so a caller cannot tell them apart.
|
|
10
51
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
52
|
+
export class SecretUnreadableError extends BasaltError {
|
|
53
|
+
status = 500;
|
|
54
|
+
expose = false;
|
|
55
|
+
constructor(detail) {
|
|
56
|
+
super('AUTH_SECRET_UNREADABLE', `A stored secret could not be decrypted: ${detail}`);
|
|
57
|
+
}
|
|
15
58
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
59
|
+
const toBytes = (key) => (typeof key === 'string' ? Buffer.from(key, 'utf8') : Buffer.from(key));
|
|
60
|
+
/** NUL-separated, so no field boundary can be shifted (`a|b`+`c` ≠ `a`+`b|c`). */
|
|
61
|
+
function aad(keyId, context) {
|
|
62
|
+
for (const field of [context.purpose, context.subject]) {
|
|
63
|
+
if (typeof field !== 'string' || field.length === 0 || field.includes('\0')) {
|
|
64
|
+
throw new SecretUnreadableError('the secret context must be non-empty strings without NUL characters.');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return Buffer.from([VERSION, keyId, context.purpose, context.subject].join('\0'), 'utf8');
|
|
23
68
|
}
|
|
24
69
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* value fails authentication (tampering / wrong key).
|
|
70
|
+
* Seals and opens secrets against a key ring. See the module comment for the
|
|
71
|
+
* envelope and the threat model.
|
|
28
72
|
*/
|
|
29
|
-
export
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
73
|
+
export class SecretBox {
|
|
74
|
+
keys = new Map();
|
|
75
|
+
activeId;
|
|
76
|
+
v1Keys;
|
|
77
|
+
acceptPlaintext;
|
|
78
|
+
constructor(options) {
|
|
79
|
+
const ring = options.keys;
|
|
80
|
+
if (!Array.isArray(ring) || ring.length === 0)
|
|
81
|
+
throw new SecretBoxKeyError('at least one key is required.');
|
|
82
|
+
for (const entry of ring) {
|
|
83
|
+
if (typeof entry?.id !== 'string' || !KEY_ID.test(entry.id)) {
|
|
84
|
+
throw new SecretBoxKeyError(`key id ${JSON.stringify(entry?.id)} must match ${String(KEY_ID)}.`);
|
|
85
|
+
}
|
|
86
|
+
if (this.keys.has(entry.id))
|
|
87
|
+
throw new SecretBoxKeyError(`duplicate key id "${entry.id}".`);
|
|
88
|
+
const material = toBytes(entry.key);
|
|
89
|
+
if (material.length < MIN_KEY_BYTES) {
|
|
90
|
+
throw new SecretBoxKeyError(`key "${entry.id}" is ${material.length} bytes; at least ${MIN_KEY_BYTES} are required.`);
|
|
91
|
+
}
|
|
92
|
+
this.keys.set(entry.id, Buffer.from(hkdfSync('sha256', material, Buffer.alloc(0), HKDF_INFO, 32)));
|
|
93
|
+
}
|
|
94
|
+
this.activeId = ring[0].id;
|
|
95
|
+
// The v1 format derived its key with a bare SHA-256; reproduced only to read old rows.
|
|
96
|
+
this.v1Keys = (options.legacy?.v1Keys ?? []).map((k) => createHash('sha256').update(toBytes(k)).digest());
|
|
97
|
+
this.acceptPlaintext = options.legacy?.plaintext === true;
|
|
98
|
+
}
|
|
99
|
+
/** The key id new ciphertexts are sealed with. */
|
|
100
|
+
get activeKeyId() {
|
|
101
|
+
return this.activeId;
|
|
102
|
+
}
|
|
103
|
+
/** Encrypts `plaintext` under the active key, bound to `context`. */
|
|
104
|
+
seal(plaintext, context) {
|
|
105
|
+
const key = this.keys.get(this.activeId);
|
|
106
|
+
const iv = randomBytes(12);
|
|
107
|
+
const cipher = createCipheriv('aes-256-gcm', key, iv, { authTagLength: TAG_BYTES });
|
|
108
|
+
cipher.setAAD(aad(this.activeId, context));
|
|
109
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
|
110
|
+
return [VERSION, this.activeId, iv.toString('base64url'), cipher.getAuthTag().toString('base64url'), ciphertext.toString('base64url')].join('.');
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Decrypts a value sealed for `context`. Throws {@link SecretUnreadableError}
|
|
114
|
+
* for anything else — including plaintext and `v1:` values unless the
|
|
115
|
+
* matching legacy opt-in is set.
|
|
116
|
+
*/
|
|
117
|
+
open(value, context) {
|
|
118
|
+
if (typeof value !== 'string')
|
|
119
|
+
throw new SecretUnreadableError('not a string.');
|
|
120
|
+
if (value.startsWith(`${VERSION}.`))
|
|
121
|
+
return this.openV2(value, context);
|
|
122
|
+
if (value.startsWith(LEGACY_PREFIX))
|
|
123
|
+
return this.openV1(value);
|
|
124
|
+
if (this.acceptPlaintext)
|
|
125
|
+
return value;
|
|
126
|
+
throw new SecretUnreadableError('the value is not an encrypted envelope (plaintext is refused).');
|
|
127
|
+
}
|
|
128
|
+
/** Whether `value` is already sealed with the active key (nothing to migrate). */
|
|
129
|
+
isCurrent(value) {
|
|
130
|
+
const parts = value.split('.');
|
|
131
|
+
return parts.length === 5 && parts[0] === VERSION && parts[1] === this.activeId;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Re-seals `value` under the active key — for rotation, and for migrating
|
|
135
|
+
* `v1:` / plaintext values (which requires the legacy opt-in to read them).
|
|
136
|
+
* Returns `null` when the value is already current, so a caller can skip the
|
|
137
|
+
* write.
|
|
138
|
+
*/
|
|
139
|
+
reseal(value, context) {
|
|
140
|
+
if (this.isCurrent(value)) {
|
|
141
|
+
this.open(value, context); // still authenticate it: never vouch for a blob that does not open
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
return this.seal(this.open(value, context), context);
|
|
145
|
+
}
|
|
146
|
+
openV2(value, context) {
|
|
147
|
+
const parts = value.split('.');
|
|
148
|
+
if (parts.length !== 5)
|
|
149
|
+
throw new SecretUnreadableError('malformed envelope.');
|
|
150
|
+
const [, keyId, ivB64, tagB64, ctB64] = parts;
|
|
151
|
+
const key = this.keys.get(keyId);
|
|
152
|
+
if (!key)
|
|
153
|
+
throw new SecretUnreadableError(`unknown key id "${keyId}" (was it removed from the ring?).`);
|
|
154
|
+
const additional = aad(keyId, context);
|
|
155
|
+
try {
|
|
156
|
+
const tag = Buffer.from(tagB64, 'base64url');
|
|
157
|
+
if (tag.length !== TAG_BYTES)
|
|
158
|
+
throw new Error('truncated tag');
|
|
159
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(ivB64, 'base64url'), { authTagLength: TAG_BYTES });
|
|
160
|
+
decipher.setAAD(additional);
|
|
161
|
+
decipher.setAuthTag(tag);
|
|
162
|
+
return Buffer.concat([decipher.update(Buffer.from(ctB64, 'base64url')), decipher.final()]).toString('utf8');
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
throw new SecretUnreadableError('authentication failed (wrong key, tampering, or a value from another record).');
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
openV1(value) {
|
|
169
|
+
if (this.v1Keys.length === 0)
|
|
170
|
+
throw new SecretUnreadableError('a legacy v1 envelope, and no legacy v1 key is configured.');
|
|
171
|
+
const [, ivB64, tagB64, ctB64] = value.split(':');
|
|
172
|
+
if (!ivB64 || !tagB64 || !ctB64)
|
|
173
|
+
throw new SecretUnreadableError('malformed legacy envelope.');
|
|
174
|
+
for (const key of this.v1Keys) {
|
|
175
|
+
try {
|
|
176
|
+
const tag = Buffer.from(tagB64, 'base64');
|
|
177
|
+
if (tag.length !== TAG_BYTES)
|
|
178
|
+
break;
|
|
179
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(ivB64, 'base64'), { authTagLength: TAG_BYTES });
|
|
180
|
+
decipher.setAuthTag(tag);
|
|
181
|
+
return Buffer.concat([decipher.update(Buffer.from(ctB64, 'base64')), decipher.final()]).toString('utf8');
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
// try the next legacy key
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
throw new SecretUnreadableError('authentication failed for the legacy envelope.');
|
|
188
|
+
}
|
|
38
189
|
}
|
package/dist/stores.d.ts
CHANGED
|
@@ -23,17 +23,77 @@ export interface UserSource {
|
|
|
23
23
|
}): Promise<AuthUser>;
|
|
24
24
|
/** Required for email verification and password reset. Returns the updated user. */
|
|
25
25
|
update?(id: string, patch: UserPatch): Promise<AuthUser | null>;
|
|
26
|
+
/**
|
|
27
|
+
* Bulk counterpart of {@link UserSource.findById}, for resolving the contact
|
|
28
|
+
* details of accounts the caller already knows — e.g. "email every admin of
|
|
29
|
+
* this tenant" (`@basaltkit/teams`' `roleRecipients`). Without it a caller
|
|
30
|
+
* either makes one round trip per id or reads the auth tables directly; the
|
|
31
|
+
* point of this method is that it has to do neither.
|
|
32
|
+
*
|
|
33
|
+
* Contract:
|
|
34
|
+
* - resolves {@link PublicUser}, **never** `AuthUser` — a directory lookup
|
|
35
|
+
* has no business carrying a password hash, and a driver should not even
|
|
36
|
+
* SELECT the credential columns;
|
|
37
|
+
* - one entry per **found** id, in the order of `ids`; ids with no account
|
|
38
|
+
* are omitted, so the result may be shorter than the input;
|
|
39
|
+
* - duplicate ids yield a single entry, and an empty list resolves to `[]`
|
|
40
|
+
* without touching the database.
|
|
41
|
+
*
|
|
42
|
+
* Optional: stores written before it keep compiling, and callers fall back to
|
|
43
|
+
* one `findById` per id.
|
|
44
|
+
*/
|
|
45
|
+
findByIds?(ids: readonly string[]): Promise<PublicUser[]>;
|
|
26
46
|
}
|
|
27
47
|
export declare class MemoryUserSource implements UserSource {
|
|
28
48
|
private readonly users;
|
|
29
49
|
findByEmail(email: string): Promise<AuthUser | null>;
|
|
30
50
|
findById(id: string): Promise<AuthUser | null>;
|
|
51
|
+
findByIds(ids: readonly string[]): Promise<PublicUser[]>;
|
|
31
52
|
create(data: {
|
|
32
53
|
email: string;
|
|
33
54
|
passwordHash: string;
|
|
34
55
|
}): Promise<AuthUser>;
|
|
35
56
|
update(id: string, patch: UserPatch): Promise<AuthUser | null>;
|
|
36
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* A federated identity bound to a local account: the provider's stable subject
|
|
60
|
+
* (`sub`), not the email it happens to assert today. Once linked, the provider
|
|
61
|
+
* account keeps reaching the same local account even if its email changes at
|
|
62
|
+
* the IdP, and another subject asserting the same email does not.
|
|
63
|
+
*/
|
|
64
|
+
export interface AccountLink {
|
|
65
|
+
/** Provider name as configured (`'google'`, `'acme-okta'`, …). */
|
|
66
|
+
provider: string;
|
|
67
|
+
/** The provider's stable subject identifier (OIDC `sub`, GitHub user id). */
|
|
68
|
+
subject: string;
|
|
69
|
+
userId: string;
|
|
70
|
+
/** The (canonical) email the provider asserted when the link was made — informational. */
|
|
71
|
+
email: string;
|
|
72
|
+
createdAt: number;
|
|
73
|
+
}
|
|
74
|
+
export interface AccountLinkStore {
|
|
75
|
+
/** The link for `(provider, subject)`, or null. */
|
|
76
|
+
find(provider: string, subject: string): Promise<AccountLink | null>;
|
|
77
|
+
/**
|
|
78
|
+
* Inserts the link. MUST be atomic on `(provider, subject)`: when a link for
|
|
79
|
+
* that pair already exists (for any user) nothing is written and `false` is
|
|
80
|
+
* returned — two concurrent first logins cannot both bind the subject.
|
|
81
|
+
*/
|
|
82
|
+
create(link: AccountLink): Promise<boolean>;
|
|
83
|
+
/** Every link of a user (any provider). */
|
|
84
|
+
forUser(userId: string): Promise<AccountLink[]>;
|
|
85
|
+
remove(provider: string, subject: string): Promise<void>;
|
|
86
|
+
/** Drops every link of a user — fired when an unverified account is adopted. */
|
|
87
|
+
deleteAllForUser(userId: string): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
export declare class MemoryAccountLinkStore implements AccountLinkStore {
|
|
90
|
+
private readonly links;
|
|
91
|
+
find(provider: string, subject: string): Promise<AccountLink | null>;
|
|
92
|
+
create(link: AccountLink): Promise<boolean>;
|
|
93
|
+
forUser(userId: string): Promise<AccountLink[]>;
|
|
94
|
+
remove(provider: string, subject: string): Promise<void>;
|
|
95
|
+
deleteAllForUser(userId: string): Promise<void>;
|
|
96
|
+
}
|
|
37
97
|
export type AuthTokenPurpose = 'verify_email' | 'reset_password';
|
|
38
98
|
export interface AuthTokenRecord {
|
|
39
99
|
token: string;
|
package/dist/stores.js
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
2
|
/** SHA-256 of a session id — only this is persisted, never the raw cookie value. */
|
|
3
3
|
const hashSessionId = (id) => createHash('sha256').update(id).digest('hex');
|
|
4
|
+
/**
|
|
5
|
+
* Projects a stored user onto the safe, non-credential shape. Local to this
|
|
6
|
+
* module: the exported `publicUser` lives in `auth.ts`, which imports from
|
|
7
|
+
* here, so stores can't reach for it without a cycle.
|
|
8
|
+
*/
|
|
9
|
+
const contactOf = (user) => ({
|
|
10
|
+
id: user.id,
|
|
11
|
+
email: user.email,
|
|
12
|
+
emailVerified: user.emailVerified ?? false,
|
|
13
|
+
});
|
|
4
14
|
export class MemoryUserSource {
|
|
5
15
|
users = new Map();
|
|
6
16
|
async findByEmail(email) {
|
|
@@ -16,6 +26,20 @@ export class MemoryUserSource {
|
|
|
16
26
|
async findById(id) {
|
|
17
27
|
return this.users.get(id) ?? null;
|
|
18
28
|
}
|
|
29
|
+
async findByIds(ids) {
|
|
30
|
+
const out = [];
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
for (const id of ids) {
|
|
33
|
+
if (seen.has(id))
|
|
34
|
+
continue;
|
|
35
|
+
seen.add(id);
|
|
36
|
+
const user = this.users.get(id);
|
|
37
|
+
// Project, never hand out the live record: this is a contact list.
|
|
38
|
+
if (user)
|
|
39
|
+
out.push(contactOf(user));
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
19
43
|
async create(data) {
|
|
20
44
|
const user = { id: randomUUID(), emailVerified: false, ...data };
|
|
21
45
|
this.users.set(user.id, user);
|
|
@@ -29,6 +53,34 @@ export class MemoryUserSource {
|
|
|
29
53
|
return user;
|
|
30
54
|
}
|
|
31
55
|
}
|
|
56
|
+
/** NUL cannot occur in either part, so the key is unambiguous. */
|
|
57
|
+
const linkKey = (provider, subject) => `${provider}\0${subject}`;
|
|
58
|
+
export class MemoryAccountLinkStore {
|
|
59
|
+
links = new Map();
|
|
60
|
+
async find(provider, subject) {
|
|
61
|
+
const found = this.links.get(linkKey(provider, subject));
|
|
62
|
+
return found ? { ...found } : null;
|
|
63
|
+
}
|
|
64
|
+
// Synchronous check-and-insert: no await between the read and the write.
|
|
65
|
+
async create(link) {
|
|
66
|
+
const key = linkKey(link.provider, link.subject);
|
|
67
|
+
if (this.links.has(key))
|
|
68
|
+
return false;
|
|
69
|
+
this.links.set(key, { ...link });
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
async forUser(userId) {
|
|
73
|
+
return [...this.links.values()].filter((l) => l.userId === userId).map((l) => ({ ...l }));
|
|
74
|
+
}
|
|
75
|
+
async remove(provider, subject) {
|
|
76
|
+
this.links.delete(linkKey(provider, subject));
|
|
77
|
+
}
|
|
78
|
+
async deleteAllForUser(userId) {
|
|
79
|
+
for (const [key, link] of this.links)
|
|
80
|
+
if (link.userId === userId)
|
|
81
|
+
this.links.delete(key);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
32
84
|
export class MemoryAuthTokenStore {
|
|
33
85
|
records = new Map();
|
|
34
86
|
async create(record) {
|
package/dist/throttle.d.ts
CHANGED
|
@@ -27,8 +27,12 @@ export interface ThrottleStore {
|
|
|
27
27
|
/**
|
|
28
28
|
* Atomically counts one attempt and returns the new state. The first hit of
|
|
29
29
|
* a key opens a fixed window of `windowMs`; later hits do not extend it.
|
|
30
|
+
*
|
|
31
|
+
* `limit` is the caller's budget: once `count >= limit` the key is locked.
|
|
32
|
+
* A bounded store uses it to keep locked keys over unlocked ones when it has
|
|
33
|
+
* to evict; stores without eviction may ignore it.
|
|
30
34
|
*/
|
|
31
|
-
hit(key: string, windowMs: number): ThrottleWindow | Promise<ThrottleWindow>;
|
|
35
|
+
hit(key: string, windowMs: number, limit?: number): ThrottleWindow | Promise<ThrottleWindow>;
|
|
32
36
|
/** The current state without counting; null when the key has no live window. */
|
|
33
37
|
peek(key: string): ThrottleWindow | null | Promise<ThrottleWindow | null>;
|
|
34
38
|
/** Gives one attempt back (a successful attempt must not consume budget). */
|
|
@@ -39,8 +43,12 @@ export interface ThrottleStore {
|
|
|
39
43
|
export interface MemoryThrottleStoreOptions {
|
|
40
44
|
/**
|
|
41
45
|
* Upper bound on tracked keys. When full, expired entries are swept and then
|
|
42
|
-
* the oldest ones are evicted, so failed logins with unique
|
|
43
|
-
* cannot grow the heap without limit
|
|
46
|
+
* the oldest UNLOCKED ones are evicted, so failed logins with unique
|
|
47
|
+
* identifiers cannot grow the heap without limit — and cannot flush a locked
|
|
48
|
+
* account out of the store to unlock it. Only when every tracked key is
|
|
49
|
+
* locked is the oldest lock evicted (the memory bound is absolute); reaching
|
|
50
|
+
* that state takes `maxEntries × limit` failures within one window.
|
|
51
|
+
* Default 100 000.
|
|
44
52
|
*/
|
|
45
53
|
maxEntries?: number;
|
|
46
54
|
/** Injectable clock for tests. */
|
|
@@ -58,7 +66,7 @@ export declare class MemoryThrottleStore implements ThrottleStore {
|
|
|
58
66
|
retainedKeyChars(): number;
|
|
59
67
|
private live;
|
|
60
68
|
private store;
|
|
61
|
-
hit(key: string, windowMs: number): ThrottleWindow;
|
|
69
|
+
hit(key: string, windowMs: number, limit?: number): ThrottleWindow;
|
|
62
70
|
peek(key: string): ThrottleWindow | null;
|
|
63
71
|
release(key: string): void;
|
|
64
72
|
reset(key: string): void;
|
package/dist/throttle.js
CHANGED
|
@@ -9,6 +9,7 @@ export class AccountLockedError extends BasaltError {
|
|
|
9
9
|
this.retryAfterMs = retryAfterMs;
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
|
+
const isLocked = (entry) => entry.limit !== undefined && entry.count >= entry.limit;
|
|
12
13
|
/** In-process {@link ThrottleStore} (the default): synchronous and bounded. */
|
|
13
14
|
export class MemoryThrottleStore {
|
|
14
15
|
entries = new Map();
|
|
@@ -42,7 +43,16 @@ export class MemoryThrottleStore {
|
|
|
42
43
|
for (const [k, e] of this.entries)
|
|
43
44
|
if (now >= e.resetAt)
|
|
44
45
|
this.entries.delete(k);
|
|
45
|
-
// Still full: evict the oldest entries (Map iterates in
|
|
46
|
+
// Still full: evict the oldest UNLOCKED entries (Map iterates in
|
|
47
|
+
// insertion order). Evicting a locked one would lift the lockout, so a
|
|
48
|
+
// flood of junk identifiers could buy an attacker a fresh budget.
|
|
49
|
+
for (const [k, e] of this.entries) {
|
|
50
|
+
if (this.entries.size < this.maxEntries)
|
|
51
|
+
break;
|
|
52
|
+
if (!isLocked(e))
|
|
53
|
+
this.entries.delete(k);
|
|
54
|
+
}
|
|
55
|
+
// Every entry is locked: the memory bound wins, the oldest lock goes.
|
|
46
56
|
for (const k of this.entries.keys()) {
|
|
47
57
|
if (this.entries.size < this.maxEntries)
|
|
48
58
|
break;
|
|
@@ -51,10 +61,12 @@ export class MemoryThrottleStore {
|
|
|
51
61
|
}
|
|
52
62
|
this.entries.set(key, entry);
|
|
53
63
|
}
|
|
54
|
-
hit(key, windowMs) {
|
|
64
|
+
hit(key, windowMs, limit) {
|
|
55
65
|
const now = this.clock();
|
|
56
66
|
const entry = this.live(key, now) ?? { count: 0, resetAt: now + windowMs };
|
|
57
67
|
entry.count += 1;
|
|
68
|
+
if (limit !== undefined)
|
|
69
|
+
entry.limit = limit;
|
|
58
70
|
this.store(key, entry, now);
|
|
59
71
|
return { count: entry.count, retryAfterMs: entry.resetAt - now };
|
|
60
72
|
}
|
|
@@ -132,7 +144,7 @@ export class LoginThrottle {
|
|
|
132
144
|
});
|
|
133
145
|
}
|
|
134
146
|
recordFailure(key) {
|
|
135
|
-
return chain(this.store.hit(this.key(key), this.windowMs), () => undefined);
|
|
147
|
+
return chain(this.store.hit(this.key(key), this.windowMs, this.maxAttempts), () => undefined);
|
|
136
148
|
}
|
|
137
149
|
/**
|
|
138
150
|
* Atomically counts this attempt and throws {@link AccountLockedError} when
|
|
@@ -140,7 +152,7 @@ export class LoginThrottle {
|
|
|
140
152
|
* simply keeps the reservation.
|
|
141
153
|
*/
|
|
142
154
|
reserve(key) {
|
|
143
|
-
return chain(this.store.hit(this.key(key), this.windowMs), (window) => {
|
|
155
|
+
return chain(this.store.hit(this.key(key), this.windowMs, this.maxAttempts), (window) => {
|
|
144
156
|
if (window.count > this.maxAttempts)
|
|
145
157
|
throw new AccountLockedError(window.retryAfterMs);
|
|
146
158
|
});
|
package/dist/webauthn-plugin.js
CHANGED
|
@@ -12,7 +12,7 @@ export function webauthnPlugin(options) {
|
|
|
12
12
|
hooks.on('auth:social_account_adopted', async ({ user }) => {
|
|
13
13
|
const service = container.get(WEBAUTHN);
|
|
14
14
|
for (const credential of await service.list(user.id))
|
|
15
|
-
await service.remove(credential.id);
|
|
15
|
+
await service.remove(user.id, credential.id);
|
|
16
16
|
});
|
|
17
17
|
container.singleton(WEBAUTHN, () => new WebAuthnService({
|
|
18
18
|
config: options.config,
|
package/dist/webauthn.d.ts
CHANGED
|
@@ -24,21 +24,46 @@ export interface PasskeyStore {
|
|
|
24
24
|
add(credential: PasskeyCredential): Promise<void>;
|
|
25
25
|
get(credentialId: string): Promise<PasskeyCredential | null>;
|
|
26
26
|
forUser(userId: string): Promise<PasskeyCredential[]>;
|
|
27
|
-
|
|
27
|
+
/**
|
|
28
|
+
* Compare-and-set of the signature counter: stores `next` (and `lastUsedAt`)
|
|
29
|
+
* only if the stored counter still equals `expected`, and returns whether
|
|
30
|
+
* THIS call wrote it. Clone detection depends on it — with a read-then-write,
|
|
31
|
+
* a cloned authenticator used concurrently with the genuine one presents the
|
|
32
|
+
* same next counter twice and both assertions pass. Implement it as one
|
|
33
|
+
* conditional UPDATE (`… WHERE id = ? AND counter = ?`).
|
|
34
|
+
*/
|
|
35
|
+
compareAndSetCounter(credentialId: string, expected: number, next: number, lastUsedAt: number): Promise<boolean>;
|
|
36
|
+
/**
|
|
37
|
+
* @deprecated Unconditional write, no longer called by {@link WebAuthnService}
|
|
38
|
+
* (it uses {@link PasskeyStore.compareAndSetCounter}).
|
|
39
|
+
*/
|
|
40
|
+
updateCounter?(credentialId: string, counter: number, lastUsedAt: number): Promise<void>;
|
|
28
41
|
remove(credentialId: string): Promise<void>;
|
|
29
42
|
}
|
|
43
|
+
/** A passkey store without {@link PasskeyStore.compareAndSetCounter} (written against the pre-CAS contract). */
|
|
44
|
+
export declare class PasskeyStoreOutdatedError extends BasaltError {
|
|
45
|
+
readonly status = 500;
|
|
46
|
+
readonly expose = false;
|
|
47
|
+
constructor();
|
|
48
|
+
}
|
|
30
49
|
export declare class MemoryPasskeyStore implements PasskeyStore {
|
|
31
50
|
private readonly byId;
|
|
32
51
|
add(credential: PasskeyCredential): Promise<void>;
|
|
33
52
|
get(credentialId: string): Promise<PasskeyCredential | null>;
|
|
34
53
|
forUser(userId: string): Promise<PasskeyCredential[]>;
|
|
54
|
+
compareAndSetCounter(credentialId: string, expected: number, next: number, lastUsedAt: number): Promise<boolean>;
|
|
55
|
+
/** @deprecated See {@link PasskeyStore.updateCounter}. */
|
|
35
56
|
updateCounter(credentialId: string, counter: number, lastUsedAt: number): Promise<void>;
|
|
36
57
|
remove(credentialId: string): Promise<void>;
|
|
37
58
|
}
|
|
38
59
|
/** A stored challenge plus the subject (user id) it was issued for, if any. */
|
|
39
60
|
export interface StoredChallenge {
|
|
40
61
|
challenge: string;
|
|
41
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* The user the challenge is bound to — enforced at finish: a registration
|
|
64
|
+
* binds the new passkey to this user, an authentication started for a user
|
|
65
|
+
* only accepts that user's passkeys.
|
|
66
|
+
*/
|
|
42
67
|
userId?: string;
|
|
43
68
|
}
|
|
44
69
|
export interface WebAuthnChallengeStore {
|
|
@@ -165,7 +190,12 @@ export interface WebAuthnConfig {
|
|
|
165
190
|
origin: string | string[];
|
|
166
191
|
/** Challenge TTL in ms. Default 5 minutes. */
|
|
167
192
|
challengeTtlMs?: number;
|
|
168
|
-
/**
|
|
193
|
+
/**
|
|
194
|
+
* User-verification requirement. Default `'preferred'` (the WebAuthn default):
|
|
195
|
+
* an authenticator without a PIN/biometric can still sign, so the assertion
|
|
196
|
+
* proves possession only. Set `'required'` when a passkey is the ONLY factor
|
|
197
|
+
* (passwordless login) and you need two factors in one gesture.
|
|
198
|
+
*/
|
|
169
199
|
userVerification?: 'required' | 'preferred' | 'discouraged';
|
|
170
200
|
/** Ceremony timeout advertised to the browser, ms. Default 60s. */
|
|
171
201
|
timeoutMs?: number;
|
|
@@ -201,12 +231,18 @@ export declare class WebAuthnService {
|
|
|
201
231
|
}): Promise<RegistrationOptions>;
|
|
202
232
|
/** Verify a registration response and store the new passkey. Throws on failure. */
|
|
203
233
|
finishRegistration(sessionKey: string, userId: string, response: unknown, deviceName?: string): Promise<PasskeyCredential>;
|
|
204
|
-
/**
|
|
234
|
+
/**
|
|
235
|
+
* Authentication options; omit `userId` for discoverable login. With a
|
|
236
|
+
* `userId` (step-up, re-authentication) the challenge is bound to that user:
|
|
237
|
+
* {@link finishAuthentication} then refuses a passkey that belongs to anyone
|
|
238
|
+
* else, and `allowCredentials` lists only that user's passkeys.
|
|
239
|
+
*/
|
|
205
240
|
startAuthentication(sessionKey: string, userId?: string): Promise<AuthenticationOptions>;
|
|
206
241
|
/**
|
|
207
242
|
* Verify an authentication response. Looks the credential up by its id, checks
|
|
208
|
-
* the signature counter increased (clone detection), persists the new counter
|
|
209
|
-
* and
|
|
243
|
+
* the signature counter increased (clone detection), persists the new counter
|
|
244
|
+
* with a compare-and-set (so two concurrent assertions cannot both pass), and
|
|
245
|
+
* returns whose passkey authenticated. Throws on any failure.
|
|
210
246
|
*/
|
|
211
247
|
finishAuthentication(sessionKey: string, response: unknown): Promise<{
|
|
212
248
|
userId: string;
|
|
@@ -214,6 +250,11 @@ export declare class WebAuthnService {
|
|
|
214
250
|
}>;
|
|
215
251
|
/** A user's registered passkeys (for a "manage devices" screen). */
|
|
216
252
|
list(userId: string): Promise<PasskeyCredential[]>;
|
|
217
|
-
/**
|
|
218
|
-
|
|
253
|
+
/**
|
|
254
|
+
* Remove one of `userId`'s passkeys (revoke a device). The credential must
|
|
255
|
+
* belong to `userId`: a credential id is not an authorization, so an id that
|
|
256
|
+
* is unknown or owned by another user throws {@link PasskeyNotFoundError}
|
|
257
|
+
* (the same error for both, so the call cannot probe other users' devices).
|
|
258
|
+
*/
|
|
259
|
+
remove(userId: string, credentialId: string): Promise<void>;
|
|
219
260
|
}
|