@jgb-solutions/kit 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
- /** Where to go after signing in: `next`, with `#done=<kind>` when something was done. */
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,
@@ -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 {
@@ -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
- /** At launch: the saved token, checked with the server. A dead token is dropped; offline, the app shows signed out. */
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`. `module`
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: "out" });
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 };
@@ -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 }) => next({ context: { user: await options.viewer() } }));
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
- if (!options.canOpenAdmin(context.user.role))
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: context.user } });
27
+ return next({ context: { user } });
20
28
  });
21
29
  return { withUser, requireUser, requireAdmin };
22
30
  }
@@ -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
- /** Deleting an account without a password: the typed username didn't match. */
19
- readonly confirmUsername: "CONFIRM_USERNAME";
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 (without one, Better Auth deletes any account whose session is under a day
240
- * old); an account without one (made with Google) types its username, and Better Auth then asks for
241
- * a sign-in from the last day (SESSION_EXPIRED otherwise).
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). */