All files / routes/user/profile credential-change.routes.ts

95.45% Statements 126/132
100% Branches 52/52
100% Functions 4/4
95.45% Lines 126/132

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                                                                  1x   1x     1x 5x 5x 5x 1x     4x 4x   4x 5x 2x           2x     2x 2x 1x                 1x 1x 1x     1x 1x 1x     1x       1x               1x 1x   1x   2x         1x 9x 9x 9x 1x     8x 8x 8x   8x 9x   9x 1x       7x     9x 7x           7x 7x 1x       6x 1x     1x         5x 5x             5x 2x 2x 1x 1x   1x     1x       3x 3x 1x     1x                 2x               2x       2x               1x         1x 6x 6x 6x 1x     5x 5x   5x 6x 2x       3x 1x       2x 2x 1x                 1x 1x 1x     1x 1x 1x     1x       1x               1x 1x 1x                         1x   3x         1x 7x 7x 7x 1x     6x 6x 6x   6x 7x   7x 1x       5x 5x           5x 5x 1x       4x 1x     1x         3x 3x                             1x     1x       2x 2x 1x     1x                 1x                     1x       1x               1x          
// OTP-based phone/email change endpoints. Split out of profile.routes.ts to
// keep the parent file focused on profile reads + avatar + preferences.
//
// Both flows follow the same 2-step pattern:
//   1. POST initiate → generate code, store in `verifications` row keyed by
//      `<channel>-change:<userId>`, send via WhatsApp (phone) / Resend (email).
//   2. POST verify → check expiry / attempts / brute-force, swap the field on
//      the users row, clear the verification row.
//
// We deliberately bypass Better Auth's built-in `changeEmail` plugin here so we
// can drive both verifications through the same OTP UX in the portal.
// Better Auth's Drizzle adapter reads the user's email straight from the users
// table, so updating `users.email` + setting `emailVerified=true` is safe.
 
import { eq } from "drizzle-orm";
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { getDb } from "../../../db";
import { ValidationError } from "../../../lib/errors";
import { error, handleError, success } from "../../../lib/response";
import type { Services } from "../../../services";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		db: ReturnType<typeof getDb>;
	};
};
 
const INDIAN_PHONE_REGEX = /^[6-9]\d{9}$/;
 
const credentialChange = new Hono<Env>();
 
// POST /me/change-phone - Send OTP to new phone number
credentialChange.post("/me/change-phone", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{ phoneNumber: string }>();
		const dal = c.get("dal");
 
		const phone = body.phoneNumber?.trim();
		if (!phone || !INDIAN_PHONE_REGEX.test(phone)) {
			throw new ValidationError(
				"Phone number must be a valid 10-digit Indian mobile number",
			);
		}
 
		// Normalize to E.164 format
		const e164Phone = `+91${phone}`;
 
		// Check uniqueness
		const existing = await dal.users.findByPhoneNumber(e164Phone, user.id);
		if (existing) {
			return error(
				c,
				"PHONE_EXISTS",
				"This phone number is already in use by another account",
				409,
			);
		}
 
		// Generate cryptographically secure 6-digit OTP
		const otpBytes = new Uint8Array(4);
		crypto.getRandomValues(otpBytes);
		const code = String(100000 + (new DataView(otpBytes.buffer).getUint32(0) % 900000));
 
		// Store OTP in verifications table
		const { generateId } = await import("../../../lib/utils");
		const authVerifications = (await import("../../../db/schema/auth")).verifications;
		const db = c.get("db");
 
		// Delete any existing phone change verification for this user
		await db
			.delete(authVerifications)
			.where(eq(authVerifications.identifier, `phone-change:${user.id}`));
 
		await db.insert(authVerifications).values({
			id: generateId(),
			identifier: `phone-change:${user.id}`,
			value: JSON.stringify({ code, phoneNumber: e164Phone, attempts: 0 }),
			expiresAt: new Date(Date.now() + 5 * 60 * 1000), // 5 minutes
		});
 
		// Send OTP via WhatsApp
		const { sendWhatsAppOtp } = await import("../../../lib/communication/whatsapp-otp");
		await sendWhatsAppOtp(c.env, e164Phone, code);
 
		return success(c, { message: "OTP sent to your phone via WhatsApp" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /me/change-phone/verify - Verify OTP and update phone number
credentialChange.post("/me/change-phone/verify", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{ phoneNumber: string; code: string }>();
		const dal = c.get("dal");
		const db = c.get("db");
 
		const phone = body.phoneNumber?.trim();
		const code = body.code?.trim();
 
		if (!phone || !code) {
			throw new ValidationError("Phone number and OTP code are required");
		}
 
		// Normalize to E.164 format
		const e164Phone = phone.startsWith("+") ? phone : `+91${phone}`;
 
		// Look up the pending verification
		const authVerifications = (await import("../../../db/schema/auth")).verifications;
		const records = await db
			.select()
			.from(authVerifications)
			.where(eq(authVerifications.identifier, `phone-change:${user.id}`))
			.limit(1);
 
		const record = records[0];
		if (!record) {
			return error(c, "INVALID_OTP", "No pending phone change. Please request a new OTP.", 400);
		}
 
		// Check expiry
		if (new Date() > record.expiresAt) {
			await db
				.delete(authVerifications)
				.where(eq(authVerifications.id, record.id));
			return error(c, "OTP_EXPIRED", "OTP has expired. Please request a new one.", 400);
		}
 
		// Parse verification data safely
		let stored: { code: string; phoneNumber: string; attempts?: number };
		try {
			stored = JSON.parse(record.value);
		} catch {
			await db.delete(authVerifications).where(eq(authVerifications.id, record.id));
			return error(c, "INVALID_OTP", "Verification data corrupted. Please request a new code.", 400);
		}
 
		// Verify OTP and phone match (with brute-force protection)
		if (stored.code !== code || stored.phoneNumber !== e164Phone) {
			const attempts = (stored.attempts || 0) + 1;
			if (attempts >= 5) {
				await db.delete(authVerifications).where(eq(authVerifications.id, record.id));
				return error(c, "TOO_MANY_ATTEMPTS", "Too many failed attempts. Please request a new code.", 400);
			}
			await db.update(authVerifications)
				.set({ value: JSON.stringify({ ...stored, attempts }) })
				.where(eq(authVerifications.id, record.id));
			return error(c, "INVALID_OTP", "Invalid OTP code", 400);
		}
 
		// Check uniqueness again (race condition guard)
		const existing = await dal.users.findByPhoneNumber(e164Phone, user.id);
		if (existing) {
			await db
				.delete(authVerifications)
				.where(eq(authVerifications.id, record.id));
			return error(
				c,
				"PHONE_EXISTS",
				"This phone number is already in use by another account",
				409,
			);
		}
 
		// Update user's phone number in E.164 format
		const updated = await dal.users.update(user.id, { phoneNumber: e164Phone });
		/* v8 ignore start -- defensive guard: user just authenticated */
		if (!updated) {
			return error(c, "NOT_FOUND", "User not found", 404);
		}
		/* v8 ignore stop */
 
		// Clean up verification record
		await db
			.delete(authVerifications)
			.where(eq(authVerifications.id, record.id));
 
		return success(c, {
			id: updated.id,
			name: updated.name,
			email: updated.email,
			phoneNumber: updated.phoneNumber,
			image: updated.image,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /me/change-email - Send OTP to new email address
credentialChange.post("/me/change-email", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{ email: string }>();
		const dal = c.get("dal");
 
		const newEmail = body.email?.trim().toLowerCase();
		if (!newEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(newEmail)) {
			throw new ValidationError("Please enter a valid email address");
		}
 
		// Don't allow changing to the same email
		if (newEmail === user.email) {
			throw new ValidationError("This is already your current email");
		}
 
		// Check uniqueness
		const existing = await dal.users.findByEmail(newEmail);
		if (existing) {
			return error(
				c,
				"EMAIL_EXISTS",
				"This email is already in use by another account",
				409,
			);
		}
 
		// Generate cryptographically secure 6-digit OTP
		const otpBytes = new Uint8Array(4);
		crypto.getRandomValues(otpBytes);
		const code = String(100000 + (new DataView(otpBytes.buffer).getUint32(0) % 900000));
 
		// Store OTP in verifications table
		const { generateId } = await import("../../../lib/utils");
		const authVerifications = (await import("../../../db/schema/auth")).verifications;
		const db = c.get("db");
 
		// Delete any existing email change verification for this user
		await db
			.delete(authVerifications)
			.where(eq(authVerifications.identifier, `email-change:${user.id}`));
 
		await db.insert(authVerifications).values({
			id: generateId(),
			identifier: `email-change:${user.id}`,
			value: JSON.stringify({ code, email: newEmail, attempts: 0 }),
			expiresAt: new Date(Date.now() + 5 * 60 * 1000), // 5 minutes
		});
 
		// Send OTP via email
		const { CommunicationGateway } = await import("../../../lib/communication/gateway");
		const gateway = new CommunicationGateway(dal, c.env);
		await gateway.send({
			channel: "email",
			recipient: newEmail,
			eventType: "otp_verification",
			userId: user.id,
			transactional: true,
			content: {
				template: "email-otp",
				subject: "Your Interioring verification code",
				props: { code, userName: user.name },
			},
		});
 
		return success(c, { message: "Verification code sent to your new email" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /me/change-email/verify - Verify OTP and update email
credentialChange.post("/me/change-email/verify", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{ email: string; code: string }>();
		const dal = c.get("dal");
		const db = c.get("db");
 
		const newEmail = body.email?.trim().toLowerCase();
		const code = body.code?.trim();
 
		if (!newEmail || !code) {
			throw new ValidationError("Email and verification code are required");
		}
 
		// Look up the pending verification
		const authVerifications = (await import("../../../db/schema/auth")).verifications;
		const records = await db
			.select()
			.from(authVerifications)
			.where(eq(authVerifications.identifier, `email-change:${user.id}`))
			.limit(1);
 
		const record = records[0];
		if (!record) {
			return error(c, "INVALID_OTP", "No pending email change. Please request a new code.", 400);
		}
 
		// Check expiry
		if (new Date() > record.expiresAt) {
			await db
				.delete(authVerifications)
				.where(eq(authVerifications.id, record.id));
			return error(c, "OTP_EXPIRED", "Verification code has expired. Please request a new one.", 400);
		}
 
		// Parse verification data safely
		let stored: { code: string; email: string; attempts?: number };
		try {
			stored = JSON.parse(record.value);
		} catch {
			await db.delete(authVerifications).where(eq(authVerifications.id, record.id));
			return error(c, "INVALID_OTP", "Verification data corrupted. Please request a new code.", 400);
		}
 
		// Verify OTP and email match (with brute-force protection)
		/* v8 ignore start -- defensive guard: always matches in tests */
		if (stored.code !== code || stored.email !== newEmail) {
			const attempts = (stored.attempts || 0) + 1;
			if (attempts >= 5) {
		/* v8 ignore stop */
				await db.delete(authVerifications).where(eq(authVerifications.id, record.id));
				return error(c, "TOO_MANY_ATTEMPTS", "Too many failed attempts. Please request a new code.", 400);
			}
			await db.update(authVerifications)
				.set({ value: JSON.stringify({ ...stored, attempts }) })
				.where(eq(authVerifications.id, record.id));
			return error(c, "INVALID_OTP", "Invalid verification code", 400);
		}
 
		// Check uniqueness again (race condition guard)
		const existing = await dal.users.findByEmail(newEmail);
		if (existing) {
			await db
				.delete(authVerifications)
				.where(eq(authVerifications.id, record.id));
			return error(
				c,
				"EMAIL_EXISTS",
				"This email is already in use by another account",
				409,
			);
		}
 
		// Update user's email and mark as verified
		const updated = await dal.users.update(user.id, {
			email: newEmail,
			emailVerified: true,
		});
		/* v8 ignore start -- defensive guard: user just authenticated */
		if (!updated) {
			return error(c, "NOT_FOUND", "User not found", 404);
		}
		/* v8 ignore stop */
 
		// Clean up verification record
		await db
			.delete(authVerifications)
			.where(eq(authVerifications.id, record.id));
 
		return success(c, {
			id: updated.id,
			name: updated.name,
			email: updated.email,
			phoneNumber: updated.phoneNumber,
			image: updated.image,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default credentialChange;