@basaltkit/auth 1.6.4 → 1.8.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 CHANGED
@@ -350,6 +350,8 @@ const app = await createApp({
350
350
  }).boot()
351
351
  ```
352
352
 
353
+ `apiKeysPlugin` claims the `scopes` key in the adapters' boot-time guarded-meta check, so a route declaring `meta.scopes` **without** the plugin registered fails loud at boot (`UnguardedRouteMetaError`) instead of serving unchecked.
354
+
353
355
  The key is presented in the `Authorization: Bearer mk_live_...` or `x-api-key` header. A **scope** is a granular permission on the key (e.g. `reports:read`); `*` means all. After authenticating, `ctx().apiKey` contains `{ id, scopes, tenantId?, userId? }`.
354
356
 
355
357
  ### Brute-force lockout (LoginThrottle)
@@ -383,12 +385,12 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
383
385
  | `secret` | `string` | Yes | — | Secret that signs the JWTs (HS256). |
384
386
  | `hasher` | `PasswordHasher` | No | `ScryptPasswordHasher` | Password hashing algorithm. |
385
387
  | `sessions` | `SessionStore` | No | `MemorySessionStore` | Session storage. |
386
- | `refreshTokens` | `RefreshTokenStore` | No | `MemoryRefreshTokenStore` | Refresh token storage. |
388
+ | `refreshTokens` | `RefreshTokenStore` | No | `MemoryRefreshTokenStore` | Refresh token storage. `markUsed` must be a **compare-and-swap** — see below. |
387
389
  | `accessTtl` | `DurationInput` | No | `'15m'` | Access token validity. |
388
390
  | `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
389
391
  | `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
390
392
  | `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
391
- | `tokens` | `AuthTokenStore` | No | `MemoryAuthTokenStore` | Verification/reset tokens. |
393
+ | `tokens` | `AuthTokenStore` | No | `MemoryAuthTokenStore` | Verification/reset tokens. `markUsed` must be a **compare-and-swap** — see below. |
392
394
  | `verificationTtl` | `DurationInput` | No | `'24h'` | Email verification link validity. |
393
395
  | `resetTtl` | `DurationInput` | No | `'1h'` | Password reset link validity. |
394
396
  | `mfa` | `MfaStore` | No | `MemoryMfaStore` | Per-user MFA state. |
@@ -446,6 +448,14 @@ Options (`ApiKeysPluginOptions`):
446
448
  | `googleProvider`, `githubProvider`, `oidcProvider`, `discoverOidcProvider` | OAuth 2.0 / OpenID Connect providers. Each takes `{ clientId, clientSecret, scopes? }`. |
447
449
  | In-memory stores | `MemoryUserSource`, `MemorySessionStore`, `MemoryRefreshTokenStore`, `MemoryAuthTokenStore`, `MemoryApiKeyStore`, `MemoryMfaStore` — dev/testing. |
448
450
 
451
+ #### Single-use tokens are consumed with a compare-and-swap
452
+
453
+ `AuthTokenStore.markUsed` and `RefreshTokenStore.markUsed` return `Promise<boolean | void>`: mark the token used **only if it is still unused**, and return whether *this* call did it. `Auth.refresh()` treats `false` as reuse — it revokes the family and throws `AUTH_REFRESH_REUSED`; the verification/reset path treats it as a spent token (`AUTH_TOKEN_INVALID`).
454
+
455
+ This matters because `refresh()` reads the record, checks `usedAt`, then writes. With an unconditional `UPDATE … WHERE token = ?` those are two operations, so two concurrent refreshes of the same token — the legitimate client and a thief racing it — both read `usedAt = null` and both succeed, and reuse detection never fires. The shipped stores use a conditional update (`WHERE token = ? AND used_at IS NULL`, `where: { token, usedAt: null }`) and report the affected row count.
456
+
457
+ If you implement your own store, do the same. Returning `void` keeps the older read-then-write behaviour: it still compiles and runs, but without the race protection.
458
+
449
459
  ### Exported errors
450
460
 
451
461
  | Error | Code | HTTP |
@@ -51,6 +51,9 @@ export function apiKeysPlugin(options = {}) {
51
51
  }
52
52
  };
53
53
  metadata.add('http:guards', guard);
54
+ // Claim `meta.scopes` for the adapters' boot-time guarded-meta check —
55
+ // a scope-gated route without this plugin would serve unchecked.
56
+ metadata.add('http:guarded-meta', 'scopes');
54
57
  },
55
58
  });
56
59
  }
package/dist/auth.js CHANGED
@@ -274,7 +274,12 @@ export class Auth {
274
274
  }
275
275
  if (Date.now() >= record.expiresAt)
276
276
  throw new RefreshInvalidError();
277
- await this.refreshTokens.markUsed(hashed);
277
+ // Compare-and-swap: `false` means another caller consumed this exact token
278
+ // between our read and this write — the very race reuse detection exists for.
279
+ if ((await this.refreshTokens.markUsed(hashed)) === false) {
280
+ await this.refreshTokens.revokeFamily(record.familyId);
281
+ throw new RefreshReusedError();
282
+ }
278
283
  return this.issueTokens(record.userId, record.familyId);
279
284
  }
280
285
  /** Revokes a refresh family — logout for token-based clients. */
@@ -506,7 +511,10 @@ export class Auth {
506
511
  if (!record || record.purpose !== purpose || record.usedAt !== undefined || Date.now() >= record.expiresAt) {
507
512
  throw new AuthTokenInvalidError();
508
513
  }
509
- await this.tokens.markUsed(hashed);
514
+ // Compare-and-swap: a concurrent consumer of this single-use token wins, and
515
+ // this call is rejected as if the token had already been spent.
516
+ if ((await this.tokens.markUsed(hashed)) === false)
517
+ throw new AuthTokenInvalidError();
510
518
  return record;
511
519
  }
