@jgb-solutions/kit 0.4.4 → 0.5.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,16 @@
2
2
 
3
3
  All notable changes to `@jgb-solutions/kit`. Versions follow semver.
4
4
 
5
+ ## 0.5.0
6
+
7
+ The account logic every app copied, now in the kit. Nothing existing changes.
8
+
9
+ - `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`.
10
+ - `kit/auth/cache` (new): `sessionCookieNames(prefix)`, `hasSession`, `privatePaths(paths)` (with the language folder), `PRIVATE_HEADERS`, `makePrivate` (drops CDN caching headers) and `authRouteHandler`.
11
+ - `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).
12
+ - `kit/auth/rules`: `safeRedirect` and `isSafeRedirectPath` (control characters, backslashes and percent-encoded tricks refused), `usernameErrorCode`, `displayNameProblem` and `defineSignInReasons`.
13
+ - `kit/auth/bun`: `argon2idHasher({ concurrency })` caps the hashes that run at once; also `concurrencyLimit`.
14
+
5
15
  ## 0.4.4
6
16
 
7
17
  - `@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,37 @@ 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.
118
148
 
119
149
  #### `kit/auth/expo`: the mobile app
120
150
 
@@ -319,7 +349,7 @@ Type: Bricolage Grotesque (700/800) for titles and numbers (`tabular-nums`), Fig
319
349
  - **Infrastructure details:** hosts, IP addresses, server names, internal URLs, deploy setup.
320
350
  - **Personal data, or real addresses outside `example.com`.**
321
351
 
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.
352
+ `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/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
353
 
324
354
  ## Developing
325
355
 
@@ -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
+ };
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) {
@@ -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;
@@ -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
  export {
86
132
  ACCOUNT_NOT_LINKED,
87
133
  GOOGLE_ALREADY_LINKED,
@@ -89,13 +135,19 @@ export {
89
135
  PASSWORD,
90
136
  PLACEHOLDER_EMAIL_DOMAIN,
91
137
  USERNAME,
138
+ USERNAME_ERROR_CODES,
92
139
  authErrorCode,
93
140
  avatarInitials,
94
141
  avatarSrc,
95
142
  defineRoles,
143
+ defineSignInReasons,
144
+ displayNameProblem,
96
145
  isPlaceholderEmail,
146
+ isSafeRedirectPath,
97
147
  placeholderEmail,
148
+ safeRedirect,
98
149
  usernameCandidates,
150
+ usernameErrorCode,
99
151
  usernameFromName,
100
152
  usernameProblem
101
153
  };