All files / src auth.ts

0% Statements 0/649
0% Branches 0/1
0% Functions 0/1
0% Lines 0/649

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { passkey } from "@better-auth/passkey";
import { sso } from "@better-auth/sso";
import { ENABLE_CAPTCHA, ENABLE_ENHANCED_2FA, ENABLE_MULTI_SESSION, ENABLE_SSO } from "@snapback/config";
import { getBaseUrl } from "@snapback/config/server"; // Use centralized config
import { logger } from "@snapback/infrastructure";
import { send as sendEmail } from "@snapback/integrations/email";
import { combinedSchema, db } from "@snapback/platform";
 
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import {
	admin,
	apiKey,
	bearer,
	captcha,
	deviceAuthorization,
	haveIBeenPwned,
	jwt,
	magicLink,
	multiSession,
	openAPI,
	organization,
	twoFactor,
	username,
} from "better-auth/plugins";
import { parse as parseCookies } from "cookie";
import { nanoid } from "nanoid";
import { trackEvent } from "./lib/audit";
import { ac, admin as adminRole, member as memberRole, owner as ownerRole } from "./lib/organization-permissions";
import { invitationOnlyPlugin } from "./plugins/invitation-only/index";
 
const _getLocaleFromRequest = (request?: Request) => {
	const cookies = parseCookies(request?.headers.get("cookie") ?? "");
	return cookies.NEXT_LOCALE ?? "en";
};
 
// Frontend app URL (for OAuth redirects and CORS)
// Access process.env directly for Vercel compatibility (t3-env wrapper issue)
const appUrl = process.env.APP_URL || getBaseUrl();
 
// Better Auth base URL (where auth endpoints are served)
// CRITICAL: Auth routes are in the WEB app, NOT the API server!
// - Web app: Has /api/auth/* routes (this is where Better Auth runs)
// - API server: Backend API only, no auth routes
//
// Priority: BETTER_AUTH_URL (explicit) > APP_URL > fallback
// In dev: BETTER_AUTH_URL should be :3000 (web app with auth routes)
//         APP_URL might be :3003 (API server - no auth routes)
//
// IMPORTANT: This must be set or Better Auth will log warnings
// Access process.env directly for Vercel compatibility (t3-env wrapper issue)
const authBaseUrl =
	process.env.BETTER_AUTH_URL ||
	process.env.BETTER_AUTH_BASE_URL ||
	process.env.APP_URL ||
	`http://localhost:${process.env.PORT || 3000}`;
 
// In development, trust all localhost ports to handle Next.js dynamic port assignment
// Access process.env directly for Vercel compatibility (t3-env wrapper issue)
// Detect local development regardless of NODE_ENV.
// Doppler prd config sets NODE_ENV=production even when running locally,
// so we also check if BETTER_AUTH_URL is a localhost URL.
const isLocalDev = (process.env.BETTER_AUTH_URL || "").includes("localhost");
const isDevelopment = process.env.NODE_ENV !== "production" || isLocalDev;
const trustedOrigins = isDevelopment
	? [
			appUrl,
			authBaseUrl,
			"http://localhost:3000",
			"http://localhost:3001",
			"http://localhost:3002",
			"http://localhost:3003",
		]
	: [appUrl, authBaseUrl].filter((url, index, arr) => arr.indexOf(url) === index);
 
// ============================================================================
// Redis Secondary Storage Configuration
// ============================================================================
 
/**
 * Initialize Redis client for Better Auth secondary storage
 * Used for distributed rate limiting and session caching
 *
 * Production Features:
 * - Exponential backoff with jitter (up to 20 retries)
 * - TCP keepalive (5s) to prevent silent drops
 * - Application-level ping (60s) to keep connection alive
 * - Key namespacing for auth data
 */
 
// Key prefix for auth-related Redis operations
const AUTH_KEY_PREFIX = "auth:";
 
export let redisClient: any = null;
export let redisAvailable = false;
 
// Track reconnection attempts for metrics
let authRedisReconnectAttempts = 0;
 
