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 | 17x 16x 17x 6x 6x 6x 1x 5x 5x 5x 5x 6x 1x 4x 2x 2x 1x 3x 3x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 17x 10x 10x 10x 1x 9x 9x 9x 9x 10x 10x 1x 8x 8x 8x 8x 1x 7x 1x 1x 6x 6x 1x 1x 5x 2x 2x 1x 1x 1x 1x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 2x 1x | // OTP-based email change for homeowner accounts. Mirrors the pro portal's
// apps/api/src/routes/user/profile/credential-change.routes.ts change-email
// pair — same 2-step OTP UX, same brute-force/expiry handling — adapted to
// the ho_* tables (homeowners have no equivalent change-phone flow: their
// phone is already verified via WhatsApp OTP at signup).
//
// See issue #930: phone-signup homeowners are auto-issued an undeliverable
// placeholder email (`{phone}@phone.homeowner.interioring.com`) and, until
// this route existed, had no way to replace it with a real, verifiable one.
import { eq } from "drizzle-orm";
import { Hono } from "hono";
import { createDal } from "../../../dal";
import { getDb } from "../../../db";
import { ValidationError } from "../../../lib/errors";
import { error, handleError, success } from "../../../lib/response";
type HoUser = { id: string; name: string; email: string };
type Variables = { hoUser: HoUser | null };
const credentialChange = new Hono<{
Bindings: CloudflareBindings;
Variables: Variables;
}>();
function getUser(c: { get(key: "hoUser"): HoUser | null }): HoUser | null {
return c.get("hoUser");
}
// POST /me/change-email - Send OTP to new email address
credentialChange.post("/me/change-email", async (c) => {
try {
const user = getUser(c);
if (!user) {
return error(c, "UNAUTHORIZED", "Authentication required", 401);
}
const body = await c.req.json<{ email: string }>();
const db = getDb(c.env.DB);
const dal = createDal(db);
const newEmail = body.email?.trim().toLowerCase();
if (!newEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(newEmail)) {
throw new ValidationError("Please enter a valid email address");
}
if (newEmail === user.email.toLowerCase()) {
// Legacy accounts pre-dating phone-only auth can have a real email
// that was never verified (Better Auth's link-based verification
// flow was removed). Allow re-sending an OTP to the SAME address
// in that case instead of trapping them behind "already your
// current email" with no way to complete verification.
const account = await dal.hoUsers.findById(user.id);
if (account?.emailVerified) {
throw new ValidationError("This is already your current email");
}
}
const existing = await dal.hoUsers.findByEmail(newEmail);
if (existing && existing.id !== user.id) {
return error(
c,
"EMAIL_EXISTS",
"This email is already in use by another account",
409,
);
}
const otpBytes = new Uint8Array(4);
crypto.getRandomValues(otpBytes);
const code = String(
100000 + (new DataView(otpBytes.buffer).getUint32(0) % 900000),
);
const { generateId } = await import("../../../lib/utils");
const { hoVerifications } = await import("../../../db/schema/homeowner");
await db
.delete(hoVerifications)
.where(eq(hoVerifications.identifier, `email-change:${user.id}`));
await db.insert(hoVerifications).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
});
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 = getUser(c);
if (!user) {
return error(c, "UNAUTHORIZED", "Authentication required", 401);
}
const body = await c.req.json<{ email: string; code: string }>();
const db = getDb(c.env.DB);
const dal = createDal(db);
const newEmail = body.email?.trim().toLowerCase();
const code = body.code?.trim();
if (!newEmail || !code) {
throw new ValidationError("Email and verification code are required");
}
const { hoVerifications } = await import("../../../db/schema/homeowner");
const records = await db
.select()
.from(hoVerifications)
.where(eq(hoVerifications.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,
);
}
if (new Date() > record.expiresAt) {
await db.delete(hoVerifications).where(eq(hoVerifications.id, record.id));
return error(
c,
"OTP_EXPIRED",
"Verification code has expired. Please request a new one.",
400,
);
}
let stored: { code: string; email: string; attempts?: number };
try {
stored = JSON.parse(record.value);
} catch {
await db.delete(hoVerifications).where(eq(hoVerifications.id, record.id));
return error(
c,
"INVALID_OTP",
"Verification data corrupted. Please request a new code.",
400,
);
}
if (stored.code !== code || stored.email !== newEmail) {
const attempts = (stored.attempts || 0) + 1;
if (attempts >= 5) {
await db
.delete(hoVerifications)
.where(eq(hoVerifications.id, record.id));
return error(
c,
"TOO_MANY_ATTEMPTS",
"Too many failed attempts. Please request a new code.",
400,
);
}
await db
.update(hoVerifications)
.set({ value: JSON.stringify({ ...stored, attempts }) })
.where(eq(hoVerifications.id, record.id));
return error(c, "INVALID_OTP", "Invalid verification code", 400);
}
const existing = await dal.hoUsers.findByEmail(newEmail);
if (existing && existing.id !== user.id) {
await db.delete(hoVerifications).where(eq(hoVerifications.id, record.id));
return error(
c,
"EMAIL_EXISTS",
"This email is already in use by another account",
409,
);
}
const updated = await dal.hoUsers.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 */
await db.delete(hoVerifications).where(eq(hoVerifications.id, record.id));
// Drop the cached session so the next request rebuilds it with the new
// email/emailVerified instead of serving the stale placeholder. Uses
// refreshHoSessionCache (cache-only), NOT invalidateHoSession — the
// latter also blocklists the token and would sign the user out of
// their own still-valid session immediately after they verify.
try {
const { refreshHoSessionCache } = await import(
"../../../lib/ho-session-cache"
);
const { createDualCache } = await import("../../../lib/cache");
await refreshHoSessionCache(
createDualCache(c.env.KV_CACHE),
c.req.raw.headers,
);
} catch (err) {
const { logger } = await import("../../../lib/logger");
logger.error("[HO-CREDENTIAL-CHANGE] session invalidation failed:", err);
}
return success(c, {
id: updated.id,
name: updated.name,
email: updated.email,
emailVerified: updated.emailVerified,
});
} catch (err) {
return handleError(c, err);
}
});
export default credentialChange;
|