512
520
  async updateUser(id, patch) {
package/dist/stores.d.ts CHANGED
@@ -46,7 +46,14 @@ export interface AuthTokenRecord {
46
46
  export interface AuthTokenStore {
47
47
  create(record: AuthTokenRecord): Promise<void>;
48
48
  find(token: string): Promise<AuthTokenRecord | null>;
49
- markUsed(token: string): Promise<void>;
49
+ /**
50
+ * Consumes the token. MUST be a compare-and-swap: mark it used only if it is
51
+ * still unused, and return whether THIS call did the consuming — `false` means
52
+ * a concurrent caller got there first. Returning `void` keeps the pre-CAS
53
+ * behaviour (the caller then trusts its earlier read), so third-party stores
54
+ * written against the old contract keep working, without the race protection.
55
+ */
56
+ markUsed(token: string): Promise<boolean | void>;
50
57
  /** Invalidate outstanding tokens of a purpose for a user before issuing a new one. */
51
58
  deleteForUser(userId: string, purpose: AuthTokenPurpose): Promise<void>;
52
59
  }
@@ -54,7 +61,7 @@ export declare class MemoryAuthTokenStore implements AuthTokenStore {
54
61
  private readonly records;
55
62
  create(record: AuthTokenRecord): Promise<void>;
56
63
  find(token: string): Promise<AuthTokenRecord | null>;
57
- markUsed(token: string): Promise<void>;
64
+ markUsed(token: string): Promise<boolean>;
58
65
  deleteForUser(userId: string, purpose: AuthTokenPurpose): Promise<void>;
59
66
  }
60
67
  /**
@@ -180,7 +187,14 @@ export interface RefreshRecord {
180
187
  export interface RefreshTokenStore {
181
188
  create(record: RefreshRecord): Promise<void>;
182
189
  find(token: string): Promise<RefreshRecord | null>;
183
- markUsed(token: string): Promise<void>;
190
+ /**
191
+ * Consumes the refresh token. MUST be a compare-and-swap: mark it used only if
192
+ * it is still unused, and return whether THIS call did the consuming. Reuse
193
+ * detection depends on it — a plain `UPDATE … WHERE token = ?` lets two
194
+ * concurrent refreshes of a stolen+legitimate token both succeed. Returning
195
+ * `void` keeps the pre-CAS behaviour for stores written against the old contract.
196
+ */
197
+ markUsed(token: string): Promise<boolean | void>;
184
198
  /** Revokes every token of a family — fired on reuse detection. */
185
199
  revokeFamily(familyId: string): Promise<void>;
186
200
  /** Revokes every token of a user — fired on password reset. Optional. */
@@ -190,7 +204,7 @@ export declare class MemoryRefreshTokenStore implements RefreshTokenStore {
190
204
  private readonly records;
191
205
  create(record: RefreshRecord): Promise<void>;
192
206
  find(token: string): Promise<RefreshRecord | null>;
193
- markUsed(token: string): Promise<void>;
207
+ markUsed(token: string): Promise<boolean>;
194
208
  revokeFamily(familyId: string): Promise<void>;
195
209
  revokeAllForUser(userId: string): Promise<void>;
196
210
  }
package/dist/stores.js CHANGED
@@ -36,8 +36,10 @@ export class MemoryAuthTokenStore {
36
36
  }
37
37
  async markUsed(token) {
38
38
  const record = this.records.get(token);
39
- if (record)
40
- record.usedAt = Date.now();
39
+ if (!record || record.usedAt !== undefined)
40
+ return false;
41
+ record.usedAt = Date.now();
42
+ return true;
41
43
  }
42
44
  async deleteForUser(userId, purpose) {
43
45
  for (const [token, record] of this.records) {
@@ -151,8 +153,10 @@ export class MemoryRefreshTokenStore {
151
153
  }
152
154
  async markUsed(token) {
153
155
  const record = this.records.get(token);
154
- if (record)
155
- record.usedAt = Date.now();
156
+ if (!record || record.usedAt !== undefined)
157
+ return false;
158
+ record.usedAt = Date.now();
159
+ return true;
156
160
  }
157
161
  async revokeFamily(familyId) {
158
162
  for (const [token, record] of this.records) {
package/package.json CHANGED
@@ -1,9 +1,13 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "1.6.4",
3
+ "version": "1.8.0",
4
+ "engines": {
5
+ "node": ">=22.5.0"
6
+ },
4
7
  "description": "Authentication for Basalt: password hashing, JWT with refresh rotation and reuse detection, sessions, ready-made /auth routes and route guards.",
5
8
  "license": "MIT",
6
9
  "type": "module",
10
+ "sideEffects": false,
7
11
  "exports": {
8
12
  ".": {
9
13
  "types": "./dist/index.d.ts",
@@ -14,8 +18,8 @@
14
18
  "dist"
15
19
  ],
16
20
  "dependencies": {
17
- "@basaltkit/core": "^1.3.0",
18
- "@basaltkit/http": "^1.12.0"
21
+ "@basaltkit/core": "^1.3.1",
22
+ "@basaltkit/http": "^1.14.0"
19
23
  },
20
24
  "peerDependencies": {
21
25
  "zod": "^3.24.0 || ^4.0.0"
@@ -25,7 +29,7 @@
25
29
  "typescript": "^7.0.2",
26
30
  "vitest": "^4.1.11",
27
31
  "zod": "^3.24.0 || ^4.0.0",
28
- "@basaltkit/fastify": "^1.8.0",
32
+ "@basaltkit/fastify": "^1.8.1",
29
33
  "@basaltkit/tsconfig": "^0.24.0"
30
34
  },
31
35
  "publishConfig": {