@jgb-solutions/kit 0.5.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 +41 -0
- package/README.md +37 -6
- package/dist/auth/browser.d.ts +77 -0
- package/dist/auth/browser.js +83 -0
- package/dist/auth/bun.d.ts +3 -2
- package/dist/auth/bun.js +4 -2
- package/dist/auth/expo.d.ts +65 -1
- package/dist/auth/expo.js +42 -2
- 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 +11 -2
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: {
|