@jgb-solutions/kit 0.4.4 → 0.6.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 CHANGED
@@ -2,6 +2,25 @@
2
2
 
3
3
  All notable changes to `@jgb-solutions/kit`. Versions follow semver.
4
4
 
5
+ ## 0.6.0
6
+
7
+ - `kit/auth/browser` (new, no dependencies):
8
+ - `passkeyClient({ webauthn })`: passkey sign-in and adding a passkey against Better Auth's endpoints, with the app's `@simplewebauthn/browser` passed in. Answers are codes (`CANCELLED`, `NETWORK`, `INVALID_OPTIONS`, or Better Auth's own).
9
+ - `createPendingAction<Kind>()`: what a signed-out visitor tapped, kept in this tab until sign-in.
10
+ - `afterSignIn(next, done)` adds the `#done=` flash.
11
+ - `readSignedInFlag(name)` reads the signed-in flag cookie.
12
+ - `kit/auth/expo`: `googleIdToken(module, webClientId)`, the ID token from the phone's Google account sheet (the app's native Credential Manager module). Errors are mapped to `CANCELLED`, `NO_GOOGLE_ACCOUNT`, `GOOGLE_UNAVAILABLE` or `GOOGLE_FAILED` (with a detail for the error tracker).
13
+
14
+ ## 0.5.0
15
+
16
+ The account logic every app copied, now in the kit. Nothing existing changes.
17
+
18
+ - `kit/auth/server` (new): `authServer({ auth, headers, roleOf, canOpenAdmin })`. It covers sign-in by username or email (placeholder addresses refused), sign-up, sign-out, changing a password (other devices signed out), a first password, passkeys, sign-in methods, the Google start and link addresses (redirect checked), and deleting one's own account (password, or the typed username for accounts without one). Admin: the viewer (fresh, through `toAuthUser`, so a suspended admin is out), the user list (placeholder addresses hidden), roles, bans and password resets, never on the admin's own account. Answers are codes, never English. Also `authResult`, `AUTH_SERVER_CODES` and `temporaryPassword`.
19
+ - `kit/auth/cache` (new): `sessionCookieNames(prefix)`, `hasSession`, `privatePaths(paths)` (with the language folder), `PRIVATE_HEADERS`, `makePrivate` (drops CDN caching headers) and `authRouteHandler`.
20
+ - `kit/auth/redis` (new): `redisCounterStore` for `counterRateLimit`, plus `RATE_LIMIT_SCRIPT_FALLBACK` (`[1, 0, 0]`) and `evalWithFallback` for oRPC's Redis limiter (beta.53+ reads `[0, 0]` as refused).
21
+ - `kit/auth/rules`: `safeRedirect` and `isSafeRedirectPath` (control characters, backslashes and percent-encoded tricks refused), `usernameErrorCode`, `displayNameProblem` and `defineSignInReasons`.
22
+ - `kit/auth/bun`: `argon2idHasher({ concurrency })` caps the hashes that run at once; also `concurrencyLimit`.
23
+
5
24
  ## 0.4.4
6
25
 
7
26
  - `@jgb-solutions/kit/i18n`: `createTranslator` no longer crashes where `Intl.PluralRules` is missing (Hermes on Android, so every Expo app on Android). It then picks plural forms with the new `cldrPluralCategory(locale, count)`, CLDR's rules for en, fr, es, ht, pt (and pt-PT) and ar, tested to give the same answers as `Intl.PluralRules`. Without `Intl.NumberFormat`, numbers print plainly.
package/README.md CHANGED
@@ -56,7 +56,7 @@ bun add @jgb-solutions/kit better-auth @better-auth/passkey
56
56
  import { betterAuth } from 'better-auth'
57
57
  import { tanstackStartCookies } from 'better-auth/tanstack-start'
58
58
  import { authSettings, standardAuthOptions } from '@jgb-solutions/kit/auth'
59
- import { argon2idHasher } from '@jgb-solutions/kit/auth/bun' // on Bun (Workers keep Better Auth's scrypt); fallbackVerify for older hashes
59
+ import { argon2idHasher } from '@jgb-solutions/kit/auth/bun' // on Bun (Workers keep Better Auth's scrypt); fallbackVerify for older hashes, concurrency to cap hashes at once
60
60
 