async function initializeRedis() {
	// Access process.env directly for Vercel compatibility (t3-env wrapper issue)
	if (!process.env.REDIS_URL) {
		// Only log warning if not in MCP quiet mode
		if (process.env.MCP_QUIET !== "1") {
			logger.warn("REDIS_URL not configured - rate limiting will use database fallback");
		}
		return;
	}
 
	try {
		// Dynamic import to handle optional redis dependency
		const redis = await import("redis").catch(() => null);
		if (!redis) {
			logger.warn("Redis module not available");
			return;
		}
		// Validate REDIS_URL format before attempting connection
		const redisUrl = process.env.REDIS_URL!; // Non-null assertion safe - checked above
		if (!redisUrl.startsWith("redis://") && !redisUrl.startsWith("rediss://")) {
			logger.error("Invalid REDIS_URL format", {
				error: "REDIS_URL must start with 'redis://' or 'rediss://' protocol",
				example: "redis://localhost:6379",
				provided: `${redisUrl.split(":")[0]}:...`, // Only show protocol part
			});
			redisAvailable = false;
			return;
		}
 
		// Production-ready Redis client configuration
		redisClient = redis.createClient({
			url: redisUrl,
			socket: {
				// Connection timeout - how long to wait for initial connection
				connectTimeout: 10000, // 10s (increased from 5s)
				// TCP keepalive - prevents silent connection drops
				keepAlive: 5000, // 5s
				// Reconnection strategy with exponential backoff + jitter
				reconnectStrategy: (retries: number, cause: Error) => {
					// Don't reconnect on socket timeout - indicates a different issue
					// Check by error name since SocketTimeoutError isn't exported from redis
					if (cause?.name === "SocketTimeoutError" || cause?.message?.includes("socket timeout")) {
						logger.warn("Redis socket timeout for Better Auth - not reconnecting", {
							cause: cause?.message,
						});
						return false;
					}
 
					// Track reconnection attempts
					authRedisReconnectAttempts++;
 
					// Give up after 20 retries (increased from 3)
					if (retries > 20) {
						logger.error("Redis max retries exceeded", { retries, cause: cause?.message });
						return new Error("Max retries reached");
					}
 
					// Exponential backoff with jitter
					// 100ms, 200ms, 400ms, 800ms, ... max 30s
					const baseDelay = Math.min(2 ** retries * 100, 30000);
					const jitter = Math.floor(Math.random() * 200);
					const delay = baseDelay + jitter;
 
					if (process.env.MCP_QUIET !== "1" && retries % 5 === 0) {
						logger.debug("Redis reconnecting for Better Auth", { retries, delay });
					}
					return delay;
				},
			},
			// Application-level ping to keep connection alive
			pingInterval: 60000, // 60s
		});
 
		redisClient.on("error", (err: Error) => {
			// Don't log ECONNRESET as warning - it's expected during reconnection
			if (err.message.includes("ECONNRESET") || err.message.includes("ECONNREFUSED")) {
				logger.debug("Redis connection error (will reconnect)", { error: err.message });
			} else {
				logger.warn("Redis connection error", { error: err.message });
			}
			redisAvailable = false;
		});
 
		redisClient.on("connect", () => {
			if (process.env.MCP_QUIET !== "1") {
				logger.info("Redis connected for Better Auth secondary storage");
			}
			redisAvailable = true;
		});
 
		redisClient.on("ready", () => {
			// Reset reconnection counter on successful connection
			authRedisReconnectAttempts = 0;
			redisAvailable = true;
		});
 
		redisClient.on("reconnecting", () => {
			if (process.env.MCP_QUIET !== "1") {
				logger.debug("Redis reconnecting for Better Auth...");
			}
		});
 
		await redisClient.connect();
		redisAvailable = true;
		if (process.env.MCP_QUIET !== "1") {
			logger.info("✅ Better Auth Redis secondary storage initialized with production config");
		}
	} catch (error) {
		logger.warn("Redis initialization failed - using database fallback", {
			error: error instanceof Error ? error.message : String(error),
		});
		redisAvailable = false;
	}
}
 
/**
 * Get Redis reconnection attempt count for monitoring
 */
export function getAuthRedisReconnectAttempts(): number {
	return authRedisReconnectAttempts;
}
 
// Initialize Redis on module load
initializeRedis().catch((err) => {
	logger.error("Failed to initialize Redis for Better Auth", {
		error: err instanceof Error ? err.message : String(err),
	});
});
 
