Files
pn-new-crm/src/app/api/v1/me/email/route.ts
Matt 221ae5784e chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:

- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
  never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
  after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
  redirects (ocr to ai, reports to dashboard, invitations to users),
  docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
  flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
  let-reassign), set-state-in-effect disables in CountryFlag and
  UploadForSigning preview-bytes effect, unused 'confirm' destructures in
  interest contract + reservation tabs, unescaped apostrophe in test-template
  card copy
2026-05-23 00:52:59 +02:00

165 lines
6.3 KiB
TypeScript

import { NextResponse } from 'next/server';
import { z } from 'zod';
import { eq } from 'drizzle-orm';
import crypto from 'node:crypto';
import { withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { db } from '@/lib/db';
import { user, userEmailChanges } from '@/lib/db/schema/users';
import { createAuditLog } from '@/lib/audit';
import { ConflictError, errorResponse, ValidationError } from '@/lib/errors';
import { env } from '@/lib/env';
const updateEmailSchema = z.object({
email: z.string().email().toLowerCase(),
});
const VERIFY_TOKEN_TTL_MINUTES = 60;
const REQUIRES_VERIFICATION = process.env.EMAIL_CHANGE_INSTANT !== 'true';
/**
* Initiate an email-change for the signed-in user.
*
* Production flow (REQUIRES_VERIFICATION=true, default):
* 1. Create a user_email_changes row with sha256(token)
* 2. Email OLD address with a cancel link
* 3. Email NEW address with a confirm link
* 4. Change applies only when /api/v1/me/email/confirm/<token> is called
*
* Dev shortcut (set EMAIL_CHANGE_INSTANT=true):
* - Updates user.email immediately, skipping the email round-trip.
* - Useful for local testing where SMTP isn't wired.
*/
export const PATCH = withAuth(async (req, ctx) => {
try {
const { email } = await parseBody(req, updateEmailSchema);
if (email === ctx.user.email) {
return NextResponse.json({ ok: true, unchanged: true });
}
// Reject if another account already owns this address.
const conflict = await db.query.user.findFirst({ where: eq(user.email, email) });
if (conflict && conflict.id !== ctx.userId) {
throw new ConflictError('That email is already in use by another account');
}
if (!REQUIRES_VERIFICATION) {
// Instant change - dev only.
const [updated] = await db
.update(user)
.set({ email, emailVerified: false, updatedAt: new Date() })
.where(eq(user.id, ctx.userId))
.returning({ email: user.email });
if (!updated) throw new ValidationError('Failed to update email');
void createAuditLog({
userId: ctx.userId,
portId: ctx.portId || null,
action: 'update',
entityType: 'user',
entityId: ctx.userId,
oldValue: { email: ctx.user.email },
newValue: { email: updated.email },
metadata: { type: 'email_change_instant' },
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: { email: updated.email, instant: true } });
}
// Verification flow - generate a single-use token, hash it, persist.
const rawToken = crypto.randomBytes(32).toString('base64url');
const tokenHash = crypto.createHash('sha256').update(rawToken).digest('hex');
const expiresAt = new Date(Date.now() + VERIFY_TOKEN_TTL_MINUTES * 60 * 1000);
const [pending] = await db
.insert(userEmailChanges)
.values({
userId: ctx.userId,
oldEmail: ctx.user.email,
newEmail: email,
confirmTokenHash: tokenHash,
expiresAt,
})
.returning();
if (!pending) throw new ValidationError('Failed to create pending email-change row');
const baseUrl = env.APP_URL.replace(/\/+$/, '');
const confirmUrl = `${baseUrl}/api/v1/me/email/confirm/${rawToken}`;
const cancelUrl = `${baseUrl}/api/v1/me/email/cancel/${rawToken}`;
try {
const [{ sendEmail }, { renderShell, safeUrl }, { resolveAuthShellBranding }] =
await Promise.all([
import('@/lib/email'),
import('@/lib/email/shell'),
import('@/lib/email/auth-shell-branding'),
]);
const branding = await resolveAuthShellBranding();
const appName = branding?.appName?.trim() || 'CRM';
const brandingShell = branding
? {
logoUrl: branding.logoUrl,
backgroundUrl: branding.backgroundUrl,
primaryColor: null,
emailHeaderHtml: null,
emailFooterHtml: null,
}
: null;
const safeOldEmail = ctx.user.email.replace(/[<>&]/g, '');
const safeNewEmail = email.replace(/[<>&]/g, '');
const confirmBody = `
<p style="margin-bottom:16px;">Hi,</p>
<p style="margin-bottom:16px;">You (or someone using your account) requested to change the sign-in email on your ${appName} account from <strong>${safeOldEmail}</strong> to <strong>${safeNewEmail}</strong>.</p>
<p style="margin-bottom:16px;"><a href="${safeUrl(confirmUrl)}" style="color:#2563eb;font-weight:600;">Click here to confirm this change</a> - the link expires in ${VERIFY_TOKEN_TTL_MINUTES} minutes.</p>
<p style="color:#64748b;">If you didn't request this, ignore this email.</p>
`;
const cancelBody = `
<p style="margin-bottom:16px;">Hi,</p>
<p style="margin-bottom:16px;">A change to your sign-in email was requested. If this wasn't you, <a href="${safeUrl(cancelUrl)}" style="color:#2563eb;font-weight:600;">click here to cancel the change</a> immediately and consider rotating your password.</p>
`;
const confirmSubject = `Confirm your new ${appName} email address`;
const noticeSubject = `A change to your ${appName} email was requested`;
await Promise.allSettled([
sendEmail(
email,
confirmSubject,
renderShell({ title: confirmSubject, body: confirmBody, branding: brandingShell }),
undefined,
`Confirm new email: ${confirmUrl}`,
),
sendEmail(
ctx.user.email,
noticeSubject,
renderShell({ title: noticeSubject, body: cancelBody, branding: brandingShell }),
undefined,
`Cancel email change: ${cancelUrl}`,
),
]);
} catch {
// Email send is best-effort; the row stays so the user can re-request.
}
void createAuditLog({
userId: ctx.userId,
portId: ctx.portId || null,
action: 'create',
entityType: 'user_email_change',
entityId: pending.id,
newValue: { newEmail: email },
metadata: { type: 'email_change_requested' },
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({
data: {
pendingChangeId: pending.id,
verificationSentTo: email,
},
});
} catch (error) {
return errorResponse(error);
}
});