61
61
  export const auth = betterAuth(
62
62
  standardAuthOptions({
@@ -114,7 +114,55 @@ const { withUser, requireUser, requireAdmin } = authMiddleware({
114
114
 
115
115
  #### `kit/auth/rules`: the same rules in the browser
116
116
 
117
- `USERNAME`, `PASSWORD`, `usernameProblem`, `isPlaceholderEmail`, `placeholderEmail`, `defineRoles({ roles, defaultRole, adminPanel })` (`roleOf`, `canOpenAdmin`, `isRole`), the `AuthUser` type, `authErrorCode` with `ACCOUNT_NOT_LINKED`, `GOOGLE_ALREADY_LINKED` and `GOOGLE_EMAIL_NOT_CONFIRMED`, `avatarSrc` (https pictures only, sized) and `avatarInitials`. No dependencies.
117
+ `USERNAME`, `PASSWORD`, `usernameProblem`, `isPlaceholderEmail`, `placeholderEmail`, `defineRoles({ roles, defaultRole, adminPanel })` (`roleOf`, `canOpenAdmin`, `isRole`), the `AuthUser` type, `authErrorCode` with `ACCOUNT_NOT_LINKED`, `GOOGLE_ALREADY_LINKED` and `GOOGLE_EMAIL_NOT_CONFIRMED`, `avatarSrc` (https pictures only, sized) and `avatarInitials`.Also `usernameErrorCode` (a username's problem as Better Auth's code: `USERNAME_TOO_SHORT`, `USERNAME_TOO_LONG`, `INVALID_USERNAME`), `displayNameProblem(name, max = 50)`, `defineSignInReasons(list)` (an allow-list for `?reason=` or `#done=`: `reasonOf(value)` answers a listed code or undefined), and `safeRedirect(value)` / `isSafeRedirectPath(path)` for "back to where you were" after sign-in: a path on this site only, refusing `//host`, backslashes and control characters, also percent-encoded. No dependencies.
118
+
119
+ #### `kit/auth/server`: accounts on the server, answering codes
120
+
121
+ Sign-in, sign-up, passwords, passkeys, Google, deleting one's own account and the admin's user management, framework-free. Give it the Better Auth instance and the request's headers; call it from server functions or oRPC procedures. Failures are codes (`{ ok: false, code }`), Better Auth's own or `AUTH_SERVER_CODES`, for the app to word.
122
+
123
+ ```ts
124
+ import { authServer } from '@jgb-solutions/kit/auth/server'
125
+
126
+ const accounts = authServer({ auth: getAuth, headers: getRequestHeaders, roleOf, canOpenAdmin })
127
+
128
+ await accounts.viewer() // the signed-in person, or null (also when suspended); { fresh: true } skips the cookie cache
129
+ await accounts.signIn({ login, password }) // username or email; a placeholder address never signs in
130
+ await accounts.signUp({ username, password, email }) // no email: a placeholder address
131
+ await accounts.changePassword({ currentPassword, newPassword }) // signs out the other devices
132
+ await accounts.passkeys() // newest first
133
+ await accounts.googleStartUrl({ redirect, home: '/account', signInPath: '/sign-in' }) // redirect checked with safeRedirect
134
+ await accounts.deleteOwnAccount({ password }) // or { confirmUsername } for an account without a password
135
+ await accounts.admin.listUsers({ page, pageSize: 25, search })
136
+ await accounts.admin.ban({ userId }) // also setRole, unban, resetPassword: never on the admin's own account
137
+ ```
138
+
139
+ 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
+
141
+ #### `kit/auth/cache`: per-person pages stay out of shared caches
142
+
143
+ CDN cache keys ignore cookies, so a signed-in page stored once reaches the next visitor. `hasSession(cookieHeader, sessionCookieNames(prefix))` spots a session by exact cookie name (with Better Auth's `cookiePrefix`, if the app changed it). `privatePaths(['admin', 'account', 'sign-in'])` matches those pages and what's under them, in every language folder (`/fr/account`). `makePrivate(response)` sets `private, no-store` and drops `cdn-cache-control` and `cloudflare-cdn-cache-control`. `authRouteHandler(getAuth, { publicRequest })` serves `/api/auth/*` with every answer private.
144
+
145
+ #### `kit/auth/redis`: counters in Redis or a compatible store
146
+
147
+ `redisCounterStore(redis, 'app:')` is a counter store for `counterRateLimit`, with any client that has `incr` and `expire` (Bun's `RedisClient`, ioredis). For oRPC's Redis limiter, `evalWithFallback(() => redis.send('EVAL', …))` answers `RATE_LIMIT_SCRIPT_FALLBACK` (`[1, 0, 0]`: allowed, nothing counted) while the store is away. From oRPC 2.0.0-beta.53 the old `[0, 0]` reads as refused, and every call failed.
148
+
149
+ #### `kit/auth/browser`: passkeys and pending actions in the website
150
+
151
+ No dependencies: the app passes `@simplewebauthn/browser` in, loaded only when a passkey button is pressed.
152
+
153
+ ```ts
154
+ import { afterSignIn, createPendingAction, passkeyClient, readSignedInFlag } from '@jgb-solutions/kit/auth/browser'
155
+
156
+ const passkeys = passkeyClient({ webauthn: () => import('@simplewebauthn/browser') }) // Better Auth's /api/auth/passkey
157
+ await passkeys.signIn() // { ok: true } or { ok: false, code } (CANCELLED, NETWORK, Better Auth's codes)
158
+ await passkeys.add('My laptop')
159
+
160
+ export const pending = createPendingAction<'favorite' | 'follow'>() // what a signed-out visitor tapped, in this tab only
161
+ pending.set({ kind: 'favorite', name: song.title, run: () => addFavorite(song.id) })
162
+ const done = await pending.finish('signed-in') // after sign-in: runs it, answers its kind
163
+ location.assign(afterSignIn(redirect, done)) // …#done=favorite for the confirmation
164
+ readSignedInFlag('example_in') // the readable flag cookie standardAuthOptions sets (a hint; the server checks)
165
+ ```
118
166
 
119
167
  #### `kit/auth/expo`: the mobile app
120
168
 
@@ -141,6 +189,8 @@ await auth.signInWithPasskey(Passkeys)
141
189
  new RPCLink({ url, headers: auth.authHeaders }) // Bearer on every RPC call
142
190
  ```
143
191
 
192
+ On Android, `googleIdToken(nativeModule, webClientId)` 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
+
144
194
  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.
145
195
 
146
196
  ### `@jgb-solutions/kit/i18n`: four languages, one set of rules
@@ -319,7 +369,7 @@ Type: Bricolage Grotesque (700/800) for titles and numbers (`tabular-nums`), Fig
319
369
  - **Infrastructure details:** hosts, IP addresses, server names, internal URLs, deploy setup.
320
370
  - **Personal data, or real addresses outside `example.com`.**
321
371
 
322
- `bun run check:package` scans every file that would be published, before each publish and in CI. It fails on an Access team domain other than the examples, on a 32- or 64-character hex ID, on an address outside `example.com`, on any file besides `dist/`, the README, the changelog, the license and `package.json`, and on a module importing more than it may (`kit/access` jose alone; `kit/auth/rules`, `kit/auth/expo` and `kit/auth/bun` nothing). `bun run check:install` installs the packed package without the optional peers and checks that `kit/access`, `kit/auth/rules` and `kit/auth/expo` load and type-check there.
372
+ `bun run check:package` scans every file that would be published, before each publish and in CI. It fails on an Access team domain other than the examples, on a 32- or 64-character hex ID, on an address outside `example.com`, on any file besides `dist/`, the README, the changelog, the license and `package.json`, and on a module importing more than it may (`kit/access` jose alone; `kit/auth/rules`, `kit/auth/browser`, `kit/auth/cache`, `kit/auth/redis`, `kit/auth/expo` and `kit/auth/bun` nothing). `bun run check:install` installs the packed package without the optional peers and checks that `kit/access`, `kit/auth/rules` and `kit/auth/expo` load and type-check there.
323
373
 
324
374
  ## Developing
325
375
 
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Sign-in pieces that run in the website's browser, the same in every app: passkeys against Better
3
+ * Auth's own endpoints, the action a visitor tried before signing in, and the signed-in flag. No
4
+ * dependencies: the app passes `@simplewebauthn/browser` in (loaded only when a passkey button is
5
+ * pressed), so no auth library ships to every visitor.
6
+ *
7
+ * import { passkeyClient } from '@jgb-solutions/kit/auth/browser'
8
+ * const passkeys = passkeyClient({ webauthn: () => import('@simplewebauthn/browser') })
9
+ * const result = await passkeys.signIn() // { ok: true } or { ok: false, code }
10
+ */
11
+ /** What a passkey call answers: done, or a code (Better Auth's, or CANCELLED / NETWORK / INVALID_OPTIONS). */
12
+ export type PasskeyResult = {
13
+ ok: true;
14
+ } | {
15
+ ok: false;
16
+ code: string;
17
+ };
18
+ /**
19
+ * The two calls of `@simplewebauthn/browser` this module makes. The options come from Better Auth's
20
+ * passkey endpoints, which build them for these very functions.
21
+ */
22
+ export type WebAuthnBrowser = {
23
+ startAuthentication(input: {
24
+ optionsJSON: never;
25
+ }): Promise<unknown>;
26
+ startRegistration(input: {
27
+ optionsJSON: never;
28
+ }): Promise<unknown>;
29
+ };
30
+ /**
31
+ * Passkeys in the browser: the WebAuthn ceremony with the app's `@simplewebauthn/browser`, against
32
+ * Better Auth's endpoints under `base` (same origin, so its session and challenge cookies ride along).
33
+ */
34
+ export declare function passkeyClient(config: {
35
+ webauthn: () => Promise<WebAuthnBrowser>;
36
+ base?: string;
37
+ fetch?: typeof globalThis.fetch;
38
+ }): {
39
+ /** Signs in with a passkey on this device. On success the session cookie is set: reload or refetch. */
40
+ signIn: () => Promise<PasskeyResult>;
41
+ /** Adds a passkey, named `name`, to the signed-in account. */
42
+ add: (name: string) => Promise<PasskeyResult>;
43
+ };
44
+ /** Something a signed-out visitor tapped (a heart, Follow), to do once they're signed in. */
45
+ export type PendingAction<Kind extends string> = {
46
+ kind: Kind;
47
+ name?: string;
48
+ run: () => Promise<unknown>;
49
+ };
50
+ /**
51
+ * The action a visitor tried before signing in, kept in this tab's memory only: no storage, nothing in
52
+ * the URL. The button sets it and opens sign-in; sign-in finishes it once the person is in. A full
53
+ * reload on the way (a Google round trip) drops it: the visitor is signed in all the same and can tap again.
54
+ */
55
+ export declare function createPendingAction<Kind extends string>(): {
56
+ set(action: PendingAction<Kind>): void;
57
+ /** The name of what the visitor tapped, for the sign-in notice. */
58
+ name(): string | undefined;
59
+ clear(): void;
60
+ /**
61
+ * Runs the pending action once signed in and answers its kind, for the confirmation. With nothing
62
+ * pending it answers `otherwise` (for example 'signed-in' for a visitor sent from a page that needs
63
+ * an account). A failed action answers undefined: they're signed in and can tap again.
64
+ */
65
+ finish<Otherwise extends string | undefined = undefined>(otherwise?: Otherwise): Promise<Kind | Otherwise | undefined>;
66
+ };
67
+ /** Where to go after signing in: `next`, with `#done=<kind>` when something was done. */
68
+ export declare function afterSignIn(next: string, done: string | undefined): string;
69
+ /**
70
+ * True when the signed-in flag cookie (`signedInFlag` in `standardAuthOptions`, readable by scripts,
71
+ * unlike the session) says this browser is signed in: a cached page can then fetch the person's own
72
+ * bits without a request for every visitor. A hint only; the server always checks the session.
73
+ */
74
+ export declare function readSignedInFlag(name: string, cookie?: string): boolean;
@@ -0,0 +1,83 @@
1
+ // src/auth/browser.ts
2
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ var codeOf = (body, fallback) => isRecord(body) && typeof body.code === "string" && body.code ? body.code : fallback;
4
+ var looksLikeOptions = (body) => isRecord(body) && typeof body.challenge === "string";
5
+ function passkeyClient(config) {
6
+ const base = (config.base ?? "/api/auth/passkey").replace(/\/+$/, "");
7
+ const fetcher = config.fetch ?? globalThis.fetch.bind(globalThis);
8
+ async function call(path, body) {
9
+ try {
10
+ const response = await fetcher(`${base}/${path}`, {
11
+ credentials: "same-origin",
12
+ ...body === undefined ? {} : { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }
13
+ });
14
+ return { ok: response.ok, body: await response.json().catch(() => null) };
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+ async function ceremony(optionsPath, run, verifyPath, extra) {
20
+ const options = await call(optionsPath);
21
+ if (!options)
22
+ return { ok: false, code: "NETWORK" };
23
+ if (!options.ok)
24
+ return { ok: false, code: codeOf(options.body, "FAILED") };
25
+ if (!looksLikeOptions(options.body))
26
+ return { ok: false, code: "INVALID_OPTIONS" };
27
+ let response;
28
+ try {
29
+ response = await run(await config.webauthn(), options.body);
30
+ } catch {
31
+ return { ok: false, code: "CANCELLED" };
32
+ }
33
+ const verified = await call(verifyPath, { response, ...extra });
34
+ if (!verified)
35
+ return { ok: false, code: "NETWORK" };
36
+ return verified.ok ? { ok: true } : { ok: false, code: codeOf(verified.body, "FAILED") };
37
+ }
38
+ return {
39
+ signIn: () => ceremony("generate-authenticate-options", (webauthn, optionsJSON) => webauthn.startAuthentication({ optionsJSON }), "verify-authentication", {}),
40
+ add: (name) => ceremony(`generate-register-options?name=${encodeURIComponent(name)}`, (webauthn, optionsJSON) => webauthn.startRegistration({ optionsJSON }), "verify-registration", { name })
41
+ };
42
+ }
43
+ function createPendingAction() {
44
+ let pending;
45
+ return {
46
+ set(action) {
47
+ pending = action;
48
+ },
49
+ name() {
50
+ return pending?.name;
51
+ },
52
+ clear() {
53
+ pending = undefined;
54
+ },
55
+ async finish(otherwise) {
56
+ const action = pending;
57
+ pending = undefined;
58
+ if (!action)
59
+ return otherwise;
60
+ try {
61
+ await action.run();
62
+ return action.kind;
63
+ } catch {
64
+ return;
65
+ }
66
+ }
67
+ };
68
+ }
69
+ function afterSignIn(next, done) {
70
+ return done ? `${next.split("#")[0]}#done=${encodeURIComponent(done)}` : next;
71
+ }
72
+ function readSignedInFlag(name, cookie = typeof document === "undefined" ? "" : document.cookie) {
73
+ return cookie.split(";").some((part) => {
74
+ const [key, value] = part.split("=");
75
+ return key?.trim() === name && value?.trim() === "1";
76
+ });
77
+ }
78
+ export {
79
+ afterSignIn,
80
+ createPendingAction,
81
+ passkeyClient,
82
+ readSignedInFlag
83
+ };
@@ -21,4 +21,15 @@ export declare function argon2idHasher(options?: {
21
21
  hash: string;
22
22
  password: string;
23
23
  }) => Promise<boolean>;
24
+ /**
25
+ * At most this many hashes or checks at once; the rest wait their turn, in order. Each argon2id
26
+ * run holds `memoryCost` KiB, so a burst of sign-ins on a small server can't add up in memory.
27
+ * No limit when left out.
28
+ */
29
+ concurrency?: number;
24
30
  }): PasswordHasher;
31
+ /**
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.
34
+ */
35
+ export declare function concurrencyLimit(limit: number): <T>(task: () => Promise<T>) => Promise<T>;
package/dist/auth/bun.js CHANGED
@@ -1,16 +1,39 @@
1
1
  // src/auth/bun.ts
2
2
  function argon2idHasher(options = {}) {
3
- const { fallbackVerify, ...cost } = options;
3
+ const { fallbackVerify, concurrency, ...cost } = options;
4
4
  const algorithm = { algorithm: "argon2id", ...cost };
5
+ const run = concurrency === undefined ? (task) => task() : concurrencyLimit(concurrency);
5
6
  return {
6
- hash: (password) => Bun.password.hash(password, algorithm),
7
- verify: ({ hash, password }) => {
7
+ hash: (password) => run(() => Bun.password.hash(password, algorithm)),
8
+ verify: ({ hash, password }) => run(() => {
8
9
  if (fallbackVerify && !hash.startsWith("$argon2"))
9
10
  return fallbackVerify({ hash, password }).catch(() => false);
10
11
  return Bun.password.verify(password, hash).catch(() => false);
12
+ })
13
+ };
14
+ }
15
+ function concurrencyLimit(limit) {
16
+ if (!Number.isInteger(limit) || limit < 1)
17
+ throw new RangeError("concurrency must be a whole number of at least 1");
18
+ let running = 0;
19
+ const waiting = [];
20
+ return async (task) => {
21
+ if (running < limit)
22
+ running++;
23
+ else
24
+ await new Promise((resolve) => waiting.push(resolve));
25
+ try {
26
+ return await task();
27
+ } finally {
28
+ const next = waiting.shift();
29
+ if (next)
30
+ next();
31
+ else
32
+ running--;
11
33
  }
12
34
  };
13
35
  }
14
36
  export {
15
- argon2idHasher
37
+ argon2idHasher,
38
+ concurrencyLimit
16
39
  };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Keeping per-person pages out of shared caches (Cloudflare's edge, a zone cache rule, a proxy):
3
+ * CDN cache keys ignore cookies, so a signed-in page stored once would be served to the next visitor.
4
+ * Dependency-free; runs in Bun, Workers and Node.
5
+ *
6
+ * import { hasSession, privatePaths, makePrivate, sessionCookieNames } from '@jgb-solutions/kit/auth/cache'
7
+ */
8
+ /** `cache-control` for an answer meant for one person only. */
9
+ export declare const PRIVATE_HEADERS: {
10
+ readonly 'cache-control': "private, no-store";
11
+ };
12
+ /**
13
+ * The cookies that mean a signed-in visitor: Better Auth's session token under `prefix` (its
14
+ * `advanced.cookiePrefix`, `better-auth` by default) and its `__Secure-` name on https, plus `extra`
15
+ * (by default `__session`, the cookie of Clerk and most hosted sign-in services).
16
+ */
17
+ export declare function sessionCookieNames(prefix?: string, extra?: readonly string[]): string[];
18
+ /** True when a Cookie header holds one of `names` (exact names, not a suffix). */
19
+ export declare function hasSession(cookieHeader: string | null | undefined, names?: readonly string[]): boolean;
20
+ /**
21
+ * A matcher for pages whose HTML depends on who's asking: each path and everything under it, also
22
+ * behind a two-letter language folder (`/fr/account`) unless `localePrefix` is false.
23
+ *
24
+ * const isPrivatePath = privatePaths(['admin', 'account', 'sign-in', 'sign-up'])
25
+ * isPrivatePath('/fr/account/passkeys') // true
26
+ */
27
+ export declare function privatePaths(paths: readonly string[], options?: {
28
+ localePrefix?: boolean;
29
+ }): (pathname: string) => boolean;
30
+ /** The response, marked for one person only: `private, no-store`, and no CDN caching header. */
31
+ export declare function makePrivate(response: Response): Response;
32
+ /**
33
+ * The handler for Better Auth's routes (`/api/auth/*`): its answers carry sessions and cookies, so
34
+ * every one is made private. Give it the instance (or a function that makes it on first use) and,
35
+ * behind a proxy that ends HTTPS, a way to give the request its public address back (`asPublicRequest`).
36
+ */
37
+ export declare function authRouteHandler(auth: {
38
+ handler(request: Request): Promise<Response>;
39
+ } | (() => {
40
+ handler(request: Request): Promise<Response>;
41
+ } | Promise<{
42
+ handler(request: Request): Promise<Response>;
43
+ }>), options?: {
44
+ publicRequest?: (request: Request) => Request;
45
+ }): (request: Request) => Promise<Response>;
@@ -0,0 +1,43 @@
1
+ // src/auth/cache.ts
2
+ var PRIVATE_HEADERS = { "cache-control": "private, no-store" };
3
+ var CDN_CACHE_HEADERS = ["cdn-cache-control", "cloudflare-cdn-cache-control", "surrogate-control"];
4
+ function sessionCookieNames(prefix = "better-auth", extra = ["__session"]) {
5
+ return [`${prefix}.session_token`, `__Secure-${prefix}.session_token`, ...extra];
6
+ }
7
+ var DEFAULT_SESSION_COOKIES = sessionCookieNames();
8
+ function hasSession(cookieHeader, names = DEFAULT_SESSION_COOKIES) {
9
+ if (!cookieHeader)
10
+ return false;
11
+ return cookieHeader.split(";").some((part) => names.includes(part.split("=")[0]?.trim() ?? ""));
12
+ }
13
+ var escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14
+ function privatePaths(paths, options = {}) {
15
+ const names = paths.map((path) => escape(path.replace(/^\/+|\/+$/g, ""))).filter(Boolean);
16
+ if (names.length === 0)
17
+ return () => false;
18
+ const locale = options.localePrefix === false ? "" : "(?:[a-z]{2}\\/)?";
19
+ const pattern = new RegExp(`^\\/${locale}(?:${names.join("|")})(?:\\/|$)`);
20
+ return (pathname) => pattern.test(pathname);
21
+ }
22
+ function makePrivate(response) {
23
+ const headers = new Headers(response.headers);
24
+ headers.set("cache-control", PRIVATE_HEADERS["cache-control"]);
25
+ for (const name of CDN_CACHE_HEADERS)
26
+ headers.delete(name);
27
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
28
+ }
29
+ function authRouteHandler(auth, options = {}) {
30
+ return async (request) => {
31
+ const instance = typeof auth === "function" ? await auth() : auth;
32
+ const response = await instance.handler(options.publicRequest ? options.publicRequest(request) : request);
33
+ return makePrivate(response);
34
+ };
35
+ }
36
+ export {
37
+ PRIVATE_HEADERS,
38
+ authRouteHandler,
39
+ hasSession,
40
+ makePrivate,
41
+ privatePaths,
42
+ sessionCookieNames
43
+ };
@@ -83,3 +83,32 @@ export declare function createMobileAuth<U>(config: MobileAuthConfig<U>): {
83
83
  forget: () => Promise<void>;
84
84
  };
85
85
  export type MobileAuth<U> = ReturnType<typeof createMobileAuth<U>>;
86
+ /**
87
+ * The native Google account sheet: a module with `signIn(serverClientId)` answering Google's ID token
88
+ * (Android's Credential Manager), rejecting with `error.code` ERR_CANCELLED, ERR_NO_ACCOUNT or another.
89
+ */
90
+ export type GoogleCredentialModule = {
91
+ signIn(serverClientId: string): Promise<{
92
+ idToken: string;
93
+ }>;
94
+ };
95
+ export type GoogleTokenResult = {
96
+ ok: true;
97
+ idToken: string;
98
+ } | {
99
+ ok: false;
100
+ code: 'CANCELLED' | 'NO_GOOGLE_ACCOUNT' | 'GOOGLE_UNAVAILABLE';
101
+ }
102
+ /** `detail` (the native code and message) is for the error tracker, never for the screen. */
103
+ | {
104
+ ok: false;
105
+ code: 'GOOGLE_FAILED';
106
+ detail: string;
107
+ };
108
+ /**
109
+ * Google's ID token from the phone's account sheet, for `signInWithGoogle` or `linkGoogle`. `module`
110
+ * is the app's native module, or null where the installed app lacks it (iOS, older builds):
111
+ * GOOGLE_UNAVAILABLE then, as without `webClientId` (the website's OAuth client, whose tokens Better
112
+ * Auth accepts). CANCELLED means the person closed the sheet: nothing to say.
113
+ */
114
+ export declare function googleIdToken(module: GoogleCredentialModule | null | undefined, webClientId: string | null | undefined): Promise<GoogleTokenResult>;
package/dist/auth/expo.js CHANGED
@@ -82,6 +82,52 @@ function authErrorCode(answer) {
82
82
  return GOOGLE_EMAIL_NOT_CONFIRMED;
83
83
  return code;
84
84
  }
85
+ var USERNAME_ERROR_CODES = {
86
+ "too-short": "USERNAME_TOO_SHORT",
87
+ "too-long": "USERNAME_TOO_LONG",
88
+ characters: "INVALID_USERNAME"
89
+ };
90
+ function usernameErrorCode(username) {
91
+ const problem = usernameProblem(username);
92
+ return problem ? USERNAME_ERROR_CODES[problem] : null;
93
+ }
94
+ var NAME_UNSAFE = /[\u0000-\u001f\u007f<>]/;
95
+ function displayNameProblem(name, max = 50) {
96
+ const trimmed = name.trim();
97
+ if (!trimmed)
98
+ return "empty";
99
+ if ([...trimmed].length > max)
100
+ return "too-long";
101
+ if (NAME_UNSAFE.test(trimmed))
102
+ return "characters";
103
+ return null;
104
+ }
105
+ function defineSignInReasons(reasons) {
106
+ return {
107
+ REASONS: reasons,
108
+ reasonOf(value) {
109
+ return reasons.find((reason) => reason === value);
110
+ }
111
+ };
112
+ }
113
+ var REDIRECT_UNSAFE = /[\u0000-\u001f\u007f\\]/;
114
+ function isSafeRedirectPath(path) {
115
+ if (path.length > 500 || !path.startsWith("/") || path.startsWith("//") || REDIRECT_UNSAFE.test(path))
116
+ return false;
117
+ let decoded;
118
+ try {
119
+ decoded = decodeURIComponent(path);
120
+ } catch {
121
+ return false;
122
+ }
123
+ if (REDIRECT_UNSAFE.test(decoded) || decoded.startsWith("//"))
124
+ return false;
125
+ const base = "https://this-site.invalid";
126
+ return new URL(path, base).origin === base;
127
+ }
128
+ function safeRedirect(value) {
129
+ return typeof value === "string" && isSafeRedirectPath(value) ? value : undefined;
130
+ }
85
131
 
86
132
  // src/auth/expo.ts
87
133
  function codeOf(body, fallback) {
@@ -239,6 +285,25 @@ function createMobileAuth(config) {
239
285
  forget
240
286
  };
241
287
  }
288
+ async function googleIdToken(module, webClientId) {
289
+ if (!module || !webClientId)
290
+ return { ok: false, code: "GOOGLE_UNAVAILABLE" };
291
+ try {
292
+ const { idToken } = await module.signIn(webClientId);
293
+ if (typeof idToken !== "string" || !idToken)
294
+ return { ok: false, code: "GOOGLE_FAILED", detail: "NO_TOKEN" };
295
+ return { ok: true, idToken };
296
+ } catch (error) {
297
+ const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : "";
298
+ if (code === "ERR_CANCELLED")
299
+ return { ok: false, code: "CANCELLED" };
300
+ if (code === "ERR_NO_ACCOUNT")
301
+ return { ok: false, code: "NO_GOOGLE_ACCOUNT" };
302
+ const message = error instanceof Error ? error.message : String(error);
303
+ return { ok: false, code: "GOOGLE_FAILED", detail: `${code || "UNKNOWN"}: ${message}` };
304
+ }
305
+ }
242
306
  export {
243
- createMobileAuth
307
+ createMobileAuth,
308
+ googleIdToken
244
309
  };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Rate-limit counters in Redis or a compatible store, for Better Auth (`counterRateLimit`) and oRPC's limiter.
3
+ * No client library: pass the app's own client (Bun's `RedisClient`, ioredis…).
4
+ *
5
+ * import { redisCounterStore } from '@jgb-solutions/kit/auth/redis'
6
+ * rateLimit: { customStorage: counterRateLimit(() => redisCounterStore(redis, 'myapp:')) }
7
+ */
8
+ import type { CounterStore } from '../auth';
9
+ /** The two commands a counter store needs; Bun's `RedisClient` and ioredis both have them. */
10
+ export type RedisCounterClient = {
11
+ incr(key: string): Promise<number>;
12
+ expire(key: string, seconds: number): Promise<unknown>;
13
+ };
14
+ /**
15
+ * A counter store on Redis or a compatible store: one INCR per attempt, and the key's expiry set when it is
16
+ * new. `prefix` keeps one app's keys apart from another's on a shared server.
17
+ */
18
+ export declare function redisCounterStore(client: RedisCounterClient, prefix?: string): CounterStore;
19
+ /**
20
+ * What oRPC's Redis limiter script answers when the store can't be reached: `[success, used, ttl]`
21
+ * with success 1, so the call goes through and nothing is counted. From oRPC 2.0.0-beta.53, `[0, 0]`
22
+ * (the older two-number reply) reads as *rejected*, and every call was refused.
23
+ */
24
+ export declare const RATE_LIMIT_SCRIPT_FALLBACK: readonly [1, 0, 0];
25
+ /**
26
+ * Runs a limiter's Redis script, answering {@link RATE_LIMIT_SCRIPT_FALLBACK} (and logging) when
27
+ * the store fails, so the site keeps working while the cache is away. For a `BaseRedisRateLimiter`
28
+ * subclass:
29
+ *
30
+ * protected evalScript(script: string, keys: string[], args: string[]) {
31
+ * return evalWithFallback(() => redis.send('EVAL', [script, String(keys.length), ...keys, ...args]))
32
+ * }
33
+ */
34
+ export declare function evalWithFallback(run: () => Promise<unknown>, label?: string): Promise<unknown>;
@@ -0,0 +1,26 @@
1
+ // src/auth/redis.ts
2
+ function redisCounterStore(client, prefix = "") {
3
+ return {
4
+ async incr(key, ttlSeconds) {
5
+ const name = `${prefix}${key}`;
6
+ const value = await client.incr(name);
7
+ if (value === 1)
8
+ await client.expire(name, ttlSeconds);
9
+ return value;
10
+ }
11
+ };
12
+ }
13
+ var RATE_LIMIT_SCRIPT_FALLBACK = [1, 0, 0];
14
+ async function evalWithFallback(run, label = "rate limit") {
15
+ try {
16
+ return await run();
17
+ } catch (error) {
18
+ console.warn(`${label}: store unavailable, letting the call through`, error);
19
+ return [...RATE_LIMIT_SCRIPT_FALLBACK];
20
+ }
21
+ }
22
+ export {
23
+ RATE_LIMIT_SCRIPT_FALLBACK,
24
+ evalWithFallback,
25
+ redisCounterStore
26
+ };
@@ -104,3 +104,33 @@ export declare const GOOGLE_EMAIL_NOT_CONFIRMED = "GOOGLE_EMAIL_NOT_CONFIRMED";
104
104
  * own code ('' when there is none).
105
105
  */
106
106
  export declare function authErrorCode(answer: unknown): string;
107
+ /** Better Auth's codes for a username problem, so an app words one set of codes. */
108
+ export declare const USERNAME_ERROR_CODES: {
109
+ readonly 'too-short': "USERNAME_TOO_SHORT";
110
+ readonly 'too-long': "USERNAME_TOO_LONG";
111
+ readonly characters: "INVALID_USERNAME";
112
+ };
113
+ export type UsernameErrorCode = (typeof USERNAME_ERROR_CODES)[keyof typeof USERNAME_ERROR_CODES];
114
+ /** The code for a username's problem (the one Better Auth answers with), or null when it's fine. */
115
+ export declare function usernameErrorCode(username: string): UsernameErrorCode | null;
116
+ /** Why a display name can't be used (after trimming), or null when it can. The app words the message. */
117
+ export declare function displayNameProblem(name: string, max?: number): 'empty' | 'too-long' | 'characters' | null;
118
+ /**
119
+ * An allow-list of short codes read from a URL, such as why a page sends a visitor to sign in
120
+ * (`?reason=favorite`) or what to confirm afterwards (`#done=favorite`). Anything else is ignored, so a
121
+ * link can never make the page say words it doesn't have.
122
+ *
123
+ * export const { REASONS, reasonOf } = defineSignInReasons(['account', 'admin', 'favorite'])
124
+ */
125
+ export declare function defineSignInReasons<const R extends readonly [string, ...string[]]>(reasons: R): {
126
+ REASONS: R;
127
+ reasonOf(value: unknown): R[number] | undefined;
128
+ };
129
+ /**
130
+ * True for a path on this site that is safe to send a visitor to after sign-in: it starts with one
131
+ * "/", has no control characters or backslashes (also once percent-decoded), and still resolves to
132
+ * this site. At most 500 characters.
133
+ */
134
+ export declare function isSafeRedirectPath(path: string): boolean;
135
+ /** The value when it's a safe path on this site ({@link isSafeRedirectPath}), else undefined. */
136
+ export declare function safeRedirect(value: unknown): string | undefined;