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 | 9x 9x 9x 8x 5x 3x 2x 1x 1x 1x 1x 45x 2x 43x 43x 43x 13x 43x 32x 45x 2x 2x 2x 2x 2x 2x 2x 1x 9x 9x 1x 8x 8x 8x 8x 1x 7x 7x 7x 7x 1x 3x 3x 3x 3x 3x 1x 2x 2x 2x 2x 2x 1x 5x 5x 5x 3x 3x 5x 5x 5x 1x 5x 3x 45x 45x 45x 41x 41x 41x | import { betterAuth } from "better-auth";
// APIError and createAuthMiddleware available from "better-auth/api" if needed
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { phoneNumber, magicLink } from "better-auth/plugins";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import { createEmailService } from "./email";
import { hashPassword, verifyPassword } from "./password";
import { getOAuthClientIds } from "./env-config";
import { phoneToTempEmailLocalPart } from "./auth-helpers";
// Transform API URLs to portal URLs for email links
function transformToPortalUrl(apiUrl: string, portalOrigin: string): string {
const url = new URL(apiUrl);
const token = url.searchParams.get("token");
if (!token) return apiUrl;
// Determine the portal path based on the API path
if (url.pathname.includes("verify-email")) {
return `${portalOrigin}/verify-email?token=${encodeURIComponent(token)}`;
}
if (url.pathname.includes("reset-password")) {
return `${portalOrigin}/reset-password?token=${encodeURIComponent(token)}`;
}
return apiUrl;
}
// Module-level cache for auth instance and email service.
// On Cloudflare Workers, env bindings are passed per-request and the env object
// may differ between requests even within the same isolate. Keying by the
// BETTER_AUTH_SECRET string value (instead of object identity) is more reliable
// since the secret stays the same across requests.
let _cachedAuth: ReturnType<typeof betterAuth> | null = null;
let _cachedEmailService: ReturnType<typeof createEmailService> | null = null;
let _cachedEnvSecret: string | null = null;
export function createAuth(
db: DrizzleD1Database<typeof schema>,
env: CloudflareBindings,
) {
// Return cached auth instance if the secret matches (same environment)
if (_cachedAuth && _cachedEnvSecret === env.BETTER_AUTH_SECRET) {
return _cachedAuth;
}
// Cache email service separately — only recreate when secret changes
/* v8 ignore start -- V8 artifact: second condition always true on first call */
if (!_cachedEmailService || _cachedEnvSecret !== env.BETTER_AUTH_SECRET) {
/* v8 ignore stop */
_cachedEmailService = createEmailService(env);
}
// Build trusted origins list from environment or use defaults
const trustedOrigins: string[] = [];
if (env.ALLOWED_ORIGINS) {
trustedOrigins.push(...env.ALLOWED_ORIGINS.split(",").map((o) => o.trim()));
}
// Always allow localhost origins in development
if (!env.ALLOWED_ORIGINS || env.ALLOWED_ORIGINS === "") {
trustedOrigins.push(
env.PORTAL_URL || "http://localhost:7002",
env.API_URL || env.BETTER_AUTH_URL || "http://localhost:7001",
);
}
// Get the portal origin for email links (verify-email, reset-password)
// The final "http://localhost:7002" fallback is defensive — trustedOrigins[0]
// is always set when ALLOWED_ORIGINS is unset (localhost is added above).
/* v8 ignore start -- V8 artifact: || fallback never reached */
const portalOrigin =
env.PORTAL_URL || trustedOrigins[0] || "http://localhost:7002";
/* v8 ignore stop */
const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "sqlite",
schema: {
user: schema.users,
session: schema.sessions,
account: schema.accounts,
verification: schema.verifications,
},
}),
user: {
changeEmail: {
enabled: true,
// Phone-signup users have emailVerified=false, so they can set email directly
updateEmailWithoutVerification: true,
// Verified email users must confirm the change via the new email.
// Renamed from sendChangeEmailVerification in better-auth 1.6.
sendChangeEmailConfirmation: async ({
user,
newEmail,
url,
}: {
user: { email: string; name: string };
newEmail: string;
url: string;
token: string;
}) => {
try {
const verificationUrl = transformToPortalUrl(url, portalOrigin);
const { CommunicationGateway } = await import("./communication/gateway");
const { createDal } = await import("../dal");
const dal = createDal(db);
const gateway = new CommunicationGateway(dal, env);
await gateway.send({
channel: "email",
recipient: newEmail,
eventType: "email_verification",
transactional: true,
content: {
template: "email-verification",
subject: "Verify your new email for Interioring",
props: { verificationLink: verificationUrl, userName: user.name },
},
});
} catch (err) {
console.error("[AUTH] Failed to send change-email verification:", err);
}
},
},
additionalFields: {
termsAcceptedAt: {
type: "number",
returned: true,
required: false,
input: false,
},
termsVersion: {
type: "string",
returned: true,
required: false,
input: false,
},
},
},
secret: env.BETTER_AUTH_SECRET,
baseURL: env.BETTER_AUTH_URL,
trustedOrigins,
// Auto-link social accounts when the email matches an existing user
// (e.g., user registered with email, then clicks "Sign in with Google" using same email)
account: {
accountLinking: {
enabled: true,
trustedProviders: ["google", "facebook"],
},
// State cookie maxAge is hardcoded to 5min in Better Auth 1.6.9
// (state.mjs:47), while the DB verification row lives 10min
// (oauth2/state.mjs:17). Slow OAuth completion → cookie expires
// → user lands on `?error=state_mismatch`. The DB row alone
// (32-char crypto random identifier, single-use, deleted after
// first callback) plus PKCE is sufficient to validate the flow.
skipStateCookieCheck: true,
},
emailAndPassword: {
enabled: true,
// Require email verification before allowing login
requireEmailVerification: true,
// Password requirements
minPasswordLength: 8,
// Use PBKDF2 via Web Crypto instead of default scrypt.
// Default scrypt (N=16384, r=16) uses ~64MB and >3s CPU on Workers
// cold starts, causing 503 errors. PBKDF2 is native and <50ms.
// Legacy scrypt hashes are still verified for backward compatibility.
password: {
hash: hashPassword,
verify: verifyPassword,
},
// Custom password reset email
sendResetPassword: async ({ user, url }) => {
const portalUrl = transformToPortalUrl(url, portalOrigin);
try {
const { CommunicationGateway } = await import("./communication/gateway");
const { createDal } = await import("../dal");
const dal = createDal(db);
const gateway = new CommunicationGateway(dal, env);
await gateway.send({
channel: "email",
recipient: user.email,
eventType: "password_reset",
transactional: true,
content: {
template: "password-reset",
subject: "Reset your Interioring password",
props: { resetLink: portalUrl, userName: user.name },
},
});
} catch (err) {
console.error("[AUTH] Failed to send password reset email:", err);
}
},
},
// Email verification configuration
emailVerification: {
sendVerificationEmail: async ({ user, url }) => {
try {
// Skip for phone-signup placeholder emails (not real addresses)
if (user.email.endsWith("@phone.interioring.com")) {
return;
}
// Skip verification email for invited users — they'll be
// auto-verified via the invitation token flow
const { createDal } = await import("../dal");
const dal = createDal(db);
const pendingInvitation =
await dal.teamInvitations.findPendingByEmailGlobal(user.email);
if (pendingInvitation) {
return;
}
const portalUrl = transformToPortalUrl(url, portalOrigin);
const { CommunicationGateway } = await import("./communication/gateway");
const gateway = new CommunicationGateway(dal, env);
await gateway.send({
channel: "email",
recipient: user.email,
eventType: "email_verification",
transactional: true,
content: {
template: "email-verification",
subject: "Verify your Interioring email",
props: { verificationLink: portalUrl, userName: user.name },
},
});
} catch (err) {
console.error("[AUTH] Failed to send verification email:", err);
}
},
sendOnSignUp: true,
autoSignInAfterVerification: true,
afterEmailVerification: async (user: { email: string; name: string }) => {
try {
const { createDal } = await import("../dal");
const dal = createDal(db);
// Skip onboarding email for invited users — they're joining
// an existing team, not starting their own onboarding
const pendingInvitation =
await dal.teamInvitations.findPendingByEmailGlobal(user.email);
if (pendingInvitation) {
return;
}
const { CommunicationGateway } = await import("./communication/gateway");
const { EmailVerifiedHandler } = await import(
"./communication/handlers/email-verified.handler"
);
const gateway = new CommunicationGateway(dal, env);
const handler = new EmailVerifiedHandler(gateway);
await handler.handle({
email: user.email,
userName: user.name,
onboardingUrl: `${portalOrigin}/onboarding`,
});
} catch (err) {
console.error("[AUTH] Failed to send email-verified notification:", err);
}
},
},
session: {
// Session expires in 7 days
expiresIn: 60 * 60 * 24 * 7,
// Update session expiry on activity
updateAge: 60 * 60 * 24,
},
socialProviders: {
...(env.GOOGLE_CLIENT_SECRET
? {
google: {
clientId: getOAuthClientIds().google,
clientSecret: env.GOOGLE_CLIENT_SECRET,
prompt: "select_account",
},
}
: {}),
...(env.FACEBOOK_APP_SECRET
? {
facebook: {
clientId: getOAuthClientIds().facebook,
clientSecret: env.FACEBOOK_APP_SECRET,
},
}
: {}),
},
plugins: [
phoneNumber({
sendOTP: async ({ phoneNumber: phone, code }, _request) => {
// WhatsApp delivery via adapter — applies safety guards in non-prod
const { sendWhatsAppOtp } = await import("./communication/whatsapp-otp");
let deliveryErr: unknown;
let deliveryResult: { actualRecipient: string; provider: string } | undefined;
try {
deliveryResult = await sendWhatsAppOtp(env, phone, code);
} catch (err) {
deliveryErr = err;
console.error("[AUTH] WhatsApp OTP failed:", err);
}
// Log delivery outcome (success or failure)
try {
const { communicationLog } = await import("../db/schema/notifications");
await db.insert(communicationLog).values({
channel: "whatsapp",
recipient: phone,
actualRecipient: deliveryResult?.actualRecipient ?? phone,
eventType: "otp_verification",
status: deliveryErr ? "failed" : "sent",
provider: deliveryResult?.provider ?? "whatsapp_cloud_api",
environment: env.ENVIRONMENT ?? "local",
transactional: true,
contentSummary: JSON.stringify({ codeLength: code.length }),
previewText: `Your verification code is ${code}`,
errorMessage: deliveryErr instanceof Error ? deliveryErr.message : deliveryErr ? "WhatsApp OTP delivery failed" : undefined,
});
} catch (logErr) {
console.error("[AUTH] OTP log failed:", logErr);
}
// Re-throw so better-auth returns an error response to the client
if (deliveryErr) {
throw deliveryErr;
}
},
signUpOnVerification: {
getTempEmail: (phone: string) =>
`${phoneToTempEmailLocalPart(phone)}@phone.interioring.com`,
getTempName: (_phone: string) => "New User",
},
otpLength: 6,
expiresIn: 300,
}),
magicLink({
expiresIn: 300, // 5 minutes
sendMagicLink: async ({ email, url }) => {
// No try-catch — let errors propagate so better-auth returns an error response
const { CommunicationGateway } = await import("./communication/gateway");
const { createDal } = await import("../dal");
const dal = createDal(db);
const gateway = new CommunicationGateway(dal, env);
await gateway.send({
channel: "email",
recipient: email,
eventType: "magic_link",
transactional: true,
content: {
template: "magic-link",
subject: "Sign in to Interioring",
props: { magicLinkUrl: url },
},
});
},
}),
],
// Terms acceptance is handled post-signup via TermsGuard + AcceptTermsPage.
// New users are NOT auto-stamped — they must explicitly accept terms
// before accessing any protected pages (onboarding, dashboard, etc.).
// This works consistently for email, phone OTP, magic link, and social sign-up.
// Relax rate limits in local/dev to prevent E2E test timeouts.
// Production uses default (stricter) limits.
rateLimit:
!env.ENVIRONMENT || env.ENVIRONMENT === "local" || env.ENVIRONMENT === "dev"
? { window: 10, max: 200 }
: undefined,
});
// Widen narrow Auth<{...exact options}> to Auth<BetterAuthOptions>.
// Better-auth's Auth<O> is invariant in O — going via unknown is required
// because the precise option-literal type doesn't structurally overlap
// the generic constraint after better-auth 1.6's tightened typings.
_cachedAuth = auth as unknown as ReturnType<typeof betterAuth>;
_cachedEnvSecret = env.BETTER_AUTH_SECRET;
return _cachedAuth;
}
/**
* Reset the module-level auth cache. Used in tests to ensure clean state
* between test cases.
*/
export function _resetAuthCache(): void {
_cachedAuth = null;
_cachedEmailService = null;
_cachedEnvSecret = null;
}
export type Auth = ReturnType<typeof createAuth>;
|