@basaltkit/auth 1.7.0 → 2.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 +10 -2
- package/dist/auth.js +10 -2
- package/dist/index.d.ts +7 -1
- package/dist/index.js +1 -1
- package/dist/routes.d.ts +22 -1
- package/dist/routes.js +16 -3
- package/dist/stores.d.ts +18 -4
- package/dist/stores.js +8 -4
- package/package.json +11 -7
package/README.md
CHANGED
|
@@ -385,12 +385,12 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
385
385
|
| `secret` | `string` | Yes | — | Secret that signs the JWTs (HS256). |
|
|
386
386
|
| `hasher` | `PasswordHasher` | No | `ScryptPasswordHasher` | Password hashing algorithm. |
|
|
387
387
|
| `sessions` | `SessionStore` | No | `MemorySessionStore` | Session storage. |
|
|
388
|
-
| `refreshTokens` | `RefreshTokenStore` | No | `MemoryRefreshTokenStore` | Refresh token storage. |
|
|
388
|
+
| `refreshTokens` | `RefreshTokenStore` | No | `MemoryRefreshTokenStore` | Refresh token storage. `markUsed` must be a **compare-and-swap** — see below. |
|
|
389
389
|
| `accessTtl` | `DurationInput` | No | `'15m'` | Access token validity. |
|
|
390
390
|
| `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
|
|
391
391
|
| `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
|
|
392
392
|
| `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
|
|
393
|
-
| `tokens` | `AuthTokenStore` | No | `MemoryAuthTokenStore` | Verification/reset tokens. |
|
|
393
|
+
| `tokens` | `AuthTokenStore` | No | `MemoryAuthTokenStore` | Verification/reset tokens. `markUsed` must be a **compare-and-swap** — see below. |
|
|
394
394
|
| `verificationTtl` | `DurationInput` | No | `'24h'` | Email verification link validity. |
|
|
395
395
|
| `resetTtl` | `DurationInput` | No | `'1h'` | Password reset link validity. |
|
|
396
396
|
| `mfa` | `MfaStore` | No | `MemoryMfaStore` | Per-user MFA state. |
|
|
@@ -448,6 +448,14 @@ Options (`ApiKeysPluginOptions`):
|
|
|
448
448
|
| `googleProvider`, `githubProvider`, `oidcProvider`, `discoverOidcProvider` | OAuth 2.0 / OpenID Connect providers. Each takes `{ clientId, clientSecret, scopes? }`. |
|
|
449
449
|
| In-memory stores | `MemoryUserSource`, `MemorySessionStore`, `MemoryRefreshTokenStore`, `MemoryAuthTokenStore`, `MemoryApiKeyStore`, `MemoryMfaStore` — dev/testing. |
|
|
450
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
|
+
|
|
451
459
|
### Exported errors
|
|
452
460
|
|
|
453
461
|
| Error | Code | HTTP |
|
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
|
-
|
|
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
|
-
|
|
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/index.d.ts
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
export { ScryptPasswordHasher, type PasswordHasher } from './hashing.js';
|
|
2
2
|
export { signJwt, verifyJwt, TokenInvalidError, TokenExpiredError, type JwtClaims, } from './jwt.js';
|
|
3
3
|
export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, type TokenVersionStore, type AuthUser, type PublicUser, type UserSource, type UserPatch, type SessionStore, type SessionRecord, type RefreshTokenStore, type RefreshRecord, type AuthTokenStore, type AuthTokenRecord, type AuthTokenPurpose, type ApiKeyStore, type ApiKeyRecord, type ApiKeyInfo, type ApiKeyFilter, type MfaStore, type MfaRecord, } from './stores.js';
|
|
4
|
+
declare module '@basaltkit/http' {
|
|
5
|
+
interface RouteMeta {
|
|
6
|
+
/** `true` requires a session; `false` opts a route out. */
|
|
7
|
+
auth?: boolean;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
4
10
|
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, type AuthOptions, type TokenPair, } from './auth.js';
|
|
5
11
|
export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, type TotpOptions, type VerifyTotpOptions, type OtpauthUriInput, } from './totp.js';
|
|
6
12
|
export { authPlugin, AUTH, type AuthPluginOptions } from './plugin.js';
|
|
7
13
|
export { ApiKeys, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
|
|
8
14
|
export { apiKeysPlugin, API_KEYS, type ApiKeysPluginOptions } from './apikeys-plugin.js';
|
|
9
|
-
export { authRoutes, apiKeyRoutes, mfaRoutes } from './routes.js';
|
|
15
|
+
export { authRoutes, apiKeyRoutes, mfaRoutes, type AuthRoutesOptions, type PasswordPolicy, } from './routes.js';
|
|
10
16
|
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, type OAuthProvider, type OAuthProfile, type OAuthOptions, } from './oauth.js';
|
|
11
17
|
export { oauthPlugin, oauthRoutes, OAUTH, type OAuthPluginOptions, type OAuthRoutesOptions, } from './oauth-plugin.js';
|
|
12
18
|
export { LoginThrottle, AccountLockedError, type LoginThrottleOptions } from './throttle.js';
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, match
|
|
|
6
6
|
export { authPlugin, AUTH } from './plugin.js';
|
|
7
7
|
export { ApiKeys, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
|
|
8
8
|
export { apiKeysPlugin, API_KEYS } from './apikeys-plugin.js';
|
|
9
|
-
export { authRoutes, apiKeyRoutes, mfaRoutes } from './routes.js';
|
|
9
|
+
export { authRoutes, apiKeyRoutes, mfaRoutes, } from './routes.js';
|
|
10
10
|
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, } from './oauth.js';
|
|
11
11
|
export { oauthPlugin, oauthRoutes, OAUTH, } from './oauth-plugin.js';
|
|
12
12
|
export { LoginThrottle, AccountLockedError } from './throttle.js';
|
package/dist/routes.d.ts
CHANGED
|
@@ -1,4 +1,25 @@
|
|
|
1
1
|
import { type BasaltRoute } from '@basaltkit/http';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
/**
|
|
4
|
+
* How strong a password has to be.
|
|
5
|
+
*
|
|
6
|
+
* The rule was `min(8)`, fixed, with no way to change it — the 2012 minimum, in
|
|
7
|
+
* routes an application either uses as they are or replaces wholesale. One that
|
|
8
|
+
* needed more reached into the route's Zod object and swapped the field,
|
|
9
|
+
* depending on the internal shape of a body it does not own.
|
|
10
|
+
*
|
|
11
|
+
* A whole schema and not just a number, because the interesting rules are not
|
|
12
|
+
* lengths: "at least one symbol", "not the email address", "not in a breach
|
|
13
|
+
* list". An option taking only a number would send those applications straight
|
|
14
|
+
* back to patching.
|
|
15
|
+
*/
|
|
16
|
+
export interface PasswordPolicy {
|
|
17
|
+
minLength?: number;
|
|
18
|
+
}
|
|
19
|
+
export interface AuthRoutesOptions {
|
|
20
|
+
/** A minimum length, or the schema itself. Default: `min(8)`. */
|
|
21
|
+
password?: PasswordPolicy | z.ZodType<string>;
|
|
22
|
+
}
|
|
2
23
|
/**
|
|
3
24
|
* Ready-made auth routes — register them in fastifyPlugin({ routes }):
|
|
4
25
|
* register · login · refresh · logout · me, plus email verification
|
|
@@ -6,7 +27,7 @@ import { type BasaltRoute } from '@basaltkit/http';
|
|
|
6
27
|
* (`/auth/password/forgot`, `/auth/password/reset`).
|
|
7
28
|
* Every one is a plain BasaltRoute: replace or omit any of them freely.
|
|
8
29
|
*/
|
|
9
|
-
export declare function authRoutes(): BasaltRoute[];
|
|
30
|
+
export declare function authRoutes(options?: AuthRoutesOptions): BasaltRoute[];
|
|
10
31
|
/**
|
|
11
32
|
* CRUD routes for API keys, all requiring a logged-in user (`meta.auth`). Keys
|
|
12
33
|
* are scoped to the caller's tenant (`ctx().tenant`) and user; a caller only
|
package/dist/routes.js
CHANGED
|
@@ -3,7 +3,15 @@ import { route } from '@basaltkit/http';
|
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { AUTH } from './plugin.js';
|
|
5
5
|
import { API_KEYS } from './apikeys-plugin.js';
|
|
6
|
-
const
|
|
6
|
+
const DEFAULT_PASSWORD = z.string().min(8);
|
|
7
|
+
const passwordSchema = (policy) => {
|
|
8
|
+
if (!policy)
|
|
9
|
+
return DEFAULT_PASSWORD;
|
|
10
|
+
if (typeof policy.safeParse === 'function')
|
|
11
|
+
return policy;
|
|
12
|
+
const { minLength } = policy;
|
|
13
|
+
return minLength === undefined ? DEFAULT_PASSWORD : z.string().min(minLength);
|
|
14
|
+
};
|
|
7
15
|
const auth = () => ctx().container.get(AUTH);
|
|
8
16
|
const apiKeys = () => ctx().container.get(API_KEYS);
|
|
9
17
|
/**
|
|
@@ -13,7 +21,9 @@ const apiKeys = () => ctx().container.get(API_KEYS);
|
|
|
13
21
|
* (`/auth/password/forgot`, `/auth/password/reset`).
|
|
14
22
|
* Every one is a plain BasaltRoute: replace or omit any of them freely.
|
|
15
23
|
*/
|
|
16
|
-
export function authRoutes() {
|
|
24
|
+
export function authRoutes(options = {}) {
|
|
25
|
+
const password = passwordSchema(options.password);
|
|
26
|
+
const credentials = z.object({ email: z.string().email(), password });
|
|
17
27
|
return [
|
|
18
28
|
route({
|
|
19
29
|
method: 'POST',
|
|
@@ -93,7 +103,10 @@ export function authRoutes() {
|
|
|
93
103
|
route({
|
|
94
104
|
method: 'POST',
|
|
95
105
|
url: '/auth/password/reset',
|
|
96
|
-
|
|
106
|
+
// The same policy as register. Covering register and leaving reset behind
|
|
107
|
+
// would let anyone walk a strong password back down to eight characters
|
|
108
|
+
// through "forgot password" — a loophole worse than having no option.
|
|
109
|
+
body: z.object({ token: z.string(), password }),
|
|
97
110
|
async handler({ body }) {
|
|
98
111
|
await auth().resetPassword(body.token, body.password);
|
|
99
112
|
return { ok: true };
|
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
|
-
|
|
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<
|
|
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
|
-
|
|
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<
|
|
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
|
-
|
|
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
|
-
|
|
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": "
|
|
3
|
+
"version": "2.0.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,18 +18,18 @@
|
|
|
14
18
|
"dist"
|
|
15
19
|
],
|
|
16
20
|
"dependencies": {
|
|
17
|
-
"@basaltkit/core": "^1.3.
|
|
18
|
-
"@basaltkit/http": "^
|
|
21
|
+
"@basaltkit/core": "^1.3.1",
|
|
22
|
+
"@basaltkit/http": "^2.0.0"
|
|
19
23
|
},
|
|
20
24
|
"peerDependencies": {
|
|
21
|
-
"zod": "^
|
|
25
|
+
"zod": "^4.0.0"
|
|
22
26
|
},
|
|
23
27
|
"devDependencies": {
|
|
24
|
-
"@types/node": "^26.
|
|
28
|
+
"@types/node": "^26.4.0",
|
|
25
29
|
"typescript": "^7.0.2",
|
|
26
30
|
"vitest": "^4.1.11",
|
|
27
|
-
"zod": "^
|
|
28
|
-
"@basaltkit/fastify": "^
|
|
31
|
+
"zod": "^4.5.4",
|
|
32
|
+
"@basaltkit/fastify": "^2.0.0",
|
|
29
33
|
"@basaltkit/tsconfig": "^0.24.0"
|
|
30
34
|
},
|
|
31
35
|
"publishConfig": {
|