@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/dist/auth.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/auth.ts
2
2
  import { passkey } from "@better-auth/passkey";
3
- import { createAuthMiddleware } from "better-auth/api";
3
+ import { APIError, createAuthEndpoint, createAuthMiddleware } from "better-auth/api";
4
4
  import { admin } from "better-auth/plugins/admin";
5
5
  import { bearer } from "better-auth/plugins/bearer";
6
6
  import { username } from "better-auth/plugins/username";
@@ -187,9 +187,32 @@ var RATE_LIMIT_RULES = {
187
187
  "/passkey/*": { window: 60, max: 20 },
188
188
  "/change-password": { window: 60, max: 5 },
189
189
  "/set-password": { window: 60, max: 5 },
190
- "/delete-user": { window: 60, max: 5 }
190
+ "/delete-user": { window: 60, max: 5 },
191
+ "/google/nonce": { window: 60, max: 10 }
191
192
  };
193
+ function memoryRateLimit(now = Date.now, maxKeys = 1e5) {
194
+ const counts = new Map;
195
+ return {
196
+ async consume(key, rule) {
197
+ const windowMs = rule.window * 1000;
198
+ const slot = Math.floor(now() / windowMs);
199
+ const entry = counts.get(key);
200
+ const count = entry && entry.slot === slot ? entry.count + 1 : 1;
201
+ counts.delete(key);
202
+ counts.set(key, { slot, count });
203
+ if (counts.size > maxKeys) {
204
+ const oldest = counts.keys().next().value;
205
+ if (oldest !== undefined)
206
+ counts.delete(oldest);
207
+ }
208
+ if (count <= rule.max)
209
+ return { allowed: true, retryAfter: null };
210
+ return { allowed: false, retryAfter: Math.max(1, Math.ceil(((slot + 1) * windowMs - now()) / 1000)) };
211
+ }
212
+ };
213
+ }
192
214
  function counterRateLimit(store, now = Date.now) {
215
+ const fallback = memoryRateLimit(now);
193
216
  return {
194
217
  async consume(key, rule) {
195
218
  const windowMs = rule.window * 1000;
@@ -198,8 +221,8 @@ function counterRateLimit(store, now = Date.now) {
198
221
  try {
199
222
  count = await store().incr(`auth-limit:${key}:${slot}`, rule.window);
200
223
  } catch (error) {
201
- console.warn("auth rate limit: store unavailable, letting the attempt through", error);
202
- return { allowed: true, retryAfter: null };
224
+ console.warn("auth rate limit: store unavailable, counting in memory", error);
225
+ return fallback.consume(key, rule);
203
226
  }
204
227
  if (count <= rule.max)
205
228
  return { allowed: true, retryAfter: null };
@@ -207,6 +230,82 @@ function counterRateLimit(store, now = Date.now) {
207
230
  }
208
231
  };
209
232
  }
233
+ var ACCOUNT_SIGN_IN_RULE = { window: 15 * 60, max: 30 };
234
+ var SIGN_IN_FIELDS = { "/sign-in/email": "email", "/sign-in/username": "username" };
235
+ async function sha256Hex(text) {
236
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
237
+ return Array.from(new Uint8Array(digest).slice(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
238
+ }
239
+ function accountSignInLimit(storage) {
240
+ return {
241
+ id: "account-sign-in-limit",
242
+ hooks: {
243
+ before: [
244
+ {
245
+ matcher: (ctx) => Object.hasOwn(SIGN_IN_FIELDS, ctx.path ?? ""),
246
+ handler: createAuthMiddleware(async (ctx) => {
247
+ const field = SIGN_IN_FIELDS[ctx.path];
248
+ const body = ctx.body;
249
+ const login = field && typeof body === "object" && body !== null && field in body ? body[field] : undefined;
250
+ if (typeof login !== "string" || !login.trim())
251
+ return;
252
+ const key = `login:${await sha256Hex(login.trim().toLowerCase())}|/sign-in`;
253
+ const answer = await storage.consume(key, ACCOUNT_SIGN_IN_RULE);
254
+ if (!answer.allowed)
255
+ throw APIError.from("TOO_MANY_REQUESTS", { code: "TOO_MANY_REQUESTS", message: "Too many sign-in attempts for this account" });
256
+ })
257
+ }
258
+ ]
259
+ }
260
+ };
261
+ }
262
+ var GOOGLE_NONCE_MINUTES = 5;
263
+ var NONCE_PATHS = new Set(["/sign-in/social", "/link-social"]);
264
+ function googleIdTokenNonce(options) {
265
+ return {
266
+ id: "google-id-token-nonce",
267
+ endpoints: {
268
+ googleNonce: createAuthEndpoint("/google/nonce", { method: "POST" }, async (ctx) => {
269
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
270
+ const nonce = btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
271
+ const stored = await ctx.context.internalAdapter.createVerificationValue({
272
+ identifier: `google-nonce:${nonce}`,
273
+ value: "1",
274
+ expiresAt: new Date(Date.now() + GOOGLE_NONCE_MINUTES * 60000)
275
+ });
276
+ if (!stored)
277
+ throw APIError.from("INTERNAL_SERVER_ERROR", { code: "NONCE_NOT_STORED", message: "The nonce could not be stored" });
278
+ await ctx.context.runInBackgroundOrAwait(ctx.context.adapter.deleteMany({ model: "verification", where: [{ field: "expiresAt", operator: "lt", value: new Date }] }).then(() => {
279
+ return;
280
+ }).catch((error) => ctx.context.logger.error("google nonce: expired rows not swept", error)));
281
+ ctx.setHeader("cache-control", "no-store");
282
+ return ctx.json({ nonce });
283
+ })
284
+ },
285
+ hooks: {
286
+ before: [
287
+ {
288
+ matcher: (ctx) => NONCE_PATHS.has(ctx.path ?? ""),
289
+ handler: createAuthMiddleware(async (ctx) => {
290
+ const body = ctx.body;
291
+ const idToken = typeof body === "object" && body !== null && "idToken" in body ? body.idToken : undefined;
292
+ if (typeof idToken !== "object" || idToken === null)
293
+ return;
294
+ const nonce = "nonce" in idToken && typeof idToken.nonce === "string" ? idToken.nonce : "";
295
+ if (!nonce) {
296
+ if (options.mode === "required")
297
+ throw APIError.from("BAD_REQUEST", { code: "NONCE_REQUIRED", message: "A nonce is required" });
298
+ return;
299
+ }
300
+ const spent = await ctx.context.internalAdapter.consumeVerificationValue(`google-nonce:${nonce}`);
301
+ if (!spent)
302
+ throw APIError.from("BAD_REQUEST", { code: "INVALID_NONCE", message: "Unknown, used or expired nonce" });
303
+ })
304
+ }
305
+ ]
306
+ }
307
+ };
308
+ }
210
309
  var CONFIRMED_ACCOUNT_LINKING = {
211
310
  enabled: true,
212
311
  trustedProviders: [],
@@ -378,14 +477,19 @@ function standardAuthOptions(input) {
378
477
  }),
379
478
  admin(input.admin),
380
479
  bearer(),
480
+ ...settings.rateLimit ? [accountSignInLimit(input.rateLimitStorage ?? memoryRateLimit())] : [],
481
+ ...settings.google ? [googleIdTokenNonce({ mode: input.googleNonce ?? "optional" })] : [],
381
482
  ...input.plugins ?? [],
382
483
  ...input.lastPlugin ? [input.lastPlugin] : []
383
484
  ]
384
485
  };
385
486
  }
386
487
  export {
488
+ ACCOUNT_SIGN_IN_RULE,
387
489
  CONFIRMED_ACCOUNT_LINKING,
490
+ GOOGLE_NONCE_MINUTES,
388
491
  RATE_LIMIT_RULES,
492
+ accountSignInLimit,
389
493
  afterAccountSaved,
390
494
  androidOrigin,
391
495
  asPublicRequest,
@@ -393,7 +497,9 @@ export {
393
497
  authSettings,
394
498
  counterRateLimit,
395
499
  freeUsername,
500
+ googleIdTokenNonce,
396
501
  googleProvider,
502
+ memoryRateLimit,
397
503
  passkeyOrigins,
398
504
  pictureFromIdToken,
399
505
  roleForNewUser,
package/dist/i18n.js CHANGED
@@ -103,7 +103,7 @@ function isPlural(value) {
103
103
  function leafAt(messages, key) {
104
104
  let node = messages;
105
105
  for (const part of key.split(".")) {
106
- if (!isRecord(node))
106
+ if (!isRecord(node) || !Object.hasOwn(node, part))
107
107
  return;
108
108
  node = node[part];
109
109
  }
@@ -161,7 +161,7 @@ function createTranslator(locale, messages, fallback) {
161
161
  const select = pluralSelector(locale);
162
162
  const numbers = typeof Intl !== "undefined" && typeof Intl.NumberFormat === "function" ? new Intl.NumberFormat(locale) : undefined;
163
163
  const fill = (template, params, formatNumbers) => template.replace(/\{(\w+)\}/g, (placeholder, name) => {
164
- const value = params?.[name];
164
+ const value = params && Object.hasOwn(params, name) ? params[name] : undefined;
165
165
  if (value === undefined)
166
166
  return placeholder;
167
167
  return typeof value === "number" && formatNumbers && numbers ? numbers.format(value) : String(value);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jgb-solutions/kit",
3
- "version": "0.5.0",
4
- "description": "One package for JGB Solutions apps, in tree-shakable namespaces: Cloudflare Access, Better Auth (kit/access, kit/auth\u2026) and the admin panel kit (kit/admin, React 19). An app bundles only the subpaths it imports.",
3
+ "version": "0.7.0",
4
+ "description": "One package for JGB Solutions apps, in tree-shakable namespaces: Cloudflare Access, Better Auth (kit/access, kit/auth…) and the admin panel kit (kit/admin, React 19). An app bundles only the subpaths it imports.",
5
5
  "license": "MIT",
6
6
  "author": "JGB Solutions",
7
7
  "repository": {
@@ -69,6 +69,14 @@
69
69
  "types": "./dist/auth/redis.d.ts",
70
70
  "import": "./dist/auth/redis.js"
71
71
  },
72
+ "./auth/browser": {
73
+ "types": "./dist/auth/browser.d.ts",
74
+ "import": "./dist/auth/browser.js"
75
+ },
76
+ "./auth/versions": {
77
+ "types": "./dist/auth/versions.d.ts",
78
+ "import": "./dist/auth/versions.js"
79
+ },
72
80
  "./auth/expo": {
73
81
  "types": "./dist/auth/expo.d.ts",
74
82
  "import": "./dist/auth/expo.js"
@@ -137,6 +145,7 @@
137
145
  "@better-auth/passkey": "1.7.29",
138
146
  "@orpc/server": "2.0.0-beta.53",
139
147
  "@playwright/test": "1.65.1",
148
+ "@simplewebauthn/browser": "13.3.0",
140
149
  "@types/bun": "1.4.5",
141
150
  "@types/react": "19.3.3",
142
151
  "@types/react-dom": "19.3.0",