const _auth = betterAuth({
	// ✅ Base URL for callbacks and redirects (required by Better Auth)
	// Uses BETTER_AUTH_URL env var, falling back to localhost with PORT
	baseURL: authBaseUrl,
 
	// Extend the user schema with additional fields
	schema: {
		user: {
			fields: {
				onboardingComplete: {
					type: "boolean",
					required: false,
					defaultValue: false,
				},
				deviceFingerprint: {
					type: "string",
					required: false,
				},
			},
		},
	},
	appName: "SnapBack",
 
	// ✅ SECURITY: Prevent account enumeration attacks
	// OWASP ASVS 2.2.1 - Don't reveal whether username exists
	disablePaths: ["/is-username-available"],
 
	endpoints: {
		GET: {
			"/health": {
				async handler() {
					return new Response("OK", { status: 200 });
				},
			},
		},
	},
	emailAndPassword: {
		enabled: true,
		// Account lockout hooks are handled via middleware (see account-lockout.ts)
		// - incrementFailedAttempts() called on failed login
		// - resetFailedAttempts() called on successful login
	},
	socialProviders: {
		// Only include social providers if credentials are configured
		// This prevents Better Auth from logging warnings that corrupt MCP stdio
		// Note: Access process.env directly for Vercel compatibility (t3-env wrapper issue)
		...(process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET
			? {
					github: {
						clientId: process.env.GITHUB_CLIENT_ID,
						clientSecret: process.env.GITHUB_CLIENT_SECRET,
					},
				}
			: {}),
		...(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET
			? {
					google: {
						clientId: process.env.GOOGLE_CLIENT_ID,
						clientSecret: process.env.GOOGLE_CLIENT_SECRET,
					},
				}
			: {}),
	},
	database: drizzleAdapter(db as any, {
		provider: "pg",
		schema: combinedSchema,
	}),
	session: {
		expiresIn: 60 * 60 * 24 * 7, // 7 days
		updateAge: 60 * 60 * 24, // 1 day
 
		// ✅ CRITICAL FIX: Always store sessions in DB so findSession() falls back
		// to the primary DB when Redis (secondaryStorage) is unavailable or misses.
		// Without this, a Redis miss in serverless (Vercel cold start, connection lag)
		// causes findSession to return null WITHOUT checking the DB, silently breaking
		// bearer token validation (CLI device auth, auto-provision API key).
		storeSessionInDatabase: true,
 
		// ✅ OPTIMIZATION: Cookie cache for 80% database load reduction
		// Note: When database/secondaryStorage is configured, we use cookieCache
		// WITHOUT refreshCache (which is only for stateless/DB-less setups)
		// The cache reduces DB queries by storing session data in signed cookies
		cookieCache: {
			enabled: true,
			maxAge: 5 * 60, // 5 minutes - short-lived, signed cookie
			strategy: "jwe", // Use JWE for encrypted session data (most secure)
			// refreshCache is intentionally NOT set here - it's for stateless setups only
		},
	},
	account: {
		accountLinking: {
			enabled: true,
			trustedProviders: ["google", "github"],
		},
	},
	trustedOrigins,
 
	// ✅ OPTIMIZATION: Redis secondary storage for distributed rate limiting
	// Uses a lazy wrapper so Redis connects asynchronously without blocking
	// betterAuth() initialization. Each call checks redisAvailable at runtime.
	secondaryStorage: {
		get: async (key: string) => {
			if (!redisAvailable || !redisClient) return null;
			try {
				return await redisClient.get(key);
			} catch (error) {
				logger.error("Redis get failed", { key, error });
				return null;
			}
		},
		set: async (key: string, value: string, ttl?: number) => {
			if (!redisAvailable || !redisClient) return;
			try {
				if (ttl) {
					await redisClient.set(key, value, { EX: ttl });
				} else {
					await redisClient.set(key, value);
				}
			} catch (error) {
				logger.error("Redis set failed", { key, error });
			}
		},
		delete: async (key: string) => {
			if (!redisAvailable || !redisClient) return;
			try {
				await redisClient.del(key);
			} catch (error) {
				logger.error("Redis delete failed", { key, error });
			}
		},
	},
 
	advanced: {
		// ✅ FIX: Use isDevelopment (not NODE_ENV) so Doppler prd config running locally
		// still gets dev-friendly cookie settings. isDevelopment checks BETTER_AUTH_URL
		// for localhost, which Doppler overrides correctly.
		useSecureCookies: !isDevelopment,
 
		crossSiteRequestForgery: {
			enabled: true,
			// Verify origin header matches trusted origins
			checkOrigin: true,
		},
 
		// ✅ OPTIMIZATION: Explicit ID generation using nanoid
		database: {
			generateId: () => nanoid(),
			defaultFindManyLimit: 100, // Prevent unbounded queries
			experimentalJoins: false, // Disable experimental features in production
		},
 
		// ✅ OPTIMIZATION: IP tracking configuration for security audit
		ipAddress: {
			ipAddressHeaders: [
				"cf-connecting-ip", // Cloudflare (highest priority)
				"x-real-ip", // Nginx proxy
				"x-forwarded-for", // Standard proxy header
				"x-client-ip",
			],
			disableIpTracking: false, // Enable IP tracking for security
		},
 
		// ✅ OPTIMIZATION: Enhanced cookie configuration
		// ✅ FIX: Use isDevelopment consistently (not env.NODE_ENV === "production")
		// Doppler prd sets NODE_ENV=production even when running locally, which would
		// incorrectly set domain=".snapback.dev" on localhost cookies.
		crossSubDomainCookies: {
			enabled: !isDevelopment,
			domain: !isDevelopment ? ".snapback.dev" : undefined,
		},
 
		defaultCookieAttributes: {
			sameSite: "lax",
			secure: !isDevelopment,
			httpOnly: true,
			path: "/",
		},
 
		// ✅ FIX: OAuth state/pkce cookies need SameSite=None for cross-site redirects
		// See: https://github.com/better-auth/better-auth/issues/6483
		// Note: In development (localhost), browsers allow SameSite=None without Secure
		cookies: {
			state: {
				name: "snapback.state",
				attributes: {
					sameSite: isDevelopment ? "lax" : "none",
					secure: !isDevelopment,
					httpOnly: true,
					path: "/",
					maxAge: 600, // 10 minutes (OAuth flow timeout)
				},
			},
			pkce: {
				name: "snapback.pkce",
				attributes: {
					sameSite: isDevelopment ? "lax" : "none",
					secure: !isDevelopment,
					httpOnly: true,
					path: "/",
					maxAge: 600,
				},
			},
		},
 
		cookiePrefix: "snapback", // Namespace cookies
	},
	// Rate limiting configuration (replaces 340+ lines of custom rate limit code)
	rateLimit: {
		window: 60, // 60 seconds
		max: 100, // 100 requests per window (global default)
 
		// ✅ OPTIMIZATION: Use Redis for distributed rate limiting via secondaryStorage.
		// secondaryStorage lazy-checks redisAvailable at runtime, so this is always safe.
		storage: "secondary-storage",
 
		customRules: {
			// Strict limits for authentication endpoints
			"/sign-in/email": {
				window: 10, // 10 seconds
				max: 3, // 3 attempts per 10 seconds (brute force protection)
			},
			"/sign-in/social": {
				window: 10,
				max: 5,
			},
			"/sign-up": {
				window: 60,
				max: 5, // 5 signups per minute
			},
			"/password-reset": {
				window: 60,
				max: 3, // 3 reset attempts per minute
			},
			// RFC 8628 Device Authorization - protect against brute-force of user codes
			"/device/*": {
				window: 60,
				max: isDevelopment ? 100 : 10, // Higher limit for local dev testing
			},
			// Higher limits for normal API endpoints
			"/api/*": {
				window: 60,
				max: 500,
			},
			// No rate limiting for health checks
			"/health": false,
			"/health/ready": false,
			"/health/live": false,
		},
	},
	// Use database hooks for audit logging (replaces 371 lines of custom auth-audit.ts)
	// Also includes rate limiting configuration (replaces 340+ lines of custom rate limit code)
	databaseHooks: {
		session: {
			create: {
				after: async (session: any) => {
					// Track session creation (indicates successful auth)
					await trackEvent("session.created", {
						userId: session.userId,
					});
 
					// Also track auth.signin for returning users (session without new user)
					// This fires on every login (new session = successful signin)
					await trackEvent("auth.signin", {
						userId: session.userId,
						timestamp: new Date().toISOString(),
					});
 
					// ✅ SECURITY: Session regeneration on login (prevents session fixation)
					// Invalidate any old sessions to prevent fixation attacks
					// OWASP A07:2021 - Session Fixation Prevention
					try {
						// Delete all previous sessions for this user EXCEPT the current one
						const { db } = await import("@snapback/platform");
						const { sql } = await import("drizzle-orm");
 
						if (db) {
							const result = await db.execute(sql`
								DELETE FROM session
								WHERE "userId" = ${session.userId}
								AND id != ${session.id}
							`);
 
							const rotatedCount = result.rowCount || 0;
							if (rotatedCount > 0) {
								logger.info("Session regenerated on login - old sessions invalidated", {
									userId: session.userId,
									sessionId: session.id,
									rotatedCount,
								});
 
								await trackEvent("session.regenerated" as any, {
									userId: session.userId,
									reason: "login",
									rotatedCount,
								});
							}
						}
					} catch (error) {
						// Don't fail login if session rotation fails
						logger.warn("Session regeneration failed on login", {
							userId: session.userId,
							error: error instanceof Error ? error.message : String(error),
						});
					}
 
					// ✅ AUTO-SET ACTIVE ORG: If user has org but session doesn't have activeOrganizationId
					// This handles the race condition after signup where org is created but session doesn't know
					try {
						if (!session.activeOrganizationId) {
							const { db, combinedSchema } = await import("@snapback/platform");
							const { sql } = await import("drizzle-orm");
 
							if (db) {
								const { member, session: sessionTable } = combinedSchema;
 
								// Find user's first organization (they should have one from auto-provisioning)
								const membership = await db
									.select({ organizationId: member.organizationId })
									.from(member)
									.where(sql`${member.userId} = ${session.userId}`)
									.orderBy(member.createdAt)
									.limit(1);
 
								if (membership.length > 0 && membership[0]?.organizationId) {
									// Set the active organization on this session
									await db
										.update(sessionTable)
										.set({ activeOrganizationId: membership[0].organizationId })
										.where(sql`${sessionTable.id} = ${session.id}`);
 
									logger.info("Auto-set active organization for session", {
										userId: session.userId,
										sessionId: session.id,
										organizationId: membership[0].organizationId,
									});
								}
							}
						}
					} catch (error) {
						// Don't fail session creation if auto-set fails
						logger.warn("Failed to auto-set active organization", {
							userId: session.userId,
							sessionId: session.id,
							error: error instanceof Error ? error.message : String(error),
						});
					}
				},
			},
			delete: {
				after: async (session: any) => {
					// Track logout/session revocation
					await trackEvent("session.revoked", {
						userId: session.userId,
					});
 
					// Also track auth.signout for analytics funnel
					await trackEvent("auth.signout", {
						userId: session.userId,
						timestamp: new Date().toISOString(),
					});
				},
			},
		},
		user: {
			create: {
				after: async (user: any) => {
					// Track new user signup
					await trackEvent("auth.signup", {
						userId: user.id,
						timestamp: new Date().toISOString(),
					});
 
					// ✅ NEW: Auto-populate Pioneer profile on OAuth signup
					// This ensures every user automatically gets a Pioneer profile
					// with proper tier tracking and referral codes
					try {
						const { onOAuthSuccess } = await import("./lib/pioneer-oauth-hook");
						await onOAuthSuccess(user);
					} catch (error) {
						// Don't fail auth flow if pioneer hook fails
						logger.error("Pioneer OAuth hook failed", { userId: user.id, error });
					}
 
					// ✅ AUTO-ORG: Create personal organization for new user
					// This ensures every user has a billing context from day one.
					// Enterprise security: transaction-safe, audit-logged, XSS-sanitized.
					try {
						const { autoProvisionOrganization } = await import("./lib/auto-provision-organization");
						const result = await autoProvisionOrganization(user);
						if (!result.success) {
							// Log but don't fail - user can create org manually
							logger.warn("Auto-org provisioning failed", {
								userId: user.id,
								error: result.error,
							});
						}
					} catch (error) {
						// Don't fail auth flow if auto-org fails
						logger.error("Auto-org provisioning error", { userId: user.id, error });
					}
				},
			},
		},
	},
	plugins: [
		// ✅ CRITICAL: Bearer plugin enables getSession to validate Bearer tokens
		// Required for CLI device flow where access_token is passed via Authorization header
		// Without this, getSession only checks session cookies, not Bearer tokens
		bearer(),
 
		// ✅ RFC 8628 Device Authorization Grant Flow (for WSL, Remote SSH, Codespaces)
		deviceAuthorization({
			// IMPORTANT: Must point to /link page on web app where users verify their device code
			// Better Auth uses baseURL to construct full URI, but baseURL might point to API
			// Users need to visit the web app to verify their device code
			verificationUri: `${appUrl}/link`,
		}),
		admin(),
		apiKey({
			// ✅ CONSOLIDATED: Single source of truth for API key management
			// Replaces: KeysDb, apikeys-service, in-memory keys.ts
 
			// Key format: sk_live_[64 chars] or sk_test_[64 chars]
			defaultPrefix: "sk_live_",
			defaultKeyLength: 64,
 
			// Schema mapping - use our existing apiKeys table with snake_case columns
			schema: {
				apikey: {
					modelName: "apiKeys",
					fields: {
						// Map Better Auth field names to our Drizzle schema property names
						userId: "userId",
						name: "name", // Key display name
						key: "key", // Hashed key value
						start: "start", // First few chars for lookup
						prefix: "prefix", // Key prefix
						createdAt: "createdAt",
						updatedAt: "updatedAt",
					},
				},
			},
 
			// Permissions model: { resource: [actions] }
			permissions: {
				defaultPermissions: {
					"snapback:analyze": ["read"],
					"snapback:snapshot": ["read", "write"],
					"snapback:context": ["read"],
					// MCP server tool access - enables API key usage with MCP protocol
					mcp: ["tools"],
					// API access levels
					api: ["read", "write"],
					// CLI operations
					cli: ["snapshots"],
				},
			},
 
			// Enable automatic session creation for API key-authenticated requests
			// This eliminates need for separate verifyApiKey + getSession calls
			enableSessionForAPIKeys: true,
 
			// Global rate limiting for all API keys
			rateLimit: {
				enabled: true,
				timeWindow: 86400000, // 1 day in milliseconds
				maxRequests: 10000, // Default quota per day
			},
 
			// Enable metadata storage for additional key info
			enableMetadata: true,
		}),
		// ✅ LEVEL 4: JWT plugin with device-specific token issuance
		jwt({
			issuer: appUrl,
			audience: ["vscode", "mcp", "cli"],
			expirationTime: 60 * 15, // 15 minutes for tool JWTs
		} as any),
		magicLink({
			// SECURITY: Token expiration (default 5 min per Better Auth)
			// Links older than this are rejected
			expiresIn: 300, // 5 minutes
 
			async sendMagicLink({ email, url }) {
				await sendEmail({
					to: email,
					subject: "Sign in to SnapBack",
					text: `Click the link to sign in: ${url}`,
					html: `<p>Click the link to sign in: <a href="${url}">${url}</a></p>`,
				});
			},
		}),
		openAPI(),
 
		// ✅ OPTIMIZATION: Organization plugin with RBAC configuration
		// ✅ SECURITY: Session rotation on privilege escalation
		// Note: Call rotateSessionsOnOrgRoleChange() manually after updateMemberRole()
		// See: src/lib/session-rotation.ts
		organization({
			// Access control instance from organization-permissions.ts
			ac,
 
			// Define roles and permissions
			roles: {
				owner: ownerRole,
				admin: adminRole,
				member: memberRole,
			},
 
			// Organization creation settings
			allowUserToCreateOrganization: true,
			organizationLimit: 5, // Max 5 orgs per user (prevent abuse)
 
			// SECURITY: Invitation expiration (7 days per OWASP recommendation)
			// After this period, invitations must be re-sent
			invitationExpiresIn: 7 * 24 * 60 * 60, // 7 days in seconds
 
			// Send invitation emails
			async sendInvitationEmail({
				invitation,
				organization,
			}: {
				invitation: { id: string; email: string; expiresAt: Date };
				organization: { name: string };
			}) {
				// Added proper typing
				const { id, email, expiresAt } = invitation;
				const url = new URL(appUrl);
				url.pathname = "/accept-invitation";
				url.searchParams.set("invitationId", id);
				url.searchParams.set("email", email);
 
				// Include expiration info in email for transparency
				const expiresInDays = Math.ceil((expiresAt.getTime() - Date.now()) / (1000 * 60 * 60 * 24));
 
				await sendEmail({
					to: email,
					subject: `You've been invited to join ${organization.name} on SnapBack`,
					text: `You've been invited to join ${organization.name}. Click the link to accept: ${url.toString()}\n\nThis invitation expires in ${expiresInDays} days.`,
					html: `<p>You've been invited to join <strong>${organization.name}</strong> on SnapBack.</p><p><a href="${url.toString()}">Click here to accept the invitation</a></p><p><small>This invitation expires in ${expiresInDays} days.</small></p>`,
				});
			},
		}),
		invitationOnlyPlugin(),
 
		// ✅ SECURITY: Password breach detection via HaveIBeenPwned
		// OWASP A07:2021, NIST SP 800-63B Section 5.1.1.2
		// Automatically checks passwords during signup and password changes
		haveIBeenPwned(),
 
		// ✅ SECURITY: Two-Factor Authentication
		// NIST SP 800-63B compliant configuration
		twoFactor({
			// Application name shown in authenticator apps
			issuer: "SnapBack",
			// Require verification on enable for security
			skipVerificationOnEnable: false,
			// TOTP configuration
			totpOptions: {
				// 6-digit codes (standard)
				digits: 6,
				// 30-second validity period (TOTP standard)
				period: 30,
			},
			// Backup codes configuration (enhanced when ENABLE_ENHANCED_2FA=true)
			backupCodeOptions: {
				// Number of backup codes to generate
				amount: ENABLE_ENHANCED_2FA ? 10 : 6,
				// Backup code length (longer for enterprise)
				length: ENABLE_ENHANCED_2FA ? 12 : 8,
			},
		}),
		username({
			// Removed onUserUpdated as it's not a valid config option
		}),
		passkey({
			// Removed sendVerificationEmail as it's not a valid config option
		}),
 
		// =============================================================================
		// Enterprise Auth Plugins (Feature Flag Gated)
		// =============================================================================
 
		// ✅ ENTERPRISE: SSO Plugin (SAML 2.0 / OIDC)
		// Requires: ENABLE_SSO=true, @better-auth/sso package
		...(ENABLE_SSO
			? [
					sso({
						// Auto-provision users to organization based on domain
						provisionUser: async ({ user, userInfo }) => {
							// PII: Hash email for privacy-safe logging
							const emailHash = user.email
								? `email_${Math.abs(
										user.email
											.split("")
											.reduce((acc, char) => ((acc << 5) - acc + char.charCodeAt(0)) | 0, 0),
									)
										.toString(16)
										.padStart(8, "0")}`
								: "none";
							logger.info("SSO user provisioning", { userId: user.id, emailHash });
							// Update user with IdP-provided email verification status
							if (userInfo?.email_verified && !user.emailVerified) {
								// The user object is already created, we just log the provisioning
								// Email verification status is handled by trustEmailVerified option
							}
						},
						// Organization auto-provisioning settings
						organizationProvisioning: {
							defaultRole: "member",
						},
						// Allow new users via SSO (don't require pre-existing account)
						disableImplicitSignUp: false,
						// Trust IdP email verification status
						trustEmailVerified: true,
						// Domain verification for SSO providers
						domainVerification: {
							enabled: true,
						},
					}),
				]
			: []),
 
		// ✅ SECURITY: Captcha Plugin (Bot Protection)
		// OWASP A07:2021 - Prevents automated attacks on auth endpoints
		// Requires: ENABLE_CAPTCHA=true, CAPTCHA_SECRET_KEY env var
		...(ENABLE_CAPTCHA && process.env.CAPTCHA_SECRET_KEY
			? [
					captcha({
						provider: "cloudflare-turnstile",
						secretKey: process.env.CAPTCHA_SECRET_KEY,
						// Protect critical auth endpoints
						endpoints: ["/sign-up/email", "/sign-in/email", "/forget-password", "/password-reset"],
					}),
				]
			: []),
 
		// ✅ ENTERPRISE: Multi-Session Plugin (Device Management)
		// Allows users to manage active sessions across devices
		// Requires: ENABLE_MULTI_SESSION=true
		...(ENABLE_MULTI_SESSION
			? [
					multiSession({
						// Enterprise limit: 10 concurrent sessions
						maximumSessions: 10,
					}),
				]
			: []),
	],
	onAPIError: {
		onError(error: unknown, ctx: unknown) {
			// Enhanced error logging with OAuth-specific context
			const errorDetails: Record<string, unknown> = {
				error,
				context: ctx,
			};
 
			// Extract additional context from error object
			if (error && typeof error === "object") {
				if ("code" in error) {
					errorDetails.errorCode = error.code;
				}
				if ("message" in error) {
					errorDetails.errorMessage = error.message;
				}
				if ("statusCode" in error) {
					errorDetails.statusCode = error.statusCode;
				}
			}
 
			// Extract context information (e.g., request path, method)
			let isOAuthError = false;
			if (ctx && typeof ctx === "object") {
				if ("request" in ctx) {
					const request = ctx.request as { url?: string; method?: string };
					errorDetails.requestUrl = request.url;
					errorDetails.requestMethod = request.method;
 
					// Check if this is an OAuth callback error
					if (request.url?.includes("/api/auth/callback/")) {
						const provider = request.url.split("/callback/")[1]?.split("?")[0];
						errorDetails.oauthProvider = provider;
						errorDetails.errorType = "OAuth Callback Error";
						isOAuthError = true;
 
						logger.error("OAuth Callback Error", errorDetails);
					}
				}
			}
 
			// Log auth error
			if (!isOAuthError) {
				logger.error("Better Auth API Error", errorDetails);
			}
 
			// Track failed auth in PostHog (non-blocking)
			trackEvent("auth.signin_failed", {
				errorCode: errorDetails.errorCode as string | undefined,
				errorMessage: errorDetails.errorMessage as string | undefined,
				path: errorDetails.requestUrl as string | undefined,
				timestamp: new Date().toISOString(),
			}).catch(() => {
				// Ignore tracking errors
			});
 
			// Send to Sentry for monitoring (lazy import to avoid startup overhead)
			import("@snapback/infrastructure")
				.then(({ captureError }) => {
					if (captureError && error instanceof Error) {
						captureError(error, {
							tags: {
								errorType: isOAuthError ? "oauth_callback" : "auth_api",
								...(errorDetails.errorCode ? { errorCode: String(errorDetails.errorCode) } : {}),
							},
							extra: errorDetails,
						});
					}
				})
				.catch(() => {
					// Sentry not available, already logged
				});
		},
	},
});
 
// ============================================================================
// Plugin API Type Declarations
// ============================================================================
// Better Auth's InferAPI doesn't emit stable types for plugins, causing
// "Maximum call stack size exceeded" during builds. We define explicit types
// for the plugin APIs we use.
 
/** API Key plugin types */
export interface CreateApiKeyParams {
	body: {
		name: string;
		userId: string;
		permissions?: Record<string, string[]>;
		rateLimitEnabled?: boolean;
		rateLimitMax?: number;
		rateLimitTimeWindow?: number;
		expiresAt?: Date;
		metadata?: Record<string, unknown>;
	};
}
 
export interface CreateApiKeyResult {
	id: string;
	key: string;
	name: string;
	createdAt: Date;
}
 
/** verifyApiKey accepts key directly or in body wrapper (support both patterns) */
export interface VerifyApiKeyParams {
	key?: string;
	permissions?: Record<string, string[]>;
	body?: {
		key: string;
		permissions?: Record<string, string[]>;
	};
}
 
export interface VerifyApiKeyResult {
	valid?: boolean;
	isValid?: boolean; // Alternative property name used by some consumers
	userId?: string;
	key?: {
		id: string;
		userId: string;
		name: string;
		permissions?: Record<string, string[]>;
		rateLimitEnabled?: boolean;
		rateLimitMax?: number;
		remaining?: number;
		lastRefillAt?: Date;
		metadata?: Record<string, unknown>;
	};
	metadata?: Record<string, unknown>;
	permissions?: Record<string, string[]>;
	error?: { message: string; code?: string };
}
 
export interface DeleteApiKeyParams {
	body: { keyId: string };
}
 
/** Passkey plugin types */
export interface ListPasskeysParams {
	headers: Headers;
}
 
export interface PasskeyInfo {
	id: string;
	name: string;
	createdAt: Date;
	lastUsedAt?: Date;
}
 
export interface VerifyPasskeyAuthenticationParams {
	body: Record<string, unknown>;
}
 
export interface VerifyPasskeyAuthenticationResult {
	session?: { id: string; userId: string };
	user?: { id: string; email: string };
	verified?: boolean;
}
 
/** Two-factor plugin types */
export interface VerifyTwoFactorOTPParams {
	body: {
		code: string;
	};
}
 
export interface VerifyTwoFactorOTPResult {
	token?: string;
	user?: { id: string; email: string };
	verified?: boolean;
}
 
/** Sign-in types */
export interface SignInEmailParams {
	body: {
		email: string;
		password: string;
	};
}
 
export interface SignInEmailResult {
	user?: { id: string; email: string };
	session?: { id: string };
}
 
/** OpenAPI plugin types */
export interface OpenAPIComponents {
	schemas?: Record<string, unknown>;
	securitySchemes?: Record<string, unknown>;
	[key: string]: unknown;
}
 
export interface GenerateOpenAPISchemaResult {
	openapi: string;
	info: { title: string; version: string };
	paths: Record<string, unknown>;
	components?: OpenAPIComponents;
}
 
/** Organization types for API */
export interface OrganizationInfo {
	id: string;
	name: string;
	slug: string;
	logo?: string | null;
	metadata?: Record<string, unknown>;
	createdAt: Date;
}
 
export interface OrganizationMember {
	id: string;
	userId: string;
	organizationId: string;
	role: string;
	createdAt: Date;
}
 
export interface OrganizationInvitation {
	id: string;
	email: string;
	organizationId: string;
	role: string;
	status: string;
	expiresAt: Date;
	createdAt: Date;
}
 
export interface AccountInfo {
	id: string;
	userId: string;
	providerId: string;
	accountId: string;
	createdAt: Date;
}
 
/** Extended auth.api type with plugin methods */
export interface SnapBackAuthAPI {
	// Core methods (from base better-auth)
	getSession: (params: { headers: Headers }) => Promise<{
		session: { id: string; userId: string; expiresAt: Date } | null;
		user: {
			id: string;
			email: string;
			name: string;
			emailVerified: boolean;
			image?: string | null;
			createdAt: Date;
			updatedAt: Date;
			activeOrganization?: { id: string; name: string } | null;
		} | null;
	}>;
 
	// Sign-in method
	signInEmail: (params: SignInEmailParams) => Promise<SignInEmailResult>;
 
	// API Key plugin
	createApiKey: (params: CreateApiKeyParams) => Promise<CreateApiKeyResult>;
	verifyApiKey: (params: VerifyApiKeyParams) => Promise<VerifyApiKeyResult>;
	deleteApiKey: (params: DeleteApiKeyParams) => Promise<void>;
 
	// Passkey plugin
	listPasskeys: (params: { headers: Headers }) => Promise<PasskeyInfo[]>;
	verifyPasskeyAuthentication: (
		params: VerifyPasskeyAuthenticationParams,
	) => Promise<VerifyPasskeyAuthenticationResult>;
 
	// Two-factor plugin
	verifyTwoFactorOTP: (params: VerifyTwoFactorOTPParams) => Promise<VerifyTwoFactorOTPResult>;
 
	// OpenAPI plugin
	generateOpenAPISchema: () => Promise<GenerateOpenAPISchemaResult>;
 
	// Organization plugin methods
	getFullOrganization: (params: {
		headers: Headers;
		query: { organizationSlug?: string; organizationId?: string };
	}) => Promise<{
		id: string;
		name: string;
		slug: string;
		logo?: string | null;
		metadata?: Record<string, unknown>;
		createdAt: Date;
		members: OrganizationMember[];
		invitations: OrganizationInvitation[];
	} | null>;
 
	listOrganizations: (params: { headers: Headers }) => Promise<{
		organizations: OrganizationInfo[];
	} | null>;
 
	getInvitation: (params: {
		headers: Headers;
		query: { invitationId: string };
	}) => Promise<OrganizationInvitation | null>;
 
	// Account management
	listAccounts: (params: { headers: Headers }) => Promise<AccountInfo[]>;
}
 
/** Password context from Better Auth's internal AuthContext */
export interface SnapBackPasswordContext {
	hash: (password: string) => Promise<string>;
	verify: (args: { hash: string; password: string }) => Promise<boolean>;
}
 
/** Minimal AuthContext type for $context access */
export interface SnapBackAuthContext {
	password: SnapBackPasswordContext;
}
 
/** Auth instance type with plugin APIs */
export interface SnapBackAuthInstance {
	api: SnapBackAuthAPI;
	handler: (request: Request) => Promise<Response>;
	/** Internal Better Auth context - use for password hashing in scripts */
	$context: Promise<SnapBackAuthContext>;
}
 
/** Typed auth export with plugin APIs - cast to avoid complex type inference */
export const auth = _auth as unknown as SnapBackAuthInstance;
 
export * from "./lib/organization";
 
// Type exports moved to appropriate locations:
// - Session: Use 'better-auth/types' or '@snapback/contracts/auth/session'
// - Organization types: Use Better Auth organization plugin types
// Removed dangerous 'any' stub exports (audit finding #1)