@lastshotlabs/bunshot 0.0.16 → 0.0.19

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.
Files changed (72) hide show
  1. package/README.md +322 -16
  2. package/dist/adapters/memoryAuth.d.ts +3 -0
  3. package/dist/adapters/memoryAuth.js +48 -2
  4. package/dist/adapters/mongoAuth.js +39 -1
  5. package/dist/adapters/sqliteAuth.d.ts +3 -0
  6. package/dist/adapters/sqliteAuth.js +53 -0
  7. package/dist/app.d.ts +45 -2
  8. package/dist/app.js +79 -4
  9. package/dist/index.d.ts +14 -7
  10. package/dist/index.js +8 -4
  11. package/dist/lib/appConfig.d.ts +35 -0
  12. package/dist/lib/appConfig.js +10 -0
  13. package/dist/lib/authAdapter.d.ts +24 -0
  14. package/dist/lib/authRateLimit.d.ts +2 -0
  15. package/dist/lib/authRateLimit.js +4 -0
  16. package/dist/lib/clientIp.d.ts +14 -0
  17. package/dist/lib/clientIp.js +52 -0
  18. package/dist/lib/constants.d.ts +2 -0
  19. package/dist/lib/constants.js +2 -0
  20. package/dist/lib/crypto.d.ts +11 -0
  21. package/dist/lib/crypto.js +22 -0
  22. package/dist/lib/emailVerification.d.ts +4 -0
  23. package/dist/lib/emailVerification.js +20 -12
  24. package/dist/lib/jwt.js +17 -4
  25. package/dist/lib/mfaChallenge.d.ts +23 -1
  26. package/dist/lib/mfaChallenge.js +151 -42
  27. package/dist/lib/oauth.d.ts +14 -1
  28. package/dist/lib/oauth.js +19 -1
  29. package/dist/lib/oauthCode.d.ts +15 -0
  30. package/dist/lib/oauthCode.js +90 -0
  31. package/dist/lib/resetPassword.js +12 -16
  32. package/dist/lib/session.js +6 -4
  33. package/dist/lib/ws.js +5 -1
  34. package/dist/lib/zodToMongoose.d.ts +2 -2
  35. package/dist/lib/zodToMongoose.js +7 -3
  36. package/dist/middleware/bearerAuth.js +4 -3
  37. package/dist/middleware/botProtection.js +2 -2
  38. package/dist/middleware/cacheResponse.d.ts +1 -0
  39. package/dist/middleware/cacheResponse.js +14 -2
  40. package/dist/middleware/cors.d.ts +2 -0
  41. package/dist/middleware/cors.js +22 -8
  42. package/dist/middleware/csrf.d.ts +18 -0
  43. package/dist/middleware/csrf.js +115 -0
  44. package/dist/middleware/rateLimit.js +2 -3
  45. package/dist/models/AuthUser.d.ts +9 -0
  46. package/dist/models/AuthUser.js +9 -0
  47. package/dist/routes/auth.js +21 -9
  48. package/dist/routes/mfa.d.ts +5 -1
  49. package/dist/routes/mfa.js +221 -14
  50. package/dist/routes/oauth.js +274 -10
  51. package/dist/schemas/auth.d.ts +2 -0
  52. package/dist/schemas/auth.js +22 -1
  53. package/dist/server.d.ts +6 -0
  54. package/dist/server.js +10 -3
  55. package/dist/services/auth.d.ts +1 -0
  56. package/dist/services/auth.js +21 -5
  57. package/dist/services/mfa.d.ts +47 -0
  58. package/dist/services/mfa.js +276 -9
  59. package/dist/ws/index.js +3 -2
  60. package/docs/sections/auth-flow/full.md +180 -2
  61. package/docs/sections/configuration/full.md +20 -0
  62. package/docs/sections/configuration/overview.md +1 -1
  63. package/docs/sections/configuration-example/full.md +19 -1
  64. package/docs/sections/exports/full.md +11 -2
  65. package/docs/sections/multi-tenancy/full.md +5 -1
  66. package/docs/sections/oauth/full.md +80 -10
  67. package/docs/sections/oauth/overview.md +2 -2
  68. package/docs/sections/peer-dependencies/full.md +6 -2
  69. package/docs/sections/response-caching/full.md +3 -1
  70. package/docs/sections/websocket/full.md +4 -3
  71. package/docs/sections/websocket/overview.md +1 -1
  72. package/package.json +16 -4
@@ -3,14 +3,18 @@ import { createRouter } from "../lib/context";
3
3
  import { setCookie } from "hono/cookie";
4
4
  import { decodeIdToken } from "arctic";
5
5
  import { z } from "zod";
6
- import { getGoogle, getApple, storeOAuthState, consumeOAuthState, generateState, generateCodeVerifier, } from "../lib/oauth";
6
+ import { getGoogle, getApple, getMicrosoft, getGitHub, storeOAuthState, consumeOAuthState, generateState, generateCodeVerifier, } from "../lib/oauth";
7
7
  import { getAuthAdapter } from "../lib/authAdapter";
8
8
  import { HttpError } from "../lib/HttpError";
9
9
  import { signToken } from "../lib/jwt";
10
10
  import { createSession, getActiveSessionCount, evictOldestSession, setRefreshToken } from "../lib/session";
11
+ import { storeOAuthCode, consumeOAuthCode } from "../lib/oauthCode";
11
12
  import { COOKIE_TOKEN, COOKIE_REFRESH_TOKEN } from "../lib/constants";
12
13
  import { userAuth } from "../middleware/userAuth";
13
- import { getDefaultRole, getMaxSessions, getRefreshTokenConfig, getAccessTokenExpiry, getRefreshTokenExpiry } from "../lib/appConfig";
14
+ import { getDefaultRole, getMaxSessions, getRefreshTokenConfig, getAccessTokenExpiry, getRefreshTokenExpiry, getCsrfEnabled } from "../lib/appConfig";
15
+ import { refreshCsrfToken } from "../middleware/csrf";
16
+ import { trackAttempt } from "../lib/authRateLimit";
17
+ import { getClientIp } from "../lib/clientIp";
14
18
  const isProd = process.env.NODE_ENV === "production";
15
19
  const cookieOptions = (maxAge) => ({
16
20
  httpOnly: true,
@@ -44,27 +48,30 @@ const finishOAuth = async (c, provider, providerId, profile, postLoginRedirect)
44
48
  const rtConfig = getRefreshTokenConfig();
45
49
  const expirySeconds = rtConfig ? getAccessTokenExpiry() : undefined;
46
50
  const token = await signToken(user.id, sessionId, expirySeconds);
47
- const xff = c.req.header("x-forwarded-for");
48
51
  const metadata = {
49
- ipAddress: (xff ? xff.split(",")[0]?.trim() : undefined) ?? c.req.header("x-real-ip") ?? undefined,
52
+ ipAddress: getClientIp(c),
50
53
  userAgent: c.req.header("user-agent") ?? undefined,
51
54
  };
52
55
  while (await getActiveSessionCount(user.id) >= getMaxSessions()) {
53
56
  await evictOldestSession(user.id);
54
57
  }
55
58
  await createSession(user.id, token, sessionId, metadata);
56
- setCookie(c, COOKIE_TOKEN, token, cookieOptions(rtConfig ? getAccessTokenExpiry() : undefined));
57
59
  let refreshTokenValue;
58
60
  if (rtConfig) {
59
61
  refreshTokenValue = crypto.randomUUID();
60
62
  await setRefreshToken(sessionId, refreshTokenValue);
61
- setCookie(c, COOKIE_REFRESH_TOKEN, refreshTokenValue, cookieOptions(getRefreshTokenExpiry()));
62
63
  }
63
- // Append token to redirect so non-browser clients (mobile deep links) can extract it.
64
- // Browser apps can safely ignore the query param.
64
+ // Store a one-time authorization code instead of exposing the token in the redirect URL.
65
+ // The client exchanges this code via POST /auth/oauth/exchange to get the session token.
66
+ const code = await storeOAuthCode({
67
+ token,
68
+ userId: user.id,
69
+ email: profile.email,
70
+ refreshToken: refreshTokenValue,
71
+ });
65
72
  try {
66
73
  const url = new URL(postLoginRedirect);
67
- url.searchParams.set("token", token);
74
+ url.searchParams.set("code", code);
68
75
  if (profile.email)
69
76
  url.searchParams.set("user", profile.email);
70
77
  return c.redirect(url.toString());
@@ -73,7 +80,7 @@ const finishOAuth = async (c, provider, providerId, profile, postLoginRedirect)
73
80
  // Relative path fallback
74
81
  const sep = postLoginRedirect.includes("?") ? "&" : "?";
75
82
  const userParam = profile.email ? `&user=${encodeURIComponent(profile.email)}` : "";
76
- return c.redirect(`${postLoginRedirect}${sep}token=${token}${userParam}`);
83
+ return c.redirect(`${postLoginRedirect}${sep}code=${code}${userParam}`);
77
84
  }
78
85
  };
79
86
  export const createOAuthRouter = (providers, postLoginRedirect) => {
@@ -246,5 +253,262 @@ export const createOAuthRouter = (providers, postLoginRedirect) => {
246
253
  return c.redirect(url.toString());
247
254
  });
248
255
  }
256
+ // ─── Microsoft ──────────────────────────────────────────────────────────
257
+ if (providers.includes("microsoft")) {
258
+ router.openapi(createRoute({
259
+ method: "get",
260
+ path: "/auth/microsoft",
261
+ summary: "Initiate Microsoft OAuth",
262
+ description: "Redirects the user to Microsoft's sign-in page to begin the OAuth login flow. After the user authorizes, Microsoft redirects back to `/auth/microsoft/callback`.",
263
+ tags,
264
+ responses: {
265
+ 302: { description: "Redirect to Microsoft's OAuth sign-in page." },
266
+ 500: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "OAuth provider not configured." },
267
+ },
268
+ }), async (c) => {
269
+ const state = generateState();
270
+ const codeVerifier = generateCodeVerifier();
271
+ await storeOAuthState(state, codeVerifier);
272
+ const url = getMicrosoft().createAuthorizationURL(state, codeVerifier, ["openid", "profile", "email"]);
273
+ return c.redirect(url.toString());
274
+ });
275
+ router.openapi(createRoute({
276
+ method: "get",
277
+ path: "/auth/microsoft/callback",
278
+ summary: "Microsoft OAuth callback",
279
+ description: "Handles the redirect from Microsoft after user authorization. Validates the OAuth state and code, then creates or finds the user account. Sets a session cookie and redirects to the configured post-login URL.",
280
+ tags,
281
+ request: {
282
+ query: z.object({
283
+ code: z.string().describe("Authorization code from Microsoft."),
284
+ state: z.string().describe("OAuth state parameter for CSRF protection."),
285
+ }),
286
+ },
287
+ responses: {
288
+ 302: { description: "Redirect to the post-login URL with session token." },
289
+ 400: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "Invalid callback parameters or expired state." },
290
+ },
291
+ }), async (c) => {
292
+ const { code, state } = c.req.valid("query");
293
+ if (!code || !state)
294
+ return c.json({ error: "Invalid callback" }, 400);
295
+ const stored = await consumeOAuthState(state);
296
+ if (!stored?.codeVerifier)
297
+ return c.json({ error: "Invalid or expired state" }, 400);
298
+ const tokens = await getMicrosoft().validateAuthorizationCode(code, stored.codeVerifier);
299
+ const info = await fetch("https://graph.microsoft.com/v1.0/me", {
300
+ headers: { Authorization: `Bearer ${tokens.accessToken()}` },
301
+ }).then((r) => r.json());
302
+ if (stored.linkUserId) {
303
+ const adapter = getAuthAdapter();
304
+ if (!adapter.linkProvider)
305
+ return c.json({ error: "Auth adapter does not support linkProvider" }, 500);
306
+ await adapter.linkProvider(stored.linkUserId, "microsoft", info.id);
307
+ const sep = postLoginRedirect.includes("?") ? "&" : "?";
308
+ return c.redirect(`${postLoginRedirect}${sep}linked=microsoft`);
309
+ }
310
+ return finishOAuth(c, "microsoft", info.id, { email: info.mail ?? info.userPrincipalName, name: info.displayName }, postLoginRedirect);
311
+ });
312
+ router.use("/auth/microsoft/link", userAuth);
313
+ router.openapi(withSecurity(createRoute({
314
+ method: "get",
315
+ path: "/auth/microsoft/link",
316
+ summary: "Link Microsoft account",
317
+ description: "Initiates an OAuth flow to link a Microsoft account to the authenticated user. Requires a valid session. Redirects to Microsoft's sign-in page.",
318
+ tags,
319
+ responses: {
320
+ 302: { description: "Redirect to Microsoft's OAuth sign-in page." },
321
+ 401: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "No valid session." },
322
+ },
323
+ }), { cookieAuth: [] }, { userToken: [] }), async (c) => {
324
+ const state = generateState();
325
+ const codeVerifier = generateCodeVerifier();
326
+ await storeOAuthState(state, codeVerifier, c.get("authUserId"));
327
+ const url = getMicrosoft().createAuthorizationURL(state, codeVerifier, ["openid", "profile", "email"]);
328
+ return c.redirect(url.toString());
329
+ });
330
+ router.openapi(withSecurity(createRoute({
331
+ method: "delete",
332
+ path: "/auth/microsoft/link",
333
+ summary: "Unlink Microsoft account",
334
+ description: "Removes the linked Microsoft OAuth account from the authenticated user. Requires a valid session.",
335
+ tags,
336
+ responses: {
337
+ 204: { description: "Microsoft account unlinked successfully." },
338
+ 401: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "No valid session." },
339
+ 500: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "Auth adapter does not support unlinkProvider." },
340
+ },
341
+ }), { cookieAuth: [] }, { userToken: [] }), async (c) => {
342
+ const adapter = getAuthAdapter();
343
+ if (!adapter.unlinkProvider) {
344
+ return c.json({ error: "Auth adapter does not support unlinkProvider" }, 500);
345
+ }
346
+ await adapter.unlinkProvider(c.get("authUserId"), "microsoft");
347
+ return c.body(null, 204);
348
+ });
349
+ }
350
+ // ─── GitHub ────────────────────────────────────────────────────────────
351
+ if (providers.includes("github")) {
352
+ router.openapi(createRoute({
353
+ method: "get",
354
+ path: "/auth/github",
355
+ summary: "Initiate GitHub OAuth",
356
+ description: "Redirects the user to GitHub's authorization page to begin the OAuth login flow. After the user authorizes, GitHub redirects back to `/auth/github/callback`.",
357
+ tags,
358
+ responses: {
359
+ 302: { description: "Redirect to GitHub's OAuth authorization page." },
360
+ 500: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "OAuth provider not configured." },
361
+ },
362
+ }), async (c) => {
363
+ const state = generateState();
364
+ await storeOAuthState(state);
365
+ const url = getGitHub().createAuthorizationURL(state, ["read:user", "user:email"]);
366
+ return c.redirect(url.toString());
367
+ });
368
+ router.openapi(createRoute({
369
+ method: "get",
370
+ path: "/auth/github/callback",
371
+ summary: "GitHub OAuth callback",
372
+ description: "Handles the redirect from GitHub after user authorization. Validates the OAuth state and code, then creates or finds the user account. Sets a session cookie and redirects to the configured post-login URL.",
373
+ tags,
374
+ request: {
375
+ query: z.object({
376
+ code: z.string().describe("Authorization code from GitHub."),
377
+ state: z.string().describe("OAuth state parameter for CSRF protection."),
378
+ }),
379
+ },
380
+ responses: {
381
+ 302: { description: "Redirect to the post-login URL with session token." },
382
+ 400: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "Invalid callback parameters or expired state." },
383
+ },
384
+ }), async (c) => {
385
+ const { code, state } = c.req.valid("query");
386
+ if (!code || !state)
387
+ return c.json({ error: "Invalid callback" }, 400);
388
+ const stored = await consumeOAuthState(state);
389
+ if (!stored)
390
+ return c.json({ error: "Invalid or expired state" }, 400);
391
+ const tokens = await getGitHub().validateAuthorizationCode(code);
392
+ const headers = { Authorization: `Bearer ${tokens.accessToken()}`, "User-Agent": "bunshot" };
393
+ const info = await fetch("https://api.github.com/user", { headers })
394
+ .then((r) => r.json());
395
+ // GitHub may not return email on /user if it's private — fetch from /user/emails
396
+ let email = info.email;
397
+ if (!email) {
398
+ const emails = await fetch("https://api.github.com/user/emails", { headers })
399
+ .then((r) => r.json());
400
+ email = emails.find((e) => e.primary && e.verified)?.email ?? emails.find((e) => e.verified)?.email;
401
+ }
402
+ if (stored.linkUserId) {
403
+ const adapter = getAuthAdapter();
404
+ if (!adapter.linkProvider)
405
+ return c.json({ error: "Auth adapter does not support linkProvider" }, 500);
406
+ await adapter.linkProvider(stored.linkUserId, "github", String(info.id));
407
+ const sep = postLoginRedirect.includes("?") ? "&" : "?";
408
+ return c.redirect(`${postLoginRedirect}${sep}linked=github`);
409
+ }
410
+ return finishOAuth(c, "github", String(info.id), { email, name: info.name, avatarUrl: info.avatar_url }, postLoginRedirect);
411
+ });
412
+ router.use("/auth/github/link", userAuth);
413
+ router.openapi(withSecurity(createRoute({
414
+ method: "get",
415
+ path: "/auth/github/link",
416
+ summary: "Link GitHub account",
417
+ description: "Initiates an OAuth flow to link a GitHub account to the authenticated user. Requires a valid session. Redirects to GitHub's authorization page.",
418
+ tags,
419
+ responses: {
420
+ 302: { description: "Redirect to GitHub's OAuth authorization page." },
421
+ 401: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "No valid session." },
422
+ },
423
+ }), { cookieAuth: [] }, { userToken: [] }), async (c) => {
424
+ const state = generateState();
425
+ await storeOAuthState(state, undefined, c.get("authUserId"));
426
+ const url = getGitHub().createAuthorizationURL(state, ["read:user", "user:email"]);
427
+ return c.redirect(url.toString());
428
+ });
429
+ router.openapi(withSecurity(createRoute({
430
+ method: "delete",
431
+ path: "/auth/github/link",
432
+ summary: "Unlink GitHub account",
433
+ description: "Removes the linked GitHub OAuth account from the authenticated user. Requires a valid session.",
434
+ tags,
435
+ responses: {
436
+ 204: { description: "GitHub account unlinked successfully." },
437
+ 401: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "No valid session." },
438
+ 500: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "Auth adapter does not support unlinkProvider." },
439
+ },
440
+ }), { cookieAuth: [] }, { userToken: [] }), async (c) => {
441
+ const adapter = getAuthAdapter();
442
+ if (!adapter.unlinkProvider) {
443
+ return c.json({ error: "Auth adapter does not support unlinkProvider" }, 500);
444
+ }
445
+ await adapter.unlinkProvider(c.get("authUserId"), "github");
446
+ return c.body(null, 204);
447
+ });
448
+ }
449
+ // ─── Code Exchange ─────────────────────────────────────────────────────
450
+ router.openapi(createRoute({
451
+ method: "post",
452
+ path: "/auth/oauth/exchange",
453
+ summary: "Exchange OAuth authorization code for session token",
454
+ description: "Exchanges a one-time authorization code (received from the OAuth redirect) for a session token. The code is single-use and expires after 60 seconds. Sets session cookies for browser clients; returns the token in the JSON response for mobile/SPA clients.",
455
+ tags,
456
+ request: {
457
+ body: {
458
+ content: {
459
+ "application/json": {
460
+ schema: z.object({
461
+ code: z.string().describe("One-time authorization code from the OAuth redirect."),
462
+ }),
463
+ },
464
+ },
465
+ },
466
+ },
467
+ responses: {
468
+ 200: {
469
+ content: {
470
+ "application/json": {
471
+ schema: z.object({
472
+ token: z.string().describe("Session JWT."),
473
+ userId: z.string().describe("Authenticated user ID."),
474
+ email: z.string().optional().describe("User email if available."),
475
+ refreshToken: z.string().optional().describe("Refresh token if refresh tokens are configured."),
476
+ }),
477
+ },
478
+ },
479
+ description: "Session token and user info.",
480
+ },
481
+ 400: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "Missing code parameter." },
482
+ 401: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "Invalid, expired, or already-used code." },
483
+ 429: { content: { "application/json": { schema: OAuthErrorResponse } }, description: "Rate limit exceeded." },
484
+ },
485
+ }), async (c) => {
486
+ // Rate limit by IP to prevent brute-forcing codes within the 60s TTL
487
+ const ip = getClientIp(c);
488
+ const limited = await trackAttempt(`oauth-exchange:ip:${ip}`, { max: 20, windowMs: 60_000 });
489
+ if (limited) {
490
+ return c.json({ error: "Too many requests" }, 429);
491
+ }
492
+ const { code } = c.req.valid("json");
493
+ if (!code)
494
+ return c.json({ error: "Missing code" }, 400);
495
+ const payload = await consumeOAuthCode(code);
496
+ if (!payload)
497
+ return c.json({ error: "Invalid or expired code" }, 401);
498
+ // Set session cookies for browser clients
499
+ const rtConfig = getRefreshTokenConfig();
500
+ setCookie(c, COOKIE_TOKEN, payload.token, cookieOptions(rtConfig ? getAccessTokenExpiry() : undefined));
501
+ if (payload.refreshToken && rtConfig) {
502
+ setCookie(c, COOKIE_REFRESH_TOKEN, payload.refreshToken, cookieOptions(getRefreshTokenExpiry()));
503
+ }
504
+ if (getCsrfEnabled())
505
+ refreshCsrfToken(c);
506
+ return c.json({
507
+ token: payload.token,
508
+ userId: payload.userId,
509
+ email: payload.email,
510
+ refreshToken: payload.refreshToken,
511
+ }, 200);
512
+ });
249
513
  return router;
250
514
  };
@@ -8,3 +8,5 @@ export declare const makeLoginSchema: (primaryField: PrimaryField) => z.ZodObjec
8
8
  [x: string]: z.ZodString;
9
9
  password: z.ZodString;
10
10
  }, z.core.$strip>;
11
+ /** Password schema for reset-password — same policy as registration. */
12
+ export declare const resetPasswordSchema: () => z.ZodString;
@@ -1,9 +1,30 @@
1
1
  import { z } from "zod";
2
+ import { getPasswordPolicy } from "../lib/appConfig";
3
+ /** Build a Zod schema for the password field based on the configured policy.
4
+ * Applied to registration and reset-password. Login uses min(1) intentionally
5
+ * to avoid locking out users registered under older/weaker policies. */
6
+ const passwordSchema = () => {
7
+ const policy = getPasswordPolicy();
8
+ const minLen = policy.minLength ?? 8;
9
+ let schema = z.string().min(minLen, `Password must be at least ${minLen} characters`);
10
+ if (policy.requireLetter !== false) {
11
+ schema = schema.regex(/[a-zA-Z]/, "Password must contain at least one letter");
12
+ }
13
+ if (policy.requireDigit !== false) {
14
+ schema = schema.regex(/\d/, "Password must contain at least one digit");
15
+ }
16
+ if (policy.requireSpecial) {
17
+ schema = schema.regex(/[^a-zA-Z0-9]/, "Password must contain at least one special character");
18
+ }
19
+ return schema;
20
+ };
2
21
  export const makeRegisterSchema = (primaryField) => z.object({
3
22
  [primaryField]: primaryField === "email" ? z.string().email() : z.string().min(3),
4
- password: z.string().min(8),
23
+ password: passwordSchema(),
5
24
  });
6
25
  export const makeLoginSchema = (primaryField) => z.object({
7
26
  [primaryField]: primaryField === "email" ? z.string().email() : z.string().min(1),
8
27
  password: z.string().min(1),
9
28
  });
29
+ /** Password schema for reset-password — same policy as registration. */
30
+ export const resetPasswordSchema = () => passwordSchema();
package/dist/server.d.ts CHANGED
@@ -12,6 +12,12 @@ export interface WsConfig<T extends object = object> {
12
12
  * ws.data.userId is available for auth checks.
13
13
  */
14
14
  onRoomSubscribe?: (ws: ServerWebSocket<SocketData<T>>, room: string) => boolean | Promise<boolean>;
15
+ /**
16
+ * Maximum allowed WebSocket message size in bytes.
17
+ * Messages exceeding this limit will cause the connection to be closed with code 1009.
18
+ * Defaults to 65536 (64 KB).
19
+ */
20
+ maxMessageSize?: number;
15
21
  }
16
22
  export interface CreateServerConfig<T extends object = object> extends CreateAppConfig {
17
23
  port?: number;
package/dist/server.js CHANGED
@@ -6,16 +6,23 @@ export const createServer = async (config) => {
6
6
  const app = await createApp(config);
7
7
  const port = Number(process.env.PORT ?? config.port ?? 3000);
8
8
  const { workersDir, enableWorkers = true, ws: wsConfig = {} } = config;
9
- const { handler: userWs, upgradeHandler: wsUpgradeHandler, onRoomSubscribe } = wsConfig;
9
+ const { handler: userWs, upgradeHandler: wsUpgradeHandler, onRoomSubscribe, maxMessageSize = 65_536 } = wsConfig;
10
10
  const defaultOpen = defaultWebsocket.open;
11
- const defaultMessage = defaultWebsocket.message;
12
11
  const defaultClose = defaultWebsocket.close;
13
12
  const defaultDrain = defaultWebsocket.drain;
14
13
  const ws = {
15
14
  open: userWs?.open ?? defaultOpen,
16
15
  async message(socket, message) {
16
+ const size = typeof message === "string" ? message.length : message.byteLength;
17
+ if (size > maxMessageSize) {
18
+ socket.close(1009, "Message too large");
19
+ return;
20
+ }
17
21
  if (!await handleRoomActions(socket, message, onRoomSubscribe)) {
18
- (userWs?.message ?? defaultMessage)(socket, message);
22
+ if (userWs?.message) {
23
+ userWs.message(socket, message);
24
+ }
25
+ // No default echo — without a custom handler, non-room messages are silently dropped
19
26
  }
20
27
  },
21
28
  close(socket, code, reason) {
@@ -9,6 +9,7 @@ export interface AuthResult {
9
9
  mfaRequired?: boolean;
10
10
  mfaToken?: string;
11
11
  mfaMethods?: string[];
12
+ webauthnOptions?: Record<string, unknown>;
12
13
  }
13
14
  /** Create a session for a user (used internally and by MFA verify). */
14
15
  export declare const createSessionForUser: (userId: string, metadata?: SessionMetadata) => Promise<{
@@ -2,10 +2,10 @@ import { getAuthAdapter } from "../lib/authAdapter";
2
2
  import { HttpError } from "../lib/HttpError";
3
3
  import { signToken, verifyToken } from "../lib/jwt";
4
4
  import { createSession, deleteSession, getActiveSessionCount, evictOldestSession, deleteUserSessions, setRefreshToken, getSessionByRefreshToken, rotateRefreshToken } from "../lib/session";
5
- import { getDefaultRole, getPrimaryField, getEmailVerificationConfig, getMaxSessions, getRefreshTokenConfig, getAccessTokenExpiry, getMfaConfig, getMfaEmailOtpConfig } from "../lib/appConfig";
5
+ import { getDefaultRole, getPrimaryField, getEmailVerificationConfig, getMaxSessions, getRefreshTokenConfig, getAccessTokenExpiry, getMfaConfig, getMfaEmailOtpConfig, getMfaWebAuthnConfig } from "../lib/appConfig";
6
6
  import { createVerificationToken } from "../lib/emailVerification";
7
7
  import { createMfaChallenge } from "../lib/mfaChallenge";
8
- import { generateEmailOtpCode } from "./mfa";
8
+ import { generateEmailOtpCode, generateWebAuthnAuthenticationOptions } from "./mfa";
9
9
  async function createSessionWithRefreshToken(userId, sessionId, metadata) {
10
10
  const rtConfig = getRefreshTokenConfig();
11
11
  const expirySeconds = rtConfig ? getAccessTokenExpiry() : undefined;
@@ -47,11 +47,16 @@ export const register = async (identifier, password, metadata) => {
47
47
  }
48
48
  return { token, userId: user.id, email: identifier, refreshToken };
49
49
  };
50
+ // Pre-computed dummy hash so non-existent-user login takes the same time as wrong-password login
51
+ const DUMMY_HASH = await Bun.password.hash("dummy-timing-safe-placeholder");
50
52
  export const login = async (identifier, password, metadata) => {
51
53
  const adapter = getAuthAdapter();
52
54
  const findFn = adapter.findByIdentifier ?? adapter.findByEmail.bind(adapter);
53
55
  const user = await findFn(identifier);
54
- if (!user || !(await Bun.password.verify(password, user.passwordHash))) {
56
+ // Always verify against a hash to prevent timing-based user enumeration
57
+ const hashToVerify = user?.passwordHash ?? DUMMY_HASH;
58
+ const passwordValid = await Bun.password.verify(password, hashToVerify);
59
+ if (!user || !passwordValid) {
55
60
  throw new HttpError(401, "Invalid credentials");
56
61
  }
57
62
  // Check email verification before MFA to avoid leaking MFA status to unverified users
@@ -79,8 +84,19 @@ export const login = async (identifier, password, metadata) => {
79
84
  if (email)
80
85
  await emailOtpConfig.onSend(email, code);
81
86
  }
82
- const mfaToken = await createMfaChallenge(user.id, emailOtpHash);
83
- return { token: "", userId: user.id, mfaRequired: true, mfaToken, mfaMethods: methods };
87
+ // Generate WebAuthn authentication options if enabled
88
+ let webauthnChallenge;
89
+ let webauthnOptions;
90
+ const webauthnConfig = getMfaWebAuthnConfig();
91
+ if (methods.includes("webauthn") && webauthnConfig && adapter.getWebAuthnCredentials) {
92
+ const result = await generateWebAuthnAuthenticationOptions(user.id);
93
+ if (result) {
94
+ webauthnChallenge = result.challenge;
95
+ webauthnOptions = result.options;
96
+ }
97
+ }
98
+ const mfaToken = await createMfaChallenge(user.id, { emailOtpHash, webauthnChallenge });
99
+ return { token: "", userId: user.id, mfaRequired: true, mfaToken, mfaMethods: methods, webauthnOptions };
84
100
  }
85
101
  const sessionId = crypto.randomUUID();
86
102
  const { token, refreshToken } = await createSessionWithRefreshToken(user.id, sessionId, metadata);
@@ -35,3 +35,50 @@ export declare const disableEmailOtp: (userId: string, params: {
35
35
  }) => Promise<void>;
36
36
  /** Get the MFA methods enabled for a user. */
37
37
  export declare const getMfaMethods: (userId: string) => Promise<string[]>;
38
+ /**
39
+ * Eager startup check — call at route mount time to fail fast if the peer dependency is missing.
40
+ */
41
+ export declare const assertWebAuthnDependency: () => Promise<void>;
42
+ /**
43
+ * Generate WebAuthn authentication options for the login MFA flow.
44
+ * Called from auth.ts login when the user has "webauthn" in their methods.
45
+ */
46
+ export declare const generateWebAuthnAuthenticationOptions: (userId: string) => Promise<{
47
+ challenge: string;
48
+ options: Record<string, unknown>;
49
+ } | null>;
50
+ /**
51
+ * Initiate WebAuthn registration: generates registration options for the client.
52
+ * Returns options + a registration challenge token.
53
+ */
54
+ export declare const initiateWebAuthnRegistration: (userId: string) => Promise<{
55
+ options: Record<string, unknown>;
56
+ registrationToken: string;
57
+ }>;
58
+ /**
59
+ * Complete WebAuthn registration: verifies attestation and stores the credential.
60
+ * Returns recovery codes if this is the first MFA method.
61
+ */
62
+ export declare const completeWebAuthnRegistration: (userId: string, registrationToken: string, attestationResponse: any, name?: string) => Promise<{
63
+ credentialId: string;
64
+ recoveryCodes: string[] | null;
65
+ }>;
66
+ /**
67
+ * Verify a WebAuthn authentication assertion during login MFA.
68
+ */
69
+ export declare const verifyWebAuthn: (userId: string, assertionResponse: any, expectedChallenge: string) => Promise<boolean>;
70
+ /**
71
+ * Remove a single WebAuthn credential.
72
+ * Only requires identity verification when removing the last credential of the last MFA method.
73
+ */
74
+ export declare const removeWebAuthnCredential: (userId: string, credentialId: string, params: {
75
+ code?: string;
76
+ password?: string;
77
+ }) => Promise<void>;
78
+ /**
79
+ * Disable WebAuthn entirely: removes all credentials and the method.
80
+ */
81
+ export declare const disableWebAuthn: (userId: string, params: {
82
+ code?: string;
83
+ password?: string;
84
+ }) => Promise<void>;