@basaltkit/auth 1.5.0 → 1.6.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,248 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { BasaltError } from '@basaltkit/core';
3
+ export class MemoryPasskeyStore {
4
+ byId = new Map();
5
+ async add(credential) {
6
+ this.byId.set(credential.id, { ...credential });
7
+ }
8
+ async get(credentialId) {
9
+ const found = this.byId.get(credentialId);
10
+ return found ? { ...found } : null;
11
+ }
12
+ async forUser(userId) {
13
+ return [...this.byId.values()].filter((c) => c.userId === userId).map((c) => ({ ...c }));
14
+ }
15
+ async updateCounter(credentialId, counter, lastUsedAt) {
16
+ const found = this.byId.get(credentialId);
17
+ if (found) {
18
+ found.counter = counter;
19
+ found.lastUsedAt = lastUsedAt;
20
+ }
21
+ }
22
+ async remove(credentialId) {
23
+ this.byId.delete(credentialId);
24
+ }
25
+ }
26
+ export class MemoryWebAuthnChallengeStore {
27
+ entries = new Map();
28
+ now;
29
+ maxEntries;
30
+ constructor(options = {}) {
31
+ this.now = options.now ?? (() => Date.now());
32
+ this.maxEntries = options.maxEntries ?? 10_000;
33
+ }
34
+ async save(key, value, expiresAt) {
35
+ // Purge expired entries so unconsumed challenges cannot accumulate (DoS),
36
+ // and cap total size with FIFO eviction as a hard backstop.
37
+ const now = this.now();
38
+ for (const [k, entry] of this.entries) {
39
+ if (entry.expiresAt <= now)
40
+ this.entries.delete(k);
41
+ }
42
+ while (this.entries.size >= this.maxEntries) {
43
+ const oldest = this.entries.keys().next().value;
44
+ if (oldest === undefined)
45
+ break;
46
+ this.entries.delete(oldest);
47
+ }
48
+ this.entries.set(key, { value, expiresAt });
49
+ }
50
+ async take(key) {
51
+ const entry = this.entries.get(key);
52
+ if (!entry)
53
+ return null;
54
+ this.entries.delete(key);
55
+ return entry.expiresAt > this.now() ? entry.value : null;
56
+ }
57
+ }
58
+ // ES256 and RS256 — the pair virtually every authenticator supports.
59
+ const DEFAULT_PUB_KEY_PARAMS = [
60
+ { type: 'public-key', alg: -7 },
61
+ { type: 'public-key', alg: -257 },
62
+ ];
63
+ // --- errors ---------------------------------------------------------------
64
+ export class WebAuthnChallengeError extends BasaltError {
65
+ status = 400;
66
+ constructor() {
67
+ super('WEBAUTHN_CHALLENGE_INVALID', 'No matching WebAuthn challenge — it expired or was already used.');
68
+ }
69
+ }
70
+ export class WebAuthnVerificationError extends BasaltError {
71
+ status = 400;
72
+ constructor() {
73
+ super('WEBAUTHN_VERIFICATION_FAILED', 'The WebAuthn response could not be verified.');
74
+ }
75
+ }
76
+ export class PasskeyNotFoundError extends BasaltError {
77
+ status = 404;
78
+ constructor() {
79
+ super('PASSKEY_NOT_FOUND', 'No passkey matches the presented credential.');
80
+ }
81
+ }
82
+ export class PasskeyClonedError extends BasaltError {
83
+ status = 401;
84
+ constructor() {
85
+ super('PASSKEY_CLONED', 'Signature counter did not increase — the authenticator may be cloned.');
86
+ }
87
+ }
88
+ export class PasskeyExistsError extends BasaltError {
89
+ status = 409;
90
+ constructor() {
91
+ super('PASSKEY_EXISTS', 'This credential is already registered.');
92
+ }
93
+ }
94
+ export class WebAuthnSubjectMismatchError extends BasaltError {
95
+ status = 403;
96
+ constructor() {
97
+ super('WEBAUTHN_SUBJECT_MISMATCH', 'The challenge was issued for a different user — refusing to bind the passkey.');
98
+ }
99
+ }
100
+ export class WebAuthnService {
101
+ config;
102
+ credentials;
103
+ challenges;
104
+ verifier;
105
+ now;
106
+ randomChallenge;
107
+ constructor(options) {
108
+ this.config = options.config;
109
+ this.credentials = options.credentials;
110
+ this.challenges = options.challenges;
111
+ this.verifier = options.verifier;
112
+ this.now = options.now ?? (() => Date.now());
113
+ this.randomChallenge = options.randomChallenge ?? (() => randomBytes(32).toString('base64url'));
114
+ }
115
+ get uv() {
116
+ return this.config.userVerification ?? 'preferred';
117
+ }
118
+ get timeout() {
119
+ return this.config.timeoutMs ?? 60_000;
120
+ }
121
+ // Challenges are namespaced per ceremony so a registration and an
122
+ // authentication on the same sessionKey never clobber or cross-consume.
123
+ challengeKey(kind, sessionKey) {
124
+ return `${kind}:${sessionKey}`;
125
+ }
126
+ async issueChallenge(kind, sessionKey, userId) {
127
+ const challenge = this.randomChallenge();
128
+ const value = userId === undefined ? { challenge } : { challenge, userId };
129
+ await this.challenges.save(this.challengeKey(kind, sessionKey), value, this.now() + (this.config.challengeTtlMs ?? 300_000));
130
+ return challenge;
131
+ }
132
+ /** Registration options for a known user; stores the challenge bound to `user.id`. */
133
+ async startRegistration(sessionKey, user) {
134
+ const challenge = await this.issueChallenge('reg', sessionKey, user.id);
135
+ const existing = await this.credentials.forUser(user.id);
136
+ return {
137
+ challenge,
138
+ rp: { id: this.config.rpId, name: this.config.rpName },
139
+ user: { id: user.id, name: user.name, displayName: user.displayName ?? user.name },
140
+ pubKeyCredParams: this.config.pubKeyCredParams ?? DEFAULT_PUB_KEY_PARAMS,
141
+ timeout: this.timeout,
142
+ attestation: 'none',
143
+ excludeCredentials: existing.map((c) => ({
144
+ type: 'public-key',
145
+ id: c.id,
146
+ ...(c.transports ? { transports: c.transports } : {}),
147
+ })),
148
+ authenticatorSelection: { userVerification: this.uv, residentKey: 'preferred' },
149
+ };
150
+ }
151
+ /** Verify a registration response and store the new passkey. Throws on failure. */
152
+ async finishRegistration(sessionKey, userId, response, deviceName) {
153
+ const stored = await this.challenges.take(this.challengeKey('reg', sessionKey));
154
+ if (!stored)
155
+ throw new WebAuthnChallengeError();
156
+ // The challenge is bound to the user it was issued for; refuse to bind the
157
+ // new passkey to any other account (prevents adding an attacker's
158
+ // authenticator to a victim's account via a caller-supplied userId).
159
+ if (stored.userId !== undefined && stored.userId !== userId) {
160
+ throw new WebAuthnSubjectMismatchError();
161
+ }
162
+ const result = await this.verifier.verifyRegistration({
163
+ response,
164
+ expectedChallenge: stored.challenge,
165
+ expectedOrigin: this.config.origin,
166
+ expectedRpId: this.config.rpId,
167
+ requireUserVerification: this.uv === 'required',
168
+ });
169
+ if (!result.verified || !result.credential)
170
+ throw new WebAuthnVerificationError();
171
+ // Never overwrite an existing credential record (a collided/duplicate
172
+ // credential id must not rebind or clobber another registration).
173
+ if (await this.credentials.get(result.credential.id))
174
+ throw new PasskeyExistsError();
175
+ const credential = {
176
+ id: result.credential.id,
177
+ userId,
178
+ publicKey: result.credential.publicKey,
179
+ counter: result.credential.counter,
180
+ ...(result.credential.transports ? { transports: result.credential.transports } : {}),
181
+ ...(deviceName ? { deviceName } : {}),
182
+ createdAt: this.now(),
183
+ };
184
+ await this.credentials.add(credential);
185
+ return credential;
186
+ }
187
+ /** Authentication options; `userId` narrows allowCredentials, omit it for discoverable login. */
188
+ async startAuthentication(sessionKey, userId) {
189
+ const challenge = await this.issueChallenge('auth', sessionKey);
190
+ const creds = userId ? await this.credentials.forUser(userId) : [];
191
+ return {
192
+ challenge,
193
+ timeout: this.timeout,
194
+ rpId: this.config.rpId,
195
+ userVerification: this.uv,
196
+ allowCredentials: creds.map((c) => ({
197
+ type: 'public-key',
198
+ id: c.id,
199
+ ...(c.transports ? { transports: c.transports } : {}),
200
+ })),
201
+ };
202
+ }
203
+ /**
204
+ * Verify an authentication response. Looks the credential up by its id, checks
205
+ * the signature counter increased (clone detection), persists the new counter,
206
+ * and returns whose passkey authenticated. Throws on any failure.
207
+ */
208
+ async finishAuthentication(sessionKey, response) {
209
+ const rawId = response?.id;
210
+ if (typeof rawId !== 'string' || rawId.length === 0 || rawId.length > 512) {
211
+ throw new PasskeyNotFoundError();
212
+ }
213
+ const credentialId = rawId;
214
+ // Consume the challenge FIRST so a failed lookup still burns the nonce and
215
+ // the endpoint cannot be used as an unauthenticated credential-existence oracle.
216
+ const stored = await this.challenges.take(this.challengeKey('auth', sessionKey));
217
+ if (!stored)
218
+ throw new WebAuthnChallengeError();
219
+ const credential = await this.credentials.get(credentialId);
220
+ if (!credential)
221
+ throw new PasskeyNotFoundError();
222
+ const result = await this.verifier.verifyAuthentication({
223
+ response,
224
+ expectedChallenge: stored.challenge,
225
+ expectedOrigin: this.config.origin,
226
+ expectedRpId: this.config.rpId,
227
+ requireUserVerification: this.uv === 'required',
228
+ credential: { id: credential.id, publicKey: credential.publicKey, counter: credential.counter },
229
+ });
230
+ if (!result.verified)
231
+ throw new WebAuthnVerificationError();
232
+ // Clone detection: a real authenticator's counter strictly increases. Some
233
+ // report 0 forever — only enforce when the stored counter is non-zero.
234
+ if (credential.counter > 0 && result.newCounter <= credential.counter) {
235
+ throw new PasskeyClonedError();
236
+ }
237
+ await this.credentials.updateCounter(credential.id, result.newCounter, this.now());
238
+ return { userId: credential.userId, credentialId: credential.id };
239
+ }
240
+ /** A user's registered passkeys (for a "manage devices" screen). */
241
+ async list(userId) {
242
+ return this.credentials.forUser(userId);
243
+ }
244
+ /** Remove a passkey (revoke a device). */
245
+ async remove(credentialId) {
246
+ await this.credentials.remove(credentialId);
247
+ }
248
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "1.5.0",
3
+ "version": "1.6.1",
4
4
  "description": "Authentication for Basalt: password hashing, JWT with refresh rotation and reuse detection, sessions, ready-made /auth routes and route guards.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -14,18 +14,17 @@
14
14
  "dist"
15
15
  ],
16
16
  "dependencies": {
17
- "@basaltkit/core": "^1.1.0",
18
- "@basaltkit/fastify": "^1.5.0"
17
+ "@basaltkit/core": "^1.1.1",
18
+ "@basaltkit/fastify": "^1.6.0"
19
19
  },
20
20
  "peerDependencies": {
21
21
  "zod": "^3.24.0 || ^4.0.0"
22
22
  },
23
23
  "devDependencies": {
24
- "@types/node": "^22.15.0",
25
- "tsup": "^8.4.0",
26
- "typescript": "^5.8.0",
27
- "vitest": "^3.1.0",
28
- "zod": "^3.24.0",
24
+ "@types/node": "^26.3.0",
25
+ "typescript": "^7.0.2",
26
+ "vitest": "^4.1.11",
27
+ "zod": "^3.24.0 || ^4.0.0",
29
28
  "@basaltkit/tsconfig": "^0.24.0"
30
29
  },
31
30
  "publishConfig": {
@@ -33,11 +32,11 @@
33
32
  },
34
33
  "repository": {
35
34
  "type": "git",
36
- "url": "git+https://github.com/Zebedeu/basalt.git",
35
+ "url": "git+https://github.com/basaltkit/basalt.git",
37
36
  "directory": "packages/auth"
38
37
  },
39
- "homepage": "https://github.com/Zebedeu/basalt/tree/main/packages/auth#readme",
40
- "bugs": "https://github.com/Zebedeu/basalt/issues",
38
+ "homepage": "https://github.com/basaltkit/basalt/tree/main/packages/auth#readme",
39
+ "bugs": "https://github.com/basaltkit/basalt/issues",
41
40
  "keywords": [
42
41
  "basalt",
43
42
  "typescript",
@@ -46,7 +45,7 @@
46
45
  "jwt"
47
46
  ],
48
47
  "scripts": {
49
- "build": "tsup src/index.ts --format esm --dts --clean",
48
+ "build": "tsc -p tsconfig.build.json",
50
49
  "test": "vitest run",
51
50
  "typecheck": "tsc --noEmit"
52
51
  }