@jgb-solutions/kit 0.6.0 → 0.7.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/CHANGELOG.md +32 -0
- package/README.md +17 -6
- package/dist/auth/browser.d.ts +4 -1
- package/dist/auth/bun.d.ts +3 -2
- package/dist/auth/bun.js +4 -2
- package/dist/auth/expo.d.ts +39 -4
- package/dist/auth/expo.js +24 -3
- package/dist/auth/orpc.d.ts +6 -0
- package/dist/auth/orpc.js +11 -3
- package/dist/auth/server.d.ts +43 -7
- package/dist/auth/server.js +178 -16
- package/dist/auth/versions.d.ts +17 -0
- package/dist/auth/versions.js +19 -0
- package/dist/auth.d.ts +111 -3
- package/dist/auth.js +110 -4
- package/dist/i18n.js +2 -2
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,38 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@jgb-solutions/kit`. Versions follow semver.
|
|
4
4
|
|
|
5
|
+
## 0.7.0
|
|
6
|
+
|
|
7
|
+
Security fixes from the 2026-12-04 audit. Breaking changes are marked; see "Upgrading" at the end of this section.
|
|
8
|
+
|
|
9
|
+
- **Breaking:** `authServer` takes a required `rateLimit: { storage }`, or `'off'` for E2E (it throws on a production server unless E2E=1). Better Auth limits only requests to its own routes, so direct `auth.api` calls from server functions were unthrottled. Each sign-in, sign-up, password change, first password, Google start or link and account deletion now counts per address under Better Auth's own keys (`<ip>|<path>`). Over the limit: `TOO_MANY_REQUESTS`.
|
|
10
|
+
- Password sign-in also counts per login, through /api/auth and direct calls alike: `accountSignInLimit(storage)`, a Better Auth hook that `standardAuthOptions` adds when rate limits are on (`ACCOUNT_SIGN_IN_RULE`, 30 in 15 minutes, keyed by a hash), so a new address per attempt doesn't reset it.
|
|
11
|
+
- **Breaking:** `AuthResult`'s failure has an optional `retryAfter`; code that rebuilds the type or matches it exactly must allow it.
|
|
12
|
+
- **Breaking:** `AuthInstance` (and so `authServer`'s `auth`) needs `options` as well as `api` (the Better Auth instance has both; a hand-made stub needs `options: {}`), and `AuthApi.getSession` must answer `session.createdAt`.
|
|
13
|
+
- **Breaking:** `deleteOwnAccount` for an account without a password no longer takes `confirmUsername` (a public username proved nothing). It needs a sign-in from the last `REAUTH_MINUTES` (5), else `REAUTH_REQUIRED`. `AUTH_SERVER_CODES.confirmUsername` becomes `reauthRequired`.
|
|
14
|
+
- **Breaking:** `MobileSession` has a new `{ status: 'unverified' }`. When the server can't be reached at launch, `restore()` sets it instead of `out` with the token still sent. New `handleUnauthorized(error)` forgets the token on any UNAUTHORIZED answer.
|
|
15
|
+
- **Breaking (trust):** the client's address comes from `ipAddressHeaders` (`cf-connecting-ip` by default), which only Cloudflare sets reliably. A server reachable without Cloudflare must list its own proxy's header, or every per-address limit can be dodged.
|
|
16
|
+
- `googleIdTokenNonce({ mode })` (new Better Auth plugin, added by `standardAuthOptions` when Google is on; `googleNonce: 'optional'` by default). POST /google/nonce issues a single-use nonce (5 minutes, never cached; expired ones are swept), and a Google ID-token sign-in or link spends it, so a stolen token can't be replayed. **Plan:** `'required'` becomes the default in 0.9.0 (planned for January 2027), once every app's mobile build sends a nonce; until then a token sent without one still skips the check. Apps can set `googleNonce: 'required'` sooner.
|
|
17
|
+
- Expo: `auth.googleNonce()` answers `{ ok: true, nonce }` or `{ ok: false, code }` (NONCE_UNAVAILABLE, NETWORK, TOO_MANY_REQUESTS…) for the app's error tracker. **Breaking:** `googleIdToken(module, webClientId, nonce)` passes the nonce to the native module's `signIn(serverClientId, nonce)`, so the module must accept and use it (Credential Manager's `setNonce`).
|
|
18
|
+
- `kit/auth/versions` (new, no imports): `AUTH_VERSIONS`, the better-auth, passkey and jose versions this release is tested with, and `authVersionProblems(dependencies)` for an app's CI check, so the auth set moves in every app together.
|
|
19
|
+
- `counterRateLimit` counts in memory while its store is down, instead of letting every attempt through. New `memoryRateLimit()`.
|
|
20
|
+
- `kit/auth/orpc`: `authMiddleware({ freshViewer })` makes `requireAdmin` re-read the session fresh, so a ban or a lost role counts at once. `withUser` marks any answer for a signed-in person `private, no-store`.
|
|
21
|
+
- `concurrencyLimit(limit, maxQueue)` refuses new tasks past `maxQueue` waiting; `argon2idHasher({ concurrency })` caps its queue at 100 per running hash.
|
|
22
|
+
- `createTranslator` reads own properties only, so `{constructor}` in a message or key never prints a built-in.
|
|
23
|
+
|
|
24
|
+
### Upgrading
|
|
25
|
+
|
|
26
|
+
From 0.4.x:
|
|
27
|
+
|
|
28
|
+
1. Pin `better-auth` and `@better-auth/passkey` to `AUTH_VERSIONS` (1.7.29).
|
|
29
|
+
2. Pass `rateLimit: { storage }` to `authServer`, the same store as `standardAuthOptions`' `rateLimitStorage` (`counterRateLimit(…)`, or `memoryRateLimit()` on one server); `'off'` only on the E2E server.
|
|
30
|
+
3. Check `ipAddressHeaders` names a header your proxy sets.
|
|
31
|
+
4. Deleting an account without a password: drop the username field; offer "sign in with Google again" on `REAUTH_REQUIRED`, then delete.
|
|
32
|
+
5. Mobile: handle `unverified` wherever the session status is switched on, call `handleUnauthorized` from the RPC client's error interceptor, fetch `googleNonce()` before Google's sheet, and update the native module's `signIn` to take the nonce.
|
|
33
|
+
6. Word the new codes: `TOO_MANY_REQUESTS`, `REAUTH_REQUIRED`, `INVALID_NONCE`, `NONCE_REQUIRED`.
|
|
34
|
+
|
|
35
|
+
From 0.3.x, also take 0.4.x's and 0.5.0's changes: move the app's own account code onto `kit/auth/server` (0.5.0) and `kit/auth/browser` (0.6.0), and its caching headers onto `kit/auth/cache`, then follow the steps above.
|
|
36
|
+
|
|
5
37
|
## 0.6.0
|
|
6
38
|
|
|
7
39
|
- `kit/auth/browser` (new, no dependencies):
|
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ What the preset sets:
|
|
|
83
83
|
- **Google**, when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set. `GOOGLE_MOBILE_CLIENT_IDS` adds the apps' clients, for ID-token sign-in. A new Google address makes a new account with a confirmed address. Joining existing accounts is "merge only confirmed" (see below).
|
|
84
84
|
- **Roles:** Better Auth's admin plugin, with the app's access control. A new account whose address is in `ADMIN_EMAILS` starts as admin when it's created with Google (a confirmed address); a sign-up with that address by email and password starts as an ordinary user, so nobody can claim an admin's address first. Other first admins are promoted from the server (the app's admin script).
|
|
85
85
|
- **The mobile app:** the bearer plugin.
|
|
86
|
-
- **Limits:** 60 requests a minute, tighter on sign-in, sign-up, passkeys and password changes (`RATE_LIMIT_RULES`). Counts go in the database, or in a counter store with `rateLimitStorage: counterRateLimit(() => redis)`, which
|
|
86
|
+
- **Limits:** 60 requests a minute, tighter on sign-in, sign-up, passkeys and password changes (`RATE_LIMIT_RULES`). Counts go in the database, or in a counter store with `rateLimitStorage: counterRateLimit(() => redis)`, which counts in the server's memory while the store is down (`memoryRateLimit()` on its own suits a single server).
|
|
87
87
|
- **Sessions:** 30 days, renewed daily, with a 5-minute cookie cache. The base URL is the request's host only for the site or a local host; anything else falls back to the site.
|
|
88
88
|
|
|
89
89
|
#### Google and existing accounts: merge only confirmed
|
|
@@ -123,7 +123,13 @@ Sign-in, sign-up, passwords, passkeys, Google, deleting one's own account and th
|
|
|
123
123
|
```ts
|
|
124
124
|
import { authServer } from '@jgb-solutions/kit/auth/server'
|
|
125
125
|
|
|
126
|
-
const accounts = authServer({
|
|
126
|
+
const accounts = authServer({
|
|
127
|
+
auth: getAuth,
|
|
128
|
+
headers: getRequestHeaders,
|
|
129
|
+
roleOf,
|
|
130
|
+
canOpenAdmin,
|
|
131
|
+
rateLimit: { storage: rateLimitStorage }, // required: the store given to standardAuthOptions; 'off' only for E2E
|
|
132
|
+
})
|
|
127
133
|
|
|
128
134
|
await accounts.viewer() // the signed-in person, or null (also when suspended); { fresh: true } skips the cookie cache
|
|
129
135
|
await accounts.signIn({ login, password }) // username or email; a placeholder address never signs in
|
|
@@ -131,11 +137,13 @@ await accounts.signUp({ username, password, email }) // no email: a placeholder
|
|
|
131
137
|
await accounts.changePassword({ currentPassword, newPassword }) // signs out the other devices
|
|
132
138
|
await accounts.passkeys() // newest first
|
|
133
139
|
await accounts.googleStartUrl({ redirect, home: '/account', signInPath: '/sign-in' }) // redirect checked with safeRedirect
|
|
134
|
-
await accounts.deleteOwnAccount({ password }) //
|
|
140
|
+
await accounts.deleteOwnAccount({ password }) // without a password (Google): a sign-in from the last 5 minutes, else REAUTH_REQUIRED
|
|
135
141
|
await accounts.admin.listUsers({ page, pageSize: 25, search })
|
|
136
142
|
await accounts.admin.ban({ userId }) // also setRole, unban, resetPassword: never on the admin's own account
|
|
137
143
|
```
|
|
138
144
|
|
|
145
|
+
**Rate limits.** The client's address comes from `ipAddressHeaders` (`cf-connecting-ip` by default): that header is trustworthy only when every request comes through Cloudflare. A server reachable directly must list the header its own proxy sets, or anyone can pick a new address per request. Better Auth limits only requests to its own routes (/api/auth/…), never a direct `auth.api` call, so a server function calling it is unthrottled. `authServer` counts each attempt itself, in the same store and under Better Auth's own keys (`<ip>|<path>`, the address read the way the instance reads it), so the two add up. Password sign-in also counts per login, through either door: `standardAuthOptions` adds `accountSignInLimit` (`ACCOUNT_SIGN_IN_RULE`, 30 in 15 minutes per login, its username and its address each, keyed by a hash), a Better Auth hook that runs for /api/auth requests and direct calls alike, so a new address per attempt doesn't reset it. It uses `rateLimitStorage` (in memory with the database store). `rateLimit: 'off'` throws on a production server unless E2E=1. Over the limit: `TOO_MANY_REQUESTS` with `retryAfter` in seconds.
|
|
146
|
+
|
|
139
147
|
Admin calls read the session fresh and go through `toAuthUser`, so a suspended admin is out at once. `authResult(fn)` turns any other Better Auth call into the same `{ ok, code }`.
|
|
140
148
|
|
|
141
149
|
#### `kit/auth/cache`: per-person pages stay out of shared caches
|
|
@@ -183,13 +191,16 @@ export const auth = createMobileAuth({
|
|
|
183
191
|
|
|
184
192
|
const session = useSyncExternalStore(auth.subscribe, auth.getSession)
|
|
185
193
|
await auth.signIn('maria', password) // or an email address
|
|
186
|
-
await auth.
|
|
194
|
+
const nonce = await auth.googleNonce() // { ok: true, nonce } (single use) or { ok: false, code }: report the code
|
|
195
|
+
await auth.signInWithGoogle(idToken, nonce.ok ? { nonce: nonce.nonce } : {}) // from the app's Google Sign-In SDK, asked with the nonce
|
|
187
196
|
await auth.linkGoogle(idToken) // signed in: connect Google from the account screen
|
|
188
197
|
await auth.signInWithPasskey(Passkeys)
|
|
189
|
-
new RPCLink({ url, headers: auth.authHeaders }) // Bearer on every RPC call
|
|
198
|
+
new RPCLink({ url, headers: auth.authHeaders }) // Bearer on every RPC call; in its error interceptor: auth.handleUnauthorized(error)
|
|
190
199
|
```
|
|
191
200
|
|
|
192
|
-
|
|
201
|
+
`restore()` at launch checks the saved token with the server. Offline, the session is `unverified`: never signed in (show signed-out or cached screens) and `restore()` again when back online. Any UNAUTHORIZED answer passed to `handleUnauthorized` forgets the token.
|
|
202
|
+
|
|
203
|
+
On Android, `googleIdToken(nativeModule, webClientId, nonce)` gets the ID token from the phone's Google account sheet (the app's own Credential Manager module: `signIn(serverClientId)` answering `{ idToken }`, rejecting with `ERR_CANCELLED` or `ERR_NO_ACCOUNT`). It answers `{ ok: true, idToken }`, or `CANCELLED`, `NO_GOOGLE_ACCOUNT`, `GOOGLE_UNAVAILABLE` (no module or client ID), or `GOOGLE_FAILED` with a `detail` for the error tracker.
|
|
193
204
|
|
|
194
205
|
Failures come back as codes (`INVALID_USERNAME_OR_PASSWORD`, `ACCOUNT_NOT_LINKED`, `GOOGLE_ALREADY_LINKED`, `TOO_MANY_REQUESTS`, `NETWORK`, `CANCELLED`…), and the app words them. The module has no dependencies: the app passes in its secure storage and passkey modules.
|
|
195
206
|
|
package/dist/auth/browser.d.ts
CHANGED
|
@@ -64,7 +64,10 @@ export declare function createPendingAction<Kind extends string>(): {
|
|
|
64
64
|
*/
|
|
65
65
|
finish<Otherwise extends string | undefined = undefined>(otherwise?: Otherwise): Promise<Kind | Otherwise | undefined>;
|
|
66
66
|
};
|
|
67
|
-
/**
|
|
67
|
+
/**
|
|
68
|
+
* Where to go after signing in: `next`, with `#done=<kind>` when something was done. `next` must
|
|
69
|
+
* already be a path checked with `safeRedirect` (kit/auth/rules): this adds the flash, it checks nothing.
|
|
70
|
+
*/
|
|
68
71
|
export declare function afterSignIn(next: string, done: string | undefined): string;
|
|
69
72
|
/**
|
|
70
73
|
* True when the signed-in flag cookie (`signedInFlag` in `standardAuthOptions`, readable by scripts,
|
package/dist/auth/bun.d.ts
CHANGED
|
@@ -30,6 +30,7 @@ export declare function argon2idHasher(options?: {
|
|
|
30
30
|
}): PasswordHasher;
|
|
31
31
|
/**
|
|
32
32
|
* Runs at most `limit` tasks at once; the rest wait in order. A finished task hands its place
|
|
33
|
-
* straight to the next one waiting, so a newcomer can never slip past the limit in between.
|
|
33
|
+
* straight to the next one waiting, so a newcomer can never slip past the limit in between. Past
|
|
34
|
+
* `maxQueue` waiting tasks, a new one is refused at once (it throws) instead of piling up in memory.
|
|
34
35
|
*/
|
|
35
|
-
export declare function concurrencyLimit(limit: number): <T>(task: () => Promise<T>) => Promise<T>;
|
|
36
|
+
export declare function concurrencyLimit(limit: number, maxQueue?: number): <T>(task: () => Promise<T>) => Promise<T>;
|
package/dist/auth/bun.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
function argon2idHasher(options = {}) {
|
|
3
3
|
const { fallbackVerify, concurrency, ...cost } = options;
|
|
4
4
|
const algorithm = { algorithm: "argon2id", ...cost };
|
|
5
|
-
const run = concurrency === undefined ? (task) => task() : concurrencyLimit(concurrency);
|
|
5
|
+
const run = concurrency === undefined ? (task) => task() : concurrencyLimit(concurrency, concurrency * 100);
|
|
6
6
|
return {
|
|
7
7
|
hash: (password) => run(() => Bun.password.hash(password, algorithm)),
|
|
8
8
|
verify: ({ hash, password }) => run(() => {
|
|
@@ -12,7 +12,7 @@ function argon2idHasher(options = {}) {
|
|
|
12
12
|
})
|
|
13
13
|
};
|
|
14
14
|
}
|
|
15
|
-
function concurrencyLimit(limit) {
|
|
15
|
+
function concurrencyLimit(limit, maxQueue = Infinity) {
|
|
16
16
|
if (!Number.isInteger(limit) || limit < 1)
|
|
17
17
|
throw new RangeError("concurrency must be a whole number of at least 1");
|
|
18
18
|
let running = 0;
|
|
@@ -20,6 +20,8 @@ function concurrencyLimit(limit) {
|
|
|
20
20
|
return async (task) => {
|
|
21
21
|
if (running < limit)
|
|
22
22
|
running++;
|
|
23
|
+
else if (waiting.length >= maxQueue)
|
|
24
|
+
throw new Error("concurrency limit: the queue is full");
|
|
23
25
|
else
|
|
24
26
|
await new Promise((resolve) => waiting.push(resolve));
|
|
25
27
|
try {
|
package/dist/auth/expo.d.ts
CHANGED
|
@@ -9,10 +9,17 @@ export type PasskeysModule = {
|
|
|
9
9
|
get(request: unknown): Promise<unknown>;
|
|
10
10
|
create(request: unknown): Promise<unknown>;
|
|
11
11
|
};
|
|
12
|
+
/**
|
|
13
|
+
* The app's session. `unverified`: a saved token the server couldn't check (offline at launch). It
|
|
14
|
+
* is never signed in: show signed-out or cached screens and call `restore()` again when back online.
|
|
15
|
+
* The token is kept for that retry, and dropped as soon as the server says it is dead.
|
|
16
|
+
*/
|
|
12
17
|
export type MobileSession<U> = {
|
|
13
18
|
status: 'loading';
|
|
14
19
|
} | {
|
|
15
20
|
status: 'out';
|
|
21
|
+
} | {
|
|
22
|
+
status: 'unverified';
|
|
16
23
|
} | {
|
|
17
24
|
status: 'in';
|
|
18
25
|
user: U;
|
|
@@ -46,8 +53,16 @@ export declare function createMobileAuth<U>(config: MobileAuthConfig<U>): {
|
|
|
46
53
|
subscribe(listener: () => void): () => void;
|
|
47
54
|
getSession: () => MobileSession<U>;
|
|
48
55
|
authHeaders: () => Record<string, string>;
|
|
49
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* At launch, and again when back online: the saved token, checked with the server. A dead token
|
|
58
|
+
* is dropped; when the server can't be reached the session is `unverified`, never signed in.
|
|
59
|
+
*/
|
|
50
60
|
restore(): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* For the app's RPC client's error interceptor: an UNAUTHORIZED answer to any call means the
|
|
63
|
+
* token is dead (expired, revoked, account deleted), so it is forgotten at once. True when it was.
|
|
64
|
+
*/
|
|
65
|
+
handleUnauthorized(error: unknown): Promise<boolean>;
|
|
51
66
|
/** A username or an email address, and the password. */
|
|
52
67
|
signIn(login: string, password: string): Promise<AuthResult>;
|
|
53
68
|
/** A new account. Without an email address, the placeholder the website uses (never shown or mailed). */
|
|
@@ -62,6 +77,20 @@ export declare function createMobileAuth<U>(config: MobileAuthConfig<U>): {
|
|
|
62
77
|
* with Google (its audience must be one of GOOGLE_CLIENT_ID or GOOGLE_MOBILE_CLIENT_IDS) and signs
|
|
63
78
|
* in, links or creates the account by the server's rules.
|
|
64
79
|
*/
|
|
80
|
+
/**
|
|
81
|
+
* A single-use nonce from the server (kit's googleIdTokenNonce), for Google's sheet and then
|
|
82
|
+
* `signInWithGoogle` / `linkGoogle`: a stolen ID token can't be replayed. Without one the answer
|
|
83
|
+
* says why, for the app's error tracker: NONCE_UNAVAILABLE (a server without the plugin), NETWORK,
|
|
84
|
+
* TOO_MANY_REQUESTS or the server's code. While the server's mode is 'optional' the app may go on
|
|
85
|
+
* without a nonce; once it is 'required' that sign-in will be refused.
|
|
86
|
+
*/
|
|
87
|
+
googleNonce(): Promise<{
|
|
88
|
+
ok: true;
|
|
89
|
+
nonce: string;
|
|
90
|
+
} | {
|
|
91
|
+
ok: false;
|
|
92
|
+
code: string;
|
|
93
|
+
}>;
|
|
65
94
|
signInWithGoogle(idToken: string, options?: {
|
|
66
95
|
nonce?: string;
|
|
67
96
|
}): Promise<AuthResult>;
|
|
@@ -88,7 +117,7 @@ export type MobileAuth<U> = ReturnType<typeof createMobileAuth<U>>;
|
|
|
88
117
|
* (Android's Credential Manager), rejecting with `error.code` ERR_CANCELLED, ERR_NO_ACCOUNT or another.
|
|
89
118
|
*/
|
|
90
119
|
export type GoogleCredentialModule = {
|
|
91
|
-
signIn(serverClientId: string): Promise<{
|
|
120
|
+
signIn(serverClientId: string, nonce?: string): Promise<{
|
|
92
121
|
idToken: string;
|
|
93
122
|
}>;
|
|
94
123
|
};
|
|
@@ -106,9 +135,15 @@ export type GoogleTokenResult = {
|
|
|
106
135
|
detail: string;
|
|
107
136
|
};
|
|
108
137
|
/**
|
|
109
|
-
* Google's ID token from the phone's account sheet, for `signInWithGoogle` or `linkGoogle
|
|
138
|
+
* Google's ID token from the phone's account sheet, for `signInWithGoogle` or `linkGoogle`, with the
|
|
139
|
+
* nonce from `auth.googleNonce()` when there is one:
|
|
140
|
+
*
|
|
141
|
+
* const nonce = await auth.googleNonce() // report a failure's code to the error tracker
|
|
142
|
+
* const google = await googleIdToken(GoogleModule, webClientId, nonce.ok ? nonce.nonce : null)
|
|
143
|
+
* if (google.ok) await auth.signInWithGoogle(google.idToken, nonce.ok ? { nonce: nonce.nonce } : {})
|
|
144
|
+
* `module`
|
|
110
145
|
* is the app's native module, or null where the installed app lacks it (iOS, older builds):
|
|
111
146
|
* GOOGLE_UNAVAILABLE then, as without `webClientId` (the website's OAuth client, whose tokens Better
|
|
112
147
|
* Auth accepts). CANCELLED means the person closed the sheet: nothing to say.
|
|
113
148
|
*/
|
|
114
|
-
export declare function googleIdToken(module: GoogleCredentialModule | null | undefined, webClientId: string | null | undefined): Promise<GoogleTokenResult>;
|
|
149
|
+
export declare function googleIdToken(module: GoogleCredentialModule | null | undefined, webClientId: string | null | undefined, nonce?: string | null): Promise<GoogleTokenResult>;
|
package/dist/auth/expo.js
CHANGED
|
@@ -205,9 +205,15 @@ function createMobileAuth(config) {
|
|
|
205
205
|
} catch (error) {
|
|
206
206
|
if (isUnauthorized(error))
|
|
207
207
|
return forget();
|
|
208
|
-
set({ status: "
|
|
208
|
+
set({ status: "unverified" });
|
|
209
209
|
}
|
|
210
210
|
},
|
|
211
|
+
async handleUnauthorized(error) {
|
|
212
|
+
if (!isUnauthorized(error) || !token)
|
|
213
|
+
return false;
|
|
214
|
+
await forget();
|
|
215
|
+
return true;
|
|
216
|
+
},
|
|
211
217
|
signIn(login, password) {
|
|
212
218
|
const value = login.trim().toLowerCase();
|
|
213
219
|
if (!value || !password)
|
|
@@ -224,6 +230,21 @@ function createMobileAuth(config) {
|
|
|
224
230
|
return Promise.resolve({ ok: false, code: "NO_RANDOM_ID" });
|
|
225
231
|
return signInWith("/sign-up/email", { name: input.name?.trim() || username, username, email, password: input.password });
|
|
226
232
|
},
|
|
233
|
+
async googleNonce() {
|
|
234
|
+
try {
|
|
235
|
+
const { response, body } = await call("/google/nonce", { method: "POST", body: {} });
|
|
236
|
+
if (response.status === 404)
|
|
237
|
+
return { ok: false, code: "NONCE_UNAVAILABLE" };
|
|
238
|
+
if (response.status === 429)
|
|
239
|
+
return { ok: false, code: "TOO_MANY_REQUESTS" };
|
|
240
|
+
const nonce = response.ok && typeof body === "object" && body !== null && "nonce" in body ? body.nonce : null;
|
|
241
|
+
if (typeof nonce === "string" && nonce)
|
|
242
|
+
return { ok: true, nonce };
|
|
243
|
+
return { ok: false, code: codeOf(body, response.ok ? "NO_NONCE" : String(response.status)) };
|
|
244
|
+
} catch {
|
|
245
|
+
return { ok: false, code: "NETWORK" };
|
|
246
|
+
}
|
|
247
|
+
},
|
|
227
248
|
signInWithGoogle(idToken, options = {}) {
|
|
228
249
|
return signInWith("/sign-in/social", {
|
|
229
250
|
provider: "google",
|
|
@@ -285,11 +306,11 @@ function createMobileAuth(config) {
|
|
|
285
306
|
forget
|
|
286
307
|
};
|
|
287
308
|
}
|
|
288
|
-
async function googleIdToken(module, webClientId) {
|
|
309
|
+
async function googleIdToken(module, webClientId, nonce) {
|
|
289
310
|
if (!module || !webClientId)
|
|
290
311
|
return { ok: false, code: "GOOGLE_UNAVAILABLE" };
|
|
291
312
|
try {
|
|
292
|
-
const { idToken } = await module.signIn(webClientId);
|
|
313
|
+
const { idToken } = await (nonce ? module.signIn(webClientId, nonce) : module.signIn(webClientId));
|
|
293
314
|
if (typeof idToken !== "string" || !idToken)
|
|
294
315
|
return { ok: false, code: "GOOGLE_FAILED", detail: "NO_TOKEN" };
|
|
295
316
|
return { ok: true, idToken };
|
package/dist/auth/orpc.d.ts
CHANGED
|
@@ -11,6 +11,12 @@ export declare function authMiddleware<U extends {
|
|
|
11
11
|
canOpenAdmin: (role: string) => boolean;
|
|
12
12
|
/** An extra check for admin procedures, such as Cloudflare Access's token. False means FORBIDDEN. */
|
|
13
13
|
adminCheck?: () => Promise<boolean>;
|
|
14
|
+
/**
|
|
15
|
+
* The signed-in person read fresh from the database, skipping the session cookie cache (authServer's
|
|
16
|
+
* `viewer({ fresh: true })`). `requireAdmin` re-checks with it, so a ban or a role taken away counts
|
|
17
|
+
* at once instead of up to 5 minutes later. Recommended.
|
|
18
|
+
*/
|
|
19
|
+
freshViewer?: () => Promise<U | null>;
|
|
14
20
|
}): {
|
|
15
21
|
withUser: import("@orpc/server").DecoratedMiddleware<HeadersContext & object, {
|
|
16
22
|
user: U | null;
|
package/dist/auth/orpc.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
// src/auth/orpc.ts
|
|
2
2
|
import { ORPCError, os } from "@orpc/server";
|
|
3
3
|
function authMiddleware(options) {
|
|
4
|
-
const withUser = os.$context().middleware(async ({ next }) =>
|
|
4
|
+
const withUser = os.$context().middleware(async ({ context, next }) => {
|
|
5
|
+
const user = await options.viewer();
|
|
6
|
+
if (user)
|
|
7
|
+
context.resHeaders?.set("cache-control", "private, no-store");
|
|
8
|
+
return next({ context: { user } });
|
|
9
|
+
});
|
|
5
10
|
const requireUser = os.$context().middleware(async ({ context, next }) => {
|
|
6
11
|
if (!context.user)
|
|
7
12
|
throw new ORPCError("UNAUTHORIZED");
|
|
@@ -11,12 +16,15 @@ function authMiddleware(options) {
|
|
|
11
16
|
const requireAdmin = os.$context().middleware(async ({ context, next }) => {
|
|
12
17
|
if (!context.user)
|
|
13
18
|
throw new ORPCError("UNAUTHORIZED");
|
|
14
|
-
|
|
19
|
+
const user = options.freshViewer ? await options.freshViewer() : context.user;
|
|
20
|
+
if (!user)
|
|
21
|
+
throw new ORPCError("UNAUTHORIZED");
|
|
22
|
+
if (!options.canOpenAdmin(user.role))
|
|
15
23
|
throw new ORPCError("FORBIDDEN");
|
|
16
24
|
if (options.adminCheck && !await options.adminCheck())
|
|
17
25
|
throw new ORPCError("FORBIDDEN");
|
|
18
26
|
context.resHeaders?.set("cache-control", "private, no-store");
|
|
19
|
-
return next({ context: { user
|
|
27
|
+
return next({ context: { user } });
|
|
20
28
|
});
|
|
21
29
|
return { withUser, requireUser, requireAdmin };
|
|
22
30
|
}
|
package/dist/auth/server.d.ts
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server side of accounts, the same in every app: sign-in, sign-up, password and passkeys,
|
|
3
|
+
* Google, deleting one's own account and the admin's user management. Framework-free: give it the
|
|
4
|
+
* Better Auth instance and a way to read the request's headers, and call its functions from server
|
|
5
|
+
* functions or oRPC procedures. Answers are codes (`{ ok: false, code }`), never English: the app
|
|
6
|
+
* words them in its own languages.
|
|
7
|
+
*
|
|
8
|
+
* import { authServer } from '@jgb-solutions/kit/auth/server'
|
|
9
|
+
* const accounts = authServer({ auth: getAuth, headers: getRequestHeaders, roleOf, canOpenAdmin, rateLimit: { storage } })
|
|
10
|
+
* export const signIn = createServerFn({ method: 'POST' }).validator(…).handler(({ data }) => accounts.signIn(data))
|
|
11
|
+
*/
|
|
12
|
+
import type { BetterAuthRateLimitStorage } from 'better-auth';
|
|
13
|
+
import { getIP } from 'better-auth/api';
|
|
1
14
|
import { type SessionUser } from '../auth';
|
|
2
15
|
import { type AuthUser } from './rules';
|
|
3
16
|
/** What an action answers: done, or Better Auth's code (or one of this module's) for the app to word. */
|
|
@@ -6,6 +19,7 @@ export type AuthResult = {
|
|
|
6
19
|
} | {
|
|
7
20
|
ok: false;
|
|
8
21
|
code: string;
|
|
22
|
+
retryAfter?: number;
|
|
9
23
|
};
|
|
10
24
|
/** Runs a Better Auth call: its APIError becomes `{ ok: false, code }`; any other error is thrown on. */
|
|
11
25
|
export declare function authResult(action: () => Promise<unknown>): Promise<AuthResult>;
|
|
@@ -15,14 +29,19 @@ export declare const AUTH_SERVER_CODES: {
|
|
|
15
29
|
readonly unauthorized: "UNAUTHORIZED";
|
|
16
30
|
/** Deleting an account with a password, without giving it. */
|
|
17
31
|
readonly passwordRequired: "INVALID_PASSWORD";
|
|
18
|
-
/**
|
|
19
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Deleting an account without a password (made with Google) needs a sign-in from the last
|
|
34
|
+
* `REAUTH_MINUTES`: sign in with Google again, then delete.
|
|
35
|
+
*/
|
|
36
|
+
readonly reauthRequired: "REAUTH_REQUIRED";
|
|
20
37
|
/** Sign-in with an account's placeholder address (it isn't a real one). */
|
|
21
38
|
readonly invalidLogin: "INVALID_EMAIL_OR_PASSWORD";
|
|
22
39
|
/** Better Auth answered a Google start without an address to go to. */
|
|
23
40
|
readonly noRedirect: "NO_REDIRECT_URL";
|
|
24
41
|
/** An admin acting on their own account (role, ban, password reset): they use their account page. */
|
|
25
42
|
readonly self: "CANNOT_ACT_ON_SELF";
|
|
43
|
+
/** Too many attempts from this address or on this account: try again after `retryAfter` seconds. */
|
|
44
|
+
readonly tooManyRequests: "TOO_MANY_REQUESTS";
|
|
26
45
|
};
|
|
27
46
|
type Headers_ = Headers;
|
|
28
47
|
type Call<Body> = {
|
|
@@ -41,6 +60,9 @@ export type AuthApi<Role extends string = string> = {
|
|
|
41
60
|
};
|
|
42
61
|
}): Promise<{
|
|
43
62
|
user: SessionUser;
|
|
63
|
+
session: {
|
|
64
|
+
createdAt: Date | string;
|
|
65
|
+
};
|
|
44
66
|
} | null>;
|
|
45
67
|
signInEmail(input: Call<{
|
|
46
68
|
email: string;
|
|
@@ -135,10 +157,21 @@ export type AuthApi<Role extends string = string> = {
|
|
|
135
157
|
userId: string;
|
|
136
158
|
}>): Promise<unknown>;
|
|
137
159
|
};
|
|
138
|
-
/** Anything with Better Auth's `api` (the instance itself). */
|
|
160
|
+
/** Anything with Better Auth's `api` and `options` (the instance itself). */
|
|
139
161
|
export type AuthInstance<Role extends string = string> = {
|
|
140
162
|
api: AuthApi<Role>;
|
|
163
|
+
options: Parameters<typeof getIP>[1];
|
|
141
164
|
};
|
|
165
|
+
/**
|
|
166
|
+
* Rate limits for the account functions. Better Auth limits only requests to its own routes, never a
|
|
167
|
+
* direct `auth.api` call, so these functions count each attempt themselves, in the same store and under
|
|
168
|
+
* the same keys (`<ip>|<path>`, the client's address read the way the instance reads it), so attempts
|
|
169
|
+
* through /api/auth and through these functions add up. Sign-in also counts per login (standardAuthOptions' accountSignInLimit hook), which holds
|
|
170
|
+
* when the address changes. `'off'` only for E2E runs.
|
|
171
|
+
*/
|
|
172
|
+
export type AuthServerRateLimit = {
|
|
173
|
+
storage: BetterAuthRateLimitStorage;
|
|
174
|
+
} | 'off';
|
|
142
175
|
export type AuthServerConfig<Role extends string> = {
|
|
143
176
|
/** The Better Auth instance, or a function that makes it on first use. */
|
|
144
177
|
auth: NoInfer<AuthInstance<Role> | (() => AuthInstance<Role> | Promise<AuthInstance<Role>>)>;
|
|
@@ -148,6 +181,8 @@ export type AuthServerConfig<Role extends string> = {
|
|
|
148
181
|
roleOf: (stored: string | null | undefined) => Role;
|
|
149
182
|
/** From `defineRoles`: who may open the admin panel. */
|
|
150
183
|
canOpenAdmin: (stored: string | null | undefined) => boolean;
|
|
184
|
+
/** Required: the rate-limit store (Better Auth's `customStorage`: `counterRateLimit(…)` or `memoryRateLimit()`), or `'off'` for E2E. */
|
|
185
|
+
rateLimit: AuthServerRateLimit;
|
|
151
186
|
/** A new placeholder address's random part (Hermes has no global crypto; servers keep the default). */
|
|
152
187
|
randomId?: () => string;
|
|
153
188
|
};
|
|
@@ -167,6 +202,8 @@ export type AdminUserRow<Role extends string = string> = {
|
|
|
167
202
|
banned: boolean;
|
|
168
203
|
createdAt: string;
|
|
169
204
|
};
|
|
205
|
+
/** How recent a sign-in must be to delete an account that has no password. */
|
|
206
|
+
export declare const REAUTH_MINUTES = 5;
|
|
170
207
|
/** A password nobody chose: 18 random bytes as base64url (24 characters). */
|
|
171
208
|
export declare function temporaryPassword(): string;
|
|
172
209
|
/** The account functions for one app. Every function reads the current request's headers itself. */
|
|
@@ -236,13 +273,12 @@ export declare function authServer<Role extends string>(config: AuthServerConfig
|
|
|
236
273
|
/**
|
|
237
274
|
* Deletes the signed-in person's account (the app's `beforeDeleteUser` removes what they saved).
|
|
238
275
|
* The server decides from the account itself, never from what the page sends: an account with a
|
|
239
|
-
* password must give it
|
|
240
|
-
*
|
|
241
|
-
*
|
|
276
|
+
* password must give it; an account without one (made with Google) must have signed in within the
|
|
277
|
+
* last `REAUTH_MINUTES` (REAUTH_REQUIRED otherwise: sign in with Google again, on the website or in
|
|
278
|
+
* the app, then delete). A stolen session can't delete an account by typing its public username.
|
|
242
279
|
*/
|
|
243
280
|
deleteOwnAccount(input: {
|
|
244
281
|
password?: string | undefined;
|
|
245
|
-
confirmUsername?: string | undefined;
|
|
246
282
|
}): Promise<AuthResult>;
|
|
247
283
|
admin: {
|
|
248
284
|
/** The signed-in admin, or null (also when suspended). */
|
package/dist/auth/server.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// src/auth/server.ts
|
|
2
|
-
import { APIError } from "better-auth/api";
|
|
2
|
+
import { APIError as APIError2, getIP } from "better-auth/api";
|
|
3
3
|
|
|
4
4
|
// src/auth.ts
|
|
5
5
|
import { passkey } from "@better-auth/passkey";
|
|
6
|
-
import { createAuthMiddleware } from "better-auth/api";
|
|
6
|
+
import { APIError, createAuthEndpoint, createAuthMiddleware } from "better-auth/api";
|
|
7
7
|
import { admin } from "better-auth/plugins/admin";
|
|
8
8
|
import { bearer } from "better-auth/plugins/bearer";
|
|
9
9
|
import { username } from "better-auth/plugins/username";
|
|
@@ -190,9 +190,32 @@ var RATE_LIMIT_RULES = {
|
|
|
190
190
|
"/passkey/*": { window: 60, max: 20 },
|
|
191
191
|
"/change-password": { window: 60, max: 5 },
|
|
192
192
|
"/set-password": { window: 60, max: 5 },
|
|
193
|
-
"/delete-user": { window: 60, max: 5 }
|
|
193
|
+
"/delete-user": { window: 60, max: 5 },
|
|
194
|
+
"/google/nonce": { window: 60, max: 10 }
|
|
194
195
|
};
|
|
196
|
+
function memoryRateLimit(now = Date.now, maxKeys = 1e5) {
|
|
197
|
+
const counts = new Map;
|
|
198
|
+
return {
|
|
199
|
+
async consume(key, rule) {
|
|
200
|
+
const windowMs = rule.window * 1000;
|
|
201
|
+
const slot = Math.floor(now() / windowMs);
|
|
202
|
+
const entry = counts.get(key);
|
|
203
|
+
const count = entry && entry.slot === slot ? entry.count + 1 : 1;
|
|
204
|
+
counts.delete(key);
|
|
205
|
+
counts.set(key, { slot, count });
|
|
206
|
+
if (counts.size > maxKeys) {
|
|
207
|
+
const oldest = counts.keys().next().value;
|
|
208
|
+
if (oldest !== undefined)
|
|
209
|
+
counts.delete(oldest);
|
|
210
|
+
}
|
|
211
|
+
if (count <= rule.max)
|
|
212
|
+
return { allowed: true, retryAfter: null };
|
|
213
|
+
return { allowed: false, retryAfter: Math.max(1, Math.ceil(((slot + 1) * windowMs - now()) / 1000)) };
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
}
|
|
195
217
|
function counterRateLimit(store, now = Date.now) {
|
|
218
|
+
const fallback = memoryRateLimit(now);
|
|
196
219
|
return {
|
|
197
220
|
async consume(key, rule) {
|
|
198
221
|
const windowMs = rule.window * 1000;
|
|
@@ -201,8 +224,8 @@ function counterRateLimit(store, now = Date.now) {
|
|
|
201
224
|
try {
|
|
202
225
|
count = await store().incr(`auth-limit:${key}:${slot}`, rule.window);
|
|
203
226
|
} catch (error) {
|
|
204
|
-
console.warn("auth rate limit: store unavailable,
|
|
205
|
-
return
|
|
227
|
+
console.warn("auth rate limit: store unavailable, counting in memory", error);
|
|
228
|
+
return fallback.consume(key, rule);
|
|
206
229
|
}
|
|
207
230
|
if (count <= rule.max)
|
|
208
231
|
return { allowed: true, retryAfter: null };
|
|
@@ -210,6 +233,82 @@ function counterRateLimit(store, now = Date.now) {
|
|
|
210
233
|
}
|
|
211
234
|
};
|
|
212
235
|
}
|
|
236
|
+
var ACCOUNT_SIGN_IN_RULE = { window: 15 * 60, max: 30 };
|
|
237
|
+
var SIGN_IN_FIELDS = { "/sign-in/email": "email", "/sign-in/username": "username" };
|
|
238
|
+
async function sha256Hex(text) {
|
|
239
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
240
|
+
return Array.from(new Uint8Array(digest).slice(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
241
|
+
}
|
|
242
|
+
function accountSignInLimit(storage) {
|
|
243
|
+
return {
|
|
244
|
+
id: "account-sign-in-limit",
|
|
245
|
+
hooks: {
|
|
246
|
+
before: [
|
|
247
|
+
{
|
|
248
|
+
matcher: (ctx) => Object.hasOwn(SIGN_IN_FIELDS, ctx.path ?? ""),
|
|
249
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
250
|
+
const field = SIGN_IN_FIELDS[ctx.path];
|
|
251
|
+
const body = ctx.body;
|
|
252
|
+
const login = field && typeof body === "object" && body !== null && field in body ? body[field] : undefined;
|
|
253
|
+
if (typeof login !== "string" || !login.trim())
|
|
254
|
+
return;
|
|
255
|
+
const key = `login:${await sha256Hex(login.trim().toLowerCase())}|/sign-in`;
|
|
256
|
+
const answer = await storage.consume(key, ACCOUNT_SIGN_IN_RULE);
|
|
257
|
+
if (!answer.allowed)
|
|
258
|
+
throw APIError.from("TOO_MANY_REQUESTS", { code: "TOO_MANY_REQUESTS", message: "Too many sign-in attempts for this account" });
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
]
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
var GOOGLE_NONCE_MINUTES = 5;
|
|
266
|
+
var NONCE_PATHS = new Set(["/sign-in/social", "/link-social"]);
|
|
267
|
+
function googleIdTokenNonce(options) {
|
|
268
|
+
return {
|
|
269
|
+
id: "google-id-token-nonce",
|
|
270
|
+
endpoints: {
|
|
271
|
+
googleNonce: createAuthEndpoint("/google/nonce", { method: "POST" }, async (ctx) => {
|
|
272
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
|
|
273
|
+
const nonce = btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
|
|
274
|
+
const stored = await ctx.context.internalAdapter.createVerificationValue({
|
|
275
|
+
identifier: `google-nonce:${nonce}`,
|
|
276
|
+
value: "1",
|
|
277
|
+
expiresAt: new Date(Date.now() + GOOGLE_NONCE_MINUTES * 60000)
|
|
278
|
+
});
|
|
279
|
+
if (!stored)
|
|
280
|
+
throw APIError.from("INTERNAL_SERVER_ERROR", { code: "NONCE_NOT_STORED", message: "The nonce could not be stored" });
|
|
281
|
+
await ctx.context.runInBackgroundOrAwait(ctx.context.adapter.deleteMany({ model: "verification", where: [{ field: "expiresAt", operator: "lt", value: new Date }] }).then(() => {
|
|
282
|
+
return;
|
|
283
|
+
}).catch((error) => ctx.context.logger.error("google nonce: expired rows not swept", error)));
|
|
284
|
+
ctx.setHeader("cache-control", "no-store");
|
|
285
|
+
return ctx.json({ nonce });
|
|
286
|
+
})
|
|
287
|
+
},
|
|
288
|
+
hooks: {
|
|
289
|
+
before: [
|
|
290
|
+
{
|
|
291
|
+
matcher: (ctx) => NONCE_PATHS.has(ctx.path ?? ""),
|
|
292
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
293
|
+
const body = ctx.body;
|
|
294
|
+
const idToken = typeof body === "object" && body !== null && "idToken" in body ? body.idToken : undefined;
|
|
295
|
+
if (typeof idToken !== "object" || idToken === null)
|
|
296
|
+
return;
|
|
297
|
+
const nonce = "nonce" in idToken && typeof idToken.nonce === "string" ? idToken.nonce : "";
|
|
298
|
+
if (!nonce) {
|
|
299
|
+
if (options.mode === "required")
|
|
300
|
+
throw APIError.from("BAD_REQUEST", { code: "NONCE_REQUIRED", message: "A nonce is required" });
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
const spent = await ctx.context.internalAdapter.consumeVerificationValue(`google-nonce:${nonce}`);
|
|
304
|
+
if (!spent)
|
|
305
|
+
throw APIError.from("BAD_REQUEST", { code: "INVALID_NONCE", message: "Unknown, used or expired nonce" });
|
|
306
|
+
})
|
|
307
|
+
}
|
|
308
|
+
]
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
}
|
|
213
312
|
var CONFIRMED_ACCOUNT_LINKING = {
|
|
214
313
|
enabled: true,
|
|
215
314
|
trustedProviders: [],
|
|
@@ -381,6 +480,8 @@ function standardAuthOptions(input) {
|
|
|
381
480
|
}),
|
|
382
481
|
admin(input.admin),
|
|
383
482
|
bearer(),
|
|
483
|
+
...settings.rateLimit ? [accountSignInLimit(input.rateLimitStorage ?? memoryRateLimit())] : [],
|
|
484
|
+
...settings.google ? [googleIdTokenNonce({ mode: input.googleNonce ?? "optional" })] : [],
|
|
384
485
|
...input.plugins ?? [],
|
|
385
486
|
...input.lastPlugin ? [input.lastPlugin] : []
|
|
386
487
|
]
|
|
@@ -393,7 +494,7 @@ async function authResult(action) {
|
|
|
393
494
|
await action();
|
|
394
495
|
return { ok: true };
|
|
395
496
|
} catch (error) {
|
|
396
|
-
if (error instanceof
|
|
497
|
+
if (error instanceof APIError2)
|
|
397
498
|
return { ok: false, code: String(error.body?.code ?? error.status) };
|
|
398
499
|
throw error;
|
|
399
500
|
}
|
|
@@ -401,18 +502,48 @@ async function authResult(action) {
|
|
|
401
502
|
var AUTH_SERVER_CODES = {
|
|
402
503
|
unauthorized: "UNAUTHORIZED",
|
|
403
504
|
passwordRequired: "INVALID_PASSWORD",
|
|
404
|
-
|
|
505
|
+
reauthRequired: "REAUTH_REQUIRED",
|
|
405
506
|
invalidLogin: "INVALID_EMAIL_OR_PASSWORD",
|
|
406
507
|
noRedirect: "NO_REDIRECT_URL",
|
|
407
|
-
self: "CANNOT_ACT_ON_SELF"
|
|
508
|
+
self: "CANNOT_ACT_ON_SELF",
|
|
509
|
+
tooManyRequests: "TOO_MANY_REQUESTS"
|
|
408
510
|
};
|
|
511
|
+
var REAUTH_MINUTES = 5;
|
|
409
512
|
function temporaryPassword() {
|
|
410
513
|
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(18));
|
|
411
514
|
return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_");
|
|
412
515
|
}
|
|
413
516
|
var iso = (value) => new Date(value).toISOString();
|
|
414
517
|
function authServer(config) {
|
|
415
|
-
|
|
518
|
+
if (config.rateLimit === "off") {
|
|
519
|
+
const env = globalThis.process?.env ?? {};
|
|
520
|
+
if (env.NODE_ENV === "production" && env.E2E !== "1")
|
|
521
|
+
throw new Error("authServer: rateLimit 'off' on a production server. It is for E2E runs only (E2E=1).");
|
|
522
|
+
console.warn("authServer: rate limits are off (rateLimit: 'off'). Only E2E runs may do this.");
|
|
523
|
+
}
|
|
524
|
+
const instance = async () => typeof config.auth === "function" ? await config.auth() : config.auth;
|
|
525
|
+
const api = async () => (await instance()).api;
|
|
526
|
+
let warnedNoIp = false;
|
|
527
|
+
async function limited(path, also = []) {
|
|
528
|
+
if (config.rateLimit === "off")
|
|
529
|
+
return null;
|
|
530
|
+
const rule = RATE_LIMIT_RULES[path];
|
|
531
|
+
const ip = getIP(config.headers(), (await instance()).options);
|
|
532
|
+
const keys = [...ip ? [`${ip}|${path}`] : [], ...also.map((key) => `${key}|${path}`)];
|
|
533
|
+
if (!ip && !warnedNoIp) {
|
|
534
|
+
warnedNoIp = true;
|
|
535
|
+
console.warn("auth rate limit: no client address in this request's headers; check Better Auth's advanced.ipAddress.ipAddressHeaders");
|
|
536
|
+
}
|
|
537
|
+
if (keys.length === 0)
|
|
538
|
+
keys.push(`unknown|${path}`);
|
|
539
|
+
let retryAfter = 0;
|
|
540
|
+
for (const key of keys) {
|
|
541
|
+
const answer = await config.rateLimit.storage.consume(key, rule);
|
|
542
|
+
if (!answer.allowed)
|
|
543
|
+
retryAfter = Math.max(retryAfter, answer.retryAfter ?? rule.window);
|
|
544
|
+
}
|
|
545
|
+
return retryAfter ? { ok: false, code: AUTH_SERVER_CODES.tooManyRequests, retryAfter } : null;
|
|
546
|
+
}
|
|
416
547
|
async function viewer(options = {}) {
|
|
417
548
|
const session = await (await api()).getSession({
|
|
418
549
|
headers: config.headers(),
|
|
@@ -430,7 +561,7 @@ function authServer(config) {
|
|
|
430
561
|
const answer = await start();
|
|
431
562
|
return answer.url ? { ok: true, url: answer.url } : { ok: false, code: AUTH_SERVER_CODES.noRedirect };
|
|
432
563
|
} catch (error) {
|
|
433
|
-
if (error instanceof
|
|
564
|
+
if (error instanceof APIError2)
|
|
434
565
|
return { ok: false, code: String(error.body?.code ?? error.status) };
|
|
435
566
|
throw error;
|
|
436
567
|
}
|
|
@@ -457,6 +588,9 @@ function authServer(config) {
|
|
|
457
588
|
const login = input.login.trim();
|
|
458
589
|
if (login.includes("@") && isPlaceholderEmail(login))
|
|
459
590
|
return { ok: false, code: AUTH_SERVER_CODES.invalidLogin };
|
|
591
|
+
const refused = await limited(login.includes("@") ? "/sign-in/email" : "/sign-in/username", []);
|
|
592
|
+
if (refused)
|
|
593
|
+
return refused;
|
|
460
594
|
const auth = await api();
|
|
461
595
|
const headers = config.headers();
|
|
462
596
|
return authResult(() => login.includes("@") ? auth.signInEmail({ body: { email: login, password: input.password }, headers }) : auth.signInUsername({ body: { username: login, password: input.password }, headers }));
|
|
@@ -464,6 +598,9 @@ function authServer(config) {
|
|
|
464
598
|
async signUp(input) {
|
|
465
599
|
if (input.email && isPlaceholderEmail(input.email))
|
|
466
600
|
return { ok: false, code: "INVALID_EMAIL" };
|
|
601
|
+
const refused = await limited("/sign-up/email");
|
|
602
|
+
if (refused)
|
|
603
|
+
return refused;
|
|
467
604
|
const auth = await api();
|
|
468
605
|
const email = input.email || placeholderEmail(config.randomId);
|
|
469
606
|
return authResult(() => auth.signUpEmail({
|
|
@@ -476,6 +613,12 @@ function authServer(config) {
|
|
|
476
613
|
return authResult(() => auth.signOut({ headers: config.headers() }));
|
|
477
614
|
},
|
|
478
615
|
async changePassword(input) {
|
|
616
|
+
const me = await viewer({ fresh: true });
|
|
617
|
+
if (!me)
|
|
618
|
+
return { ok: false, code: AUTH_SERVER_CODES.unauthorized };
|
|
619
|
+
const refused = await limited("/change-password", [`user:${me.id}`]);
|
|
620
|
+
if (refused)
|
|
621
|
+
return refused;
|
|
479
622
|
const auth = await api();
|
|
480
623
|
return authResult(() => auth.changePassword({
|
|
481
624
|
body: { currentPassword: input.currentPassword, newPassword: input.newPassword, revokeOtherSessions: true },
|
|
@@ -483,6 +626,12 @@ function authServer(config) {
|
|
|
483
626
|
}));
|
|
484
627
|
},
|
|
485
628
|
async setFirstPassword(input) {
|
|
629
|
+
const me = await viewer({ fresh: true });
|
|
630
|
+
if (!me)
|
|
631
|
+
return { ok: false, code: AUTH_SERVER_CODES.unauthorized };
|
|
632
|
+
const refused = await limited("/set-password", [`user:${me.id}`]);
|
|
633
|
+
if (refused)
|
|
634
|
+
return refused;
|
|
486
635
|
const auth = await api();
|
|
487
636
|
return authResult(() => auth.setPassword({ body: { newPassword: input.newPassword }, headers: config.headers() }));
|
|
488
637
|
},
|
|
@@ -497,6 +646,9 @@ function authServer(config) {
|
|
|
497
646
|
return authResult(() => auth.deletePasskey({ body: { id }, headers: config.headers() }));
|
|
498
647
|
},
|
|
499
648
|
async googleStartUrl(input) {
|
|
649
|
+
const refused = await limited("/sign-in/social");
|
|
650
|
+
if (refused)
|
|
651
|
+
return refused;
|
|
500
652
|
const redirect = safeRedirect(input.redirect);
|
|
501
653
|
const back = redirect ? `?redirect=${encodeURIComponent(redirect)}` : "";
|
|
502
654
|
const auth = await api();
|
|
@@ -506,8 +658,12 @@ function authServer(config) {
|
|
|
506
658
|
}));
|
|
507
659
|
},
|
|
508
660
|
async googleLinkUrl(input) {
|
|
509
|
-
|
|
661
|
+
const me = await viewer();
|
|
662
|
+
if (!me)
|
|
510
663
|
return { ok: false, code: AUTH_SERVER_CODES.unauthorized };
|
|
664
|
+
const refused = await limited("/sign-in/social", [`user:${me.id}`]);
|
|
665
|
+
if (refused)
|
|
666
|
+
return refused;
|
|
511
667
|
const auth = await api();
|
|
512
668
|
return googleUrl(() => auth.linkSocialAccount({
|
|
513
669
|
body: { provider: "google", callbackURL: `${input.accountPath}?connected=google`, errorCallbackURL: input.accountPath },
|
|
@@ -515,19 +671,24 @@ function authServer(config) {
|
|
|
515
671
|
}));
|
|
516
672
|
},
|
|
517
673
|
async deleteOwnAccount(input) {
|
|
518
|
-
const me = await viewer();
|
|
519
|
-
if (!me)
|
|
520
|
-
return { ok: false, code: AUTH_SERVER_CODES.unauthorized };
|
|
521
674
|
const auth = await api();
|
|
522
675
|
const headers = config.headers();
|
|
676
|
+
const current = await auth.getSession({ headers, query: { disableCookieCache: true } });
|
|
677
|
+
const me = toAuthUser(current?.user, config.roleOf);
|
|
678
|
+
if (!current || !me)
|
|
679
|
+
return { ok: false, code: AUTH_SERVER_CODES.unauthorized };
|
|
680
|
+
const refused = await limited("/delete-user", [`user:${me.id}`]);
|
|
681
|
+
if (refused)
|
|
682
|
+
return refused;
|
|
523
683
|
if ((await signInMethods()).password) {
|
|
524
684
|
const password = input.password;
|
|
525
685
|
if (!password)
|
|
526
686
|
return { ok: false, code: AUTH_SERVER_CODES.passwordRequired };
|
|
527
687
|
return authResult(() => auth.deleteUser({ body: { password }, headers }));
|
|
528
688
|
}
|
|
529
|
-
|
|
530
|
-
|
|
689
|
+
const signedInAt = new Date(current.session.createdAt).getTime();
|
|
690
|
+
if (!(Date.now() - signedInAt < REAUTH_MINUTES * 60000))
|
|
691
|
+
return { ok: false, code: AUTH_SERVER_CODES.reauthRequired };
|
|
531
692
|
return authResult(() => auth.deleteUser({ body: {}, headers }));
|
|
532
693
|
},
|
|
533
694
|
admin: {
|
|
@@ -576,6 +737,7 @@ function authServer(config) {
|
|
|
576
737
|
}
|
|
577
738
|
export {
|
|
578
739
|
AUTH_SERVER_CODES,
|
|
740
|
+
REAUTH_MINUTES,
|
|
579
741
|
authResult,
|
|
580
742
|
authServer,
|
|
581
743
|
temporaryPassword
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The auth libraries this kit release is tested with. Every app pins exactly these, so the auth set
|
|
3
|
+
* moves in all apps together (one PR series), never one app at a time. No imports: a CI script reads it.
|
|
4
|
+
*
|
|
5
|
+
* import { AUTH_VERSIONS, authVersionProblems } from '@jgb-solutions/kit/auth/versions'
|
|
6
|
+
* const problems = authVersionProblems(dependenciesOfEveryPackageJson)
|
|
7
|
+
*/
|
|
8
|
+
export declare const AUTH_VERSIONS: {
|
|
9
|
+
readonly 'better-auth': "1.7.29";
|
|
10
|
+
readonly '@better-auth/passkey': "1.7.29";
|
|
11
|
+
readonly jose: "6.2.19";
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* What differs from AUTH_VERSIONS in one package file's dependencies: each auth library the file
|
|
15
|
+
* lists must be pinned to exactly the kit's version (no ranges). Libraries it doesn't list are fine.
|
|
16
|
+
*/
|
|
17
|
+
export declare function authVersionProblems(dependencies: Readonly<Record<string, string>>): string[];
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// src/auth/versions.ts
|
|
2
|
+
var AUTH_VERSIONS = {
|
|
3
|
+
"better-auth": "1.7.29",
|
|
4
|
+
"@better-auth/passkey": "1.7.29",
|
|
5
|
+
jose: "6.2.19"
|
|
6
|
+
};
|
|
7
|
+
function authVersionProblems(dependencies) {
|
|
8
|
+
const problems = [];
|
|
9
|
+
for (const [name, wanted] of Object.entries(AUTH_VERSIONS)) {
|
|
10
|
+
const found = dependencies[name];
|
|
11
|
+
if (found !== undefined && found !== wanted)
|
|
12
|
+
problems.push(`${name} is ${found}, the kit's auth set has ${wanted}`);
|
|
13
|
+
}
|
|
14
|
+
return problems;
|
|
15
|
+
}
|
|
16
|
+
export {
|
|
17
|
+
AUTH_VERSIONS,
|
|
18
|
+
authVersionProblems
|
|
19
|
+
};
|
package/dist/auth.d.ts
CHANGED
|
@@ -107,18 +107,86 @@ export declare const RATE_LIMIT_RULES: {
|
|
|
107
107
|
readonly window: 60;
|
|
108
108
|
readonly max: 5;
|
|
109
109
|
};
|
|
110
|
+
readonly '/google/nonce': {
|
|
111
|
+
readonly window: 60;
|
|
112
|
+
readonly max: 10;
|
|
113
|
+
};
|
|
110
114
|
};
|
|
111
115
|
/** A counter store: Redis, Dragonfly, Workers KV with a Durable Object, or anything with an atomic increment. */
|
|
112
116
|
export type CounterStore = {
|
|
113
117
|
/** Adds 1 to `key` and returns the new count; a new key expires after `ttlSeconds`. */
|
|
114
118
|
incr(key: string, ttlSeconds: number): Promise<number>;
|
|
115
119
|
};
|
|
120
|
+
/**
|
|
121
|
+
* Rate-limit counts in this process's memory: a fixed window per key, at most `maxKeys` keys (the
|
|
122
|
+
* oldest dropped first). The floor when the shared store is down, and enough for a single server.
|
|
123
|
+
*/
|
|
124
|
+
export declare function memoryRateLimit(now?: () => number, maxKeys?: number): BetterAuthRateLimitStorage;
|
|
116
125
|
/**
|
|
117
126
|
* Rate-limit counts in a counter store (one increment per attempt, on a key per fixed window), never
|
|
118
|
-
* as a database row per attempt. When the store can't answer,
|
|
119
|
-
* the
|
|
127
|
+
* as a database row per attempt. When the store can't answer, this process counts in memory instead
|
|
128
|
+
* (and logs it): the limit holds per server until the store is back, and sign-in never goes down with
|
|
129
|
+
* the cache.
|
|
120
130
|
*/
|
|
121
131
|
export declare function counterRateLimit(store: () => CounterStore, now?: () => number): BetterAuthRateLimitStorage;
|
|
132
|
+
/**
|
|
133
|
+
* Sign-in attempts with one login (a username or an address), from any address: enough for a person
|
|
134
|
+
* who mistypes, too few to guess a password. Someone who knows a username can use it up and keep its
|
|
135
|
+
* owner out of password sign-in for a while (the price of any per-account limit); a passkey or Google
|
|
136
|
+
* still works meanwhile. An account with an email has two logins, so two counts.
|
|
137
|
+
*/
|
|
138
|
+
export declare const ACCOUNT_SIGN_IN_RULE: {
|
|
139
|
+
readonly window: number;
|
|
140
|
+
readonly max: 30;
|
|
141
|
+
};
|
|
142
|
+
/**
|
|
143
|
+
* Counts every password sign-in per login, before the password is checked: through /api/auth and
|
|
144
|
+
* through direct `auth.api` calls alike (a hook runs for both), so changing address doesn't reset it.
|
|
145
|
+
* The key is a hash, never the login itself. Over the limit: 429 TOO_MANY_REQUESTS.
|
|
146
|
+
*/
|
|
147
|
+
export declare function accountSignInLimit(storage: BetterAuthRateLimitStorage): {
|
|
148
|
+
id: "account-sign-in-limit";
|
|
149
|
+
hooks: {
|
|
150
|
+
before: {
|
|
151
|
+
matcher: (ctx: {
|
|
152
|
+
path?: string;
|
|
153
|
+
}) => boolean;
|
|
154
|
+
handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
|
|
155
|
+
}[];
|
|
156
|
+
};
|
|
157
|
+
};
|
|
158
|
+
/** How long a Google sign-in nonce stays usable. */
|
|
159
|
+
export declare const GOOGLE_NONCE_MINUTES = 5;
|
|
160
|
+
/**
|
|
161
|
+
* Single-use nonces for Google ID tokens (the app's native Google sheet). Better Auth checks a nonce
|
|
162
|
+
* only when the client sends one, so a stolen ID token could be replayed for its whole hour. With this
|
|
163
|
+
* plugin the app first asks POST /google/nonce, puts that nonce in Google's request and sends it with
|
|
164
|
+
* the token; the nonce is spent on first use (INVALID_NONCE for an unknown, spent or expired one) and
|
|
165
|
+
* Better Auth then checks the token carries it.
|
|
166
|
+
*
|
|
167
|
+
* `'optional'` still lets a token without a nonce through, for app builds made before this; switch
|
|
168
|
+
* to `'required'` once every installed build sends one. The website's Google redirect is untouched.
|
|
169
|
+
*/
|
|
170
|
+
export declare function googleIdTokenNonce(options: {
|
|
171
|
+
mode: 'optional' | 'required';
|
|
172
|
+
}): {
|
|
173
|
+
id: "google-id-token-nonce";
|
|
174
|
+
endpoints: {
|
|
175
|
+
googleNonce: import("better-call").StrictEndpoint<"/google/nonce", {
|
|
176
|
+
method: "POST";
|
|
177
|
+
}, {
|
|
178
|
+
nonce: string;
|
|
179
|
+
}>;
|
|
180
|
+
};
|
|
181
|
+
hooks: {
|
|
182
|
+
before: {
|
|
183
|
+
matcher: (ctx: {
|
|
184
|
+
path?: string;
|
|
185
|
+
}) => boolean;
|
|
186
|
+
handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
|
|
187
|
+
}[];
|
|
188
|
+
};
|
|
189
|
+
};
|
|
122
190
|
/**
|
|
123
191
|
* Account linking, "merge only confirmed" (owner, 2026-11-24):
|
|
124
192
|
*
|
|
@@ -279,6 +347,11 @@ export type StandardAuthInput<A extends AdminOptions> = {
|
|
|
279
347
|
rateLimitStorage?: BetterAuthRateLimitStorage;
|
|
280
348
|
/** Bun's argon2id (`@jgb-solutions/kit/auth/bun`); without it, Better Auth's scrypt. */
|
|
281
349
|
password?: PasswordHasher;
|
|
350
|
+
/**
|
|
351
|
+
* Google ID-token nonces (the app's native sign-in): `'optional'` (the default) or `'required'` once
|
|
352
|
+
* every installed app build sends one. See `googleIdTokenNonce`.
|
|
353
|
+
*/
|
|
354
|
+
googleNonce?: 'optional' | 'required';
|
|
282
355
|
/** The name of a readable "signed in" cookie, when cached public pages need one. */
|
|
283
356
|
signedInFlag?: string;
|
|
284
357
|
/** Removes the account's own data before it is deleted. Without it, accounts can't delete themselves. */
|
|
@@ -2053,7 +2126,34 @@ export declare function standardAuthOptions<A extends AdminOptions>(input: Stand
|
|
|
2053
2126
|
}[];
|
|
2054
2127
|
};
|
|
2055
2128
|
options: import("better-auth/plugins").BearerOptions | undefined;
|
|
2056
|
-
}, ...BetterAuthPlugin
|
|
2129
|
+
}, ...(BetterAuthPlugin | {
|
|
2130
|
+
id: "account-sign-in-limit";
|
|
2131
|
+
hooks: {
|
|
2132
|
+
before: {
|
|
2133
|
+
matcher: (ctx: {
|
|
2134
|
+
path?: string;
|
|
2135
|
+
}) => boolean;
|
|
2136
|
+
handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
|
|
2137
|
+
}[];
|
|
2138
|
+
};
|
|
2139
|
+
} | {
|
|
2140
|
+
id: "google-id-token-nonce";
|
|
2141
|
+
endpoints: {
|
|
2142
|
+
googleNonce: import("better-call").StrictEndpoint<"/google/nonce", {
|
|
2143
|
+
method: "POST";
|
|
2144
|
+
}, {
|
|
2145
|
+
nonce: string;
|
|
2146
|
+
}>;
|
|
2147
|
+
};
|
|
2148
|
+
hooks: {
|
|
2149
|
+
before: {
|
|
2150
|
+
matcher: (ctx: {
|
|
2151
|
+
path?: string;
|
|
2152
|
+
}) => boolean;
|
|
2153
|
+
handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
|
|
2154
|
+
}[];
|
|
2155
|
+
};
|
|
2156
|
+
})[]];
|
|
2057
2157
|
hooks?: {
|
|
2058
2158
|
after: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
|
|
2059
2159
|
};
|
|
@@ -2099,6 +2199,10 @@ export declare function standardAuthOptions<A extends AdminOptions>(input: Stand
|
|
|
2099
2199
|
readonly window: 60;
|
|
2100
2200
|
readonly max: 5;
|
|
2101
2201
|
};
|
|
2202
|
+
'/google/nonce': {
|
|
2203
|
+
readonly window: 60;
|
|
2204
|
+
readonly max: 10;
|
|
2205
|
+
};
|
|
2102
2206
|
};
|
|
2103
2207
|
} | {
|
|
2104
2208
|
storage: "database";
|
|
@@ -2142,6 +2246,10 @@ export declare function standardAuthOptions<A extends AdminOptions>(input: Stand
|
|
|
2142
2246
|
readonly window: 60;
|
|
2143
2247
|
readonly max: 5;
|
|
2144
2248
|
};
|
|
2249
|
+
'/google/nonce': {
|
|
2250
|
+
readonly window: 60;
|
|
2251
|
+
readonly max: 10;
|
|
2252
|
+
};
|
|
2145
2253
|
};
|
|
2146
2254
|
};
|
|
2147
2255
|
databaseHooks: {
|
package/dist/auth.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// src/auth.ts
|
|
2
2
|
import { passkey } from "@better-auth/passkey";
|
|
3
|
-
import { createAuthMiddleware } from "better-auth/api";
|
|
3
|
+
import { APIError, createAuthEndpoint, createAuthMiddleware } from "better-auth/api";
|
|
4
4
|
import { admin } from "better-auth/plugins/admin";
|
|
5
5
|
import { bearer } from "better-auth/plugins/bearer";
|
|
6
6
|
import { username } from "better-auth/plugins/username";
|
|
@@ -187,9 +187,32 @@ var RATE_LIMIT_RULES = {
|
|
|
187
187
|
"/passkey/*": { window: 60, max: 20 },
|
|
188
188
|
"/change-password": { window: 60, max: 5 },
|
|
189
189
|
"/set-password": { window: 60, max: 5 },
|
|
190
|
-
"/delete-user": { window: 60, max: 5 }
|
|
190
|
+
"/delete-user": { window: 60, max: 5 },
|
|
191
|
+
"/google/nonce": { window: 60, max: 10 }
|
|
191
192
|
};
|
|
193
|
+
function memoryRateLimit(now = Date.now, maxKeys = 1e5) {
|
|
194
|
+
const counts = new Map;
|
|
195
|
+
return {
|
|
196
|
+
async consume(key, rule) {
|
|
197
|
+
const windowMs = rule.window * 1000;
|
|
198
|
+
const slot = Math.floor(now() / windowMs);
|
|
199
|
+
const entry = counts.get(key);
|
|
200
|
+
const count = entry && entry.slot === slot ? entry.count + 1 : 1;
|
|
201
|
+
counts.delete(key);
|
|
202
|
+
counts.set(key, { slot, count });
|
|
203
|
+
if (counts.size > maxKeys) {
|
|
204
|
+
const oldest = counts.keys().next().value;
|
|
205
|
+
if (oldest !== undefined)
|
|
206
|
+
counts.delete(oldest);
|
|
207
|
+
}
|
|
208
|
+
if (count <= rule.max)
|
|
209
|
+
return { allowed: true, retryAfter: null };
|
|
210
|
+
return { allowed: false, retryAfter: Math.max(1, Math.ceil(((slot + 1) * windowMs - now()) / 1000)) };
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
}
|
|
192
214
|
function counterRateLimit(store, now = Date.now) {
|
|
215
|
+
const fallback = memoryRateLimit(now);
|
|
193
216
|
return {
|
|
194
217
|
async consume(key, rule) {
|
|
195
218
|
const windowMs = rule.window * 1000;
|
|
@@ -198,8 +221,8 @@ function counterRateLimit(store, now = Date.now) {
|
|
|
198
221
|
try {
|
|
199
222
|
count = await store().incr(`auth-limit:${key}:${slot}`, rule.window);
|
|
200
223
|
} catch (error) {
|
|
201
|
-
console.warn("auth rate limit: store unavailable,
|
|
202
|
-
return
|
|
224
|
+
console.warn("auth rate limit: store unavailable, counting in memory", error);
|
|
225
|
+
return fallback.consume(key, rule);
|
|
203
226
|
}
|
|
204
227
|
if (count <= rule.max)
|
|
205
228
|
return { allowed: true, retryAfter: null };
|
|
@@ -207,6 +230,82 @@ function counterRateLimit(store, now = Date.now) {
|
|
|
207
230
|
}
|
|
208
231
|
};
|
|
209
232
|
}
|
|
233
|
+
var ACCOUNT_SIGN_IN_RULE = { window: 15 * 60, max: 30 };
|
|
234
|
+
var SIGN_IN_FIELDS = { "/sign-in/email": "email", "/sign-in/username": "username" };
|
|
235
|
+
async function sha256Hex(text) {
|
|
236
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
237
|
+
return Array.from(new Uint8Array(digest).slice(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
238
|
+
}
|
|
239
|
+
function accountSignInLimit(storage) {
|
|
240
|
+
return {
|
|
241
|
+
id: "account-sign-in-limit",
|
|
242
|
+
hooks: {
|
|
243
|
+
before: [
|
|
244
|
+
{
|
|
245
|
+
matcher: (ctx) => Object.hasOwn(SIGN_IN_FIELDS, ctx.path ?? ""),
|
|
246
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
247
|
+
const field = SIGN_IN_FIELDS[ctx.path];
|
|
248
|
+
const body = ctx.body;
|
|
249
|
+
const login = field && typeof body === "object" && body !== null && field in body ? body[field] : undefined;
|
|
250
|
+
if (typeof login !== "string" || !login.trim())
|
|
251
|
+
return;
|
|
252
|
+
const key = `login:${await sha256Hex(login.trim().toLowerCase())}|/sign-in`;
|
|
253
|
+
const answer = await storage.consume(key, ACCOUNT_SIGN_IN_RULE);
|
|
254
|
+
if (!answer.allowed)
|
|
255
|
+
throw APIError.from("TOO_MANY_REQUESTS", { code: "TOO_MANY_REQUESTS", message: "Too many sign-in attempts for this account" });
|
|
256
|
+
})
|
|
257
|
+
}
|
|
258
|
+
]
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
var GOOGLE_NONCE_MINUTES = 5;
|
|
263
|
+
var NONCE_PATHS = new Set(["/sign-in/social", "/link-social"]);
|
|
264
|
+
function googleIdTokenNonce(options) {
|
|
265
|
+
return {
|
|
266
|
+
id: "google-id-token-nonce",
|
|
267
|
+
endpoints: {
|
|
268
|
+
googleNonce: createAuthEndpoint("/google/nonce", { method: "POST" }, async (ctx) => {
|
|
269
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
|
|
270
|
+
const nonce = btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
|
|
271
|
+
const stored = await ctx.context.internalAdapter.createVerificationValue({
|
|
272
|
+
identifier: `google-nonce:${nonce}`,
|
|
273
|
+
value: "1",
|
|
274
|
+
expiresAt: new Date(Date.now() + GOOGLE_NONCE_MINUTES * 60000)
|
|
275
|
+
});
|
|
276
|
+
if (!stored)
|
|
277
|
+
throw APIError.from("INTERNAL_SERVER_ERROR", { code: "NONCE_NOT_STORED", message: "The nonce could not be stored" });
|
|
278
|
+
await ctx.context.runInBackgroundOrAwait(ctx.context.adapter.deleteMany({ model: "verification", where: [{ field: "expiresAt", operator: "lt", value: new Date }] }).then(() => {
|
|
279
|
+
return;
|
|
280
|
+
}).catch((error) => ctx.context.logger.error("google nonce: expired rows not swept", error)));
|
|
281
|
+
ctx.setHeader("cache-control", "no-store");
|
|
282
|
+
return ctx.json({ nonce });
|
|
283
|
+
})
|
|
284
|
+
},
|
|
285
|
+
hooks: {
|
|
286
|
+
before: [
|
|
287
|
+
{
|
|
288
|
+
matcher: (ctx) => NONCE_PATHS.has(ctx.path ?? ""),
|
|
289
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
290
|
+
const body = ctx.body;
|
|
291
|
+
const idToken = typeof body === "object" && body !== null && "idToken" in body ? body.idToken : undefined;
|
|
292
|
+
if (typeof idToken !== "object" || idToken === null)
|
|
293
|
+
return;
|
|
294
|
+
const nonce = "nonce" in idToken && typeof idToken.nonce === "string" ? idToken.nonce : "";
|
|
295
|
+
if (!nonce) {
|
|
296
|
+
if (options.mode === "required")
|
|
297
|
+
throw APIError.from("BAD_REQUEST", { code: "NONCE_REQUIRED", message: "A nonce is required" });
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
const spent = await ctx.context.internalAdapter.consumeVerificationValue(`google-nonce:${nonce}`);
|
|
301
|
+
if (!spent)
|
|
302
|
+
throw APIError.from("BAD_REQUEST", { code: "INVALID_NONCE", message: "Unknown, used or expired nonce" });
|
|
303
|
+
})
|
|
304
|
+
}
|
|
305
|
+
]
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
}
|
|
210
309
|
var CONFIRMED_ACCOUNT_LINKING = {
|
|
211
310
|
enabled: true,
|
|
212
311
|
trustedProviders: [],
|
|
@@ -378,14 +477,19 @@ function standardAuthOptions(input) {
|
|
|
378
477
|
}),
|
|
379
478
|
admin(input.admin),
|
|
380
479
|
bearer(),
|
|
480
|
+
...settings.rateLimit ? [accountSignInLimit(input.rateLimitStorage ?? memoryRateLimit())] : [],
|
|
481
|
+
...settings.google ? [googleIdTokenNonce({ mode: input.googleNonce ?? "optional" })] : [],
|
|
381
482
|
...input.plugins ?? [],
|
|
382
483
|
...input.lastPlugin ? [input.lastPlugin] : []
|
|
383
484
|
]
|
|
384
485
|
};
|
|
385
486
|
}
|
|
386
487
|
export {
|
|
488
|
+
ACCOUNT_SIGN_IN_RULE,
|
|
387
489
|
CONFIRMED_ACCOUNT_LINKING,
|
|
490
|
+
GOOGLE_NONCE_MINUTES,
|
|
388
491
|
RATE_LIMIT_RULES,
|
|
492
|
+
accountSignInLimit,
|
|
389
493
|
afterAccountSaved,
|
|
390
494
|
androidOrigin,
|
|
391
495
|
asPublicRequest,
|
|
@@ -393,7 +497,9 @@ export {
|
|
|
393
497
|
authSettings,
|
|
394
498
|
counterRateLimit,
|
|
395
499
|
freeUsername,
|
|
500
|
+
googleIdTokenNonce,
|
|
396
501
|
googleProvider,
|
|
502
|
+
memoryRateLimit,
|
|
397
503
|
passkeyOrigins,
|
|
398
504
|
pictureFromIdToken,
|
|
399
505
|
roleForNewUser,
|
package/dist/i18n.js
CHANGED
|
@@ -103,7 +103,7 @@ function isPlural(value) {
|
|
|
103
103
|
function leafAt(messages, key) {
|
|
104
104
|
let node = messages;
|
|
105
105
|
for (const part of key.split(".")) {
|
|
106
|
-
if (!isRecord(node))
|
|
106
|
+
if (!isRecord(node) || !Object.hasOwn(node, part))
|
|
107
107
|
return;
|
|
108
108
|
node = node[part];
|
|
109
109
|
}
|
|
@@ -161,7 +161,7 @@ function createTranslator(locale, messages, fallback) {
|
|
|
161
161
|
const select = pluralSelector(locale);
|
|
162
162
|
const numbers = typeof Intl !== "undefined" && typeof Intl.NumberFormat === "function" ? new Intl.NumberFormat(locale) : undefined;
|
|
163
163
|
const fill = (template, params, formatNumbers) => template.replace(/\{(\w+)\}/g, (placeholder, name) => {
|
|
164
|
-
const value = params
|
|
164
|
+
const value = params && Object.hasOwn(params, name) ? params[name] : undefined;
|
|
165
165
|
if (value === undefined)
|
|
166
166
|
return placeholder;
|
|
167
167
|
return typeof value === "number" && formatNumbers && numbers ? numbers.format(value) : String(value);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jgb-solutions/kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "One package for JGB Solutions apps, in tree-shakable namespaces: Cloudflare Access, Better Auth (kit/access, kit/auth…) and the admin panel kit (kit/admin, React 19). An app bundles only the subpaths it imports.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "JGB Solutions",
|
|
@@ -73,6 +73,10 @@
|
|
|
73
73
|
"types": "./dist/auth/browser.d.ts",
|
|
74
74
|
"import": "./dist/auth/browser.js"
|
|
75
75
|
},
|
|
76
|
+
"./auth/versions": {
|
|
77
|
+
"types": "./dist/auth/versions.d.ts",
|
|
78
|
+
"import": "./dist/auth/versions.js"
|
|
79
|
+
},
|
|
76
80
|
"./auth/expo": {
|
|
77
81
|
"types": "./dist/auth/expo.d.ts",
|
|
78
82
|
"import": "./dist/auth/expo.js"
|