287 lines
12 KiB
TypeScript
287 lines
12 KiB
TypeScript
|
|
import { and, eq, gt, isNull } from 'drizzle-orm';
|
||
|
|
|
||
|
|
import { db } from '@/lib/db';
|
||
|
|
import { clients } from '@/lib/db/schema/clients';
|
||
|
|
import { ports } from '@/lib/db/schema/ports';
|
||
|
|
import { portalAuthTokens, portalUsers } from '@/lib/db/schema/portal';
|
||
|
|
import { env } from '@/lib/env';
|
||
|
|
import { sendEmail } from '@/lib/email';
|
||
|
|
import { ConflictError, NotFoundError, UnauthorizedError, ValidationError } from '@/lib/errors';
|
||
|
|
import { logger } from '@/lib/logger';
|
||
|
|
import { createPortalToken } from '@/lib/portal/auth';
|
||
|
|
import { hashPassword, hashToken, mintToken, verifyPassword } from '@/lib/portal/passwords';
|
||
|
|
|
||
|
|
const ACTIVATION_TOKEN_TTL_HOURS = 72;
|
||
|
|
const RESET_TOKEN_TTL_MINUTES = 30;
|
||
|
|
const MIN_PASSWORD_LENGTH = 12;
|
||
|
|
|
||
|
|
// ─── Admin-side: invite a client to the portal ───────────────────────────────
|
||
|
|
|
||
|
|
export async function createPortalUser(args: {
|
||
|
|
clientId: string;
|
||
|
|
portId: string;
|
||
|
|
email: string;
|
||
|
|
name?: string;
|
||
|
|
createdBy: string;
|
||
|
|
}): Promise<{ portalUserId: string }> {
|
||
|
|
const normalizedEmail = args.email.toLowerCase().trim();
|
||
|
|
|
||
|
|
const client = await db.query.clients.findFirst({
|
||
|
|
where: and(eq(clients.id, args.clientId), eq(clients.portId, args.portId)),
|
||
|
|
});
|
||
|
|
if (!client) throw new NotFoundError('Client');
|
||
|
|
|
||
|
|
// Email uniqueness check is enforced at the DB level too, but we do a
|
||
|
|
// friendlier preflight so the admin sees a clear conflict error.
|
||
|
|
const existing = await db.query.portalUsers.findFirst({
|
||
|
|
where: eq(portalUsers.email, normalizedEmail),
|
||
|
|
});
|
||
|
|
if (existing) {
|
||
|
|
throw new ConflictError(`A portal user already exists for ${normalizedEmail}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
const [user] = await db
|
||
|
|
.insert(portalUsers)
|
||
|
|
.values({
|
||
|
|
portId: args.portId,
|
||
|
|
clientId: args.clientId,
|
||
|
|
email: normalizedEmail,
|
||
|
|
name: args.name ?? client.fullName,
|
||
|
|
createdBy: args.createdBy,
|
||
|
|
})
|
||
|
|
.returning({ id: portalUsers.id });
|
||
|
|
|
||
|
|
if (!user) {
|
||
|
|
throw new Error('Failed to create portal user');
|
||
|
|
}
|
||
|
|
|
||
|
|
await issueActivationToken(user.id, normalizedEmail, args.portId);
|
||
|
|
|
||
|
|
return { portalUserId: user.id };
|
||
|
|
}
|
||
|
|
|
||
|
|
async function issueActivationToken(
|
||
|
|
portalUserId: string,
|
||
|
|
email: string,
|
||
|
|
portId: string,
|
||
|
|
): Promise<void> {
|
||
|
|
const { raw, hash } = mintToken();
|
||
|
|
const expiresAt = new Date(Date.now() + ACTIVATION_TOKEN_TTL_HOURS * 3600 * 1000);
|
||
|
|
|
||
|
|
await db.insert(portalAuthTokens).values({
|
||
|
|
portalUserId,
|
||
|
|
tokenHash: hash,
|
||
|
|
type: 'activation',
|
||
|
|
expiresAt,
|
||
|
|
});
|
||
|
|
|
||
|
|
const port = await db.query.ports.findFirst({ where: eq(ports.id, portId) });
|
||
|
|
const portName = port?.name ?? 'Port Nimara';
|
||
|
|
|
||
|
|
const link = `${env.APP_URL}/portal/activate?token=${encodeURIComponent(raw)}`;
|
||
|
|
const subject = `Activate your ${portName} client portal account`;
|
||
|
|
const html = activationEmailHtml({ portName, link, ttlHours: ACTIVATION_TOKEN_TTL_HOURS });
|
||
|
|
|
||
|
|
try {
|
||
|
|
await sendEmail(email, subject, html);
|
||
|
|
} catch (err) {
|
||
|
|
logger.error({ err, email }, 'Failed to send portal activation email');
|
||
|
|
// Re-throw — the admin should know if their invite mail bounced.
|
||
|
|
throw err;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function resendActivation(portalUserId: string, portId: string): Promise<void> {
|
||
|
|
const user = await db.query.portalUsers.findFirst({
|
||
|
|
where: and(eq(portalUsers.id, portalUserId), eq(portalUsers.portId, portId)),
|
||
|
|
});
|
||
|
|
if (!user) throw new NotFoundError('Portal user');
|
||
|
|
if (user.passwordHash) {
|
||
|
|
throw new ConflictError('Portal user has already activated their account');
|
||
|
|
}
|
||
|
|
await issueActivationToken(user.id, user.email, user.portId);
|
||
|
|
}
|
||
|
|
|
||
|
|
// ─── Activation: client sets their initial password ──────────────────────────
|
||
|
|
|
||
|
|
export async function activateAccount(rawToken: string, password: string): Promise<void> {
|
||
|
|
if (password.length < MIN_PASSWORD_LENGTH) {
|
||
|
|
throw new ValidationError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`);
|
||
|
|
}
|
||
|
|
const tokenRow = await consumeToken(rawToken, 'activation');
|
||
|
|
const passwordHash = await hashPassword(password);
|
||
|
|
await db
|
||
|
|
.update(portalUsers)
|
||
|
|
.set({ passwordHash, updatedAt: new Date() })
|
||
|
|
.where(eq(portalUsers.id, tokenRow.portalUserId));
|
||
|
|
}
|
||
|
|
|
||
|
|
// ─── Sign in (email + password) ──────────────────────────────────────────────
|
||
|
|
|
||
|
|
export async function signIn(args: {
|
||
|
|
email: string;
|
||
|
|
password: string;
|
||
|
|
}): Promise<{ token: string; clientId: string; portId: string; email: string }> {
|
||
|
|
const normalizedEmail = args.email.toLowerCase().trim();
|
||
|
|
|
||
|
|
// Always do the same amount of work regardless of whether the email
|
||
|
|
// exists, so timing doesn't leak account presence.
|
||
|
|
const user = await db.query.portalUsers.findFirst({
|
||
|
|
where: eq(portalUsers.email, normalizedEmail),
|
||
|
|
});
|
||
|
|
|
||
|
|
// Dummy hash with the right shape — used to keep verifyPassword's compute
|
||
|
|
// cost identical when the user doesn't exist.
|
||
|
|
const dummyHash =
|
||
|
|
'0000000000000000000000000000000000000000000000000000000000000000:00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000';
|
||
|
|
|
||
|
|
const ok = user?.passwordHash
|
||
|
|
? await verifyPassword(args.password, user.passwordHash)
|
||
|
|
: (await verifyPassword(args.password, dummyHash), false);
|
||
|
|
|
||
|
|
if (!user || !user.isActive || !user.passwordHash || !ok) {
|
||
|
|
throw new UnauthorizedError('Invalid email or password');
|
||
|
|
}
|
||
|
|
|
||
|
|
const token = await createPortalToken({
|
||
|
|
clientId: user.clientId,
|
||
|
|
portId: user.portId,
|
||
|
|
email: user.email,
|
||
|
|
});
|
||
|
|
|
||
|
|
await db.update(portalUsers).set({ lastLoginAt: new Date() }).where(eq(portalUsers.id, user.id));
|
||
|
|
|
||
|
|
return { token, clientId: user.clientId, portId: user.portId, email: user.email };
|
||
|
|
}
|
||
|
|
|
||
|
|
// ─── Forgot password ─────────────────────────────────────────────────────────
|
||
|
|
|
||
|
|
export async function requestPasswordReset(email: string): Promise<void> {
|
||
|
|
const normalizedEmail = email.toLowerCase().trim();
|
||
|
|
|
||
|
|
const user = await db.query.portalUsers.findFirst({
|
||
|
|
where: eq(portalUsers.email, normalizedEmail),
|
||
|
|
});
|
||
|
|
|
||
|
|
if (!user || !user.isActive) {
|
||
|
|
// Silently no-op so unknown emails don't leak through timing or
|
||
|
|
// response shape. Caller surfaces "if the email matches an account…".
|
||
|
|
logger.debug({ email: normalizedEmail }, 'Password reset for unknown email');
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
const { raw, hash } = mintToken();
|
||
|
|
const expiresAt = new Date(Date.now() + RESET_TOKEN_TTL_MINUTES * 60 * 1000);
|
||
|
|
|
||
|
|
await db.insert(portalAuthTokens).values({
|
||
|
|
portalUserId: user.id,
|
||
|
|
tokenHash: hash,
|
||
|
|
type: 'reset',
|
||
|
|
expiresAt,
|
||
|
|
});
|
||
|
|
|
||
|
|
const port = await db.query.ports.findFirst({ where: eq(ports.id, user.portId) });
|
||
|
|
const portName = port?.name ?? 'Port Nimara';
|
||
|
|
const link = `${env.APP_URL}/portal/reset-password?token=${encodeURIComponent(raw)}`;
|
||
|
|
|
||
|
|
try {
|
||
|
|
await sendEmail(
|
||
|
|
user.email,
|
||
|
|
`Reset your ${portName} client portal password`,
|
||
|
|
resetEmailHtml({ portName, link, ttlMinutes: RESET_TOKEN_TTL_MINUTES }),
|
||
|
|
);
|
||
|
|
} catch (err) {
|
||
|
|
logger.error({ err, email: user.email }, 'Failed to send password-reset email');
|
||
|
|
// Don't propagate — the public route returns 200 either way.
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function resetPassword(rawToken: string, password: string): Promise<void> {
|
||
|
|
if (password.length < MIN_PASSWORD_LENGTH) {
|
||
|
|
throw new ValidationError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`);
|
||
|
|
}
|
||
|
|
const tokenRow = await consumeToken(rawToken, 'reset');
|
||
|
|
const passwordHash = await hashPassword(password);
|
||
|
|
await db
|
||
|
|
.update(portalUsers)
|
||
|
|
.set({ passwordHash, updatedAt: new Date() })
|
||
|
|
.where(eq(portalUsers.id, tokenRow.portalUserId));
|
||
|
|
}
|
||
|
|
|
||
|
|
// ─── Token consumption (shared between activation + reset) ───────────────────
|
||
|
|
|
||
|
|
async function consumeToken(
|
||
|
|
rawToken: string,
|
||
|
|
type: 'activation' | 'reset',
|
||
|
|
): Promise<{ portalUserId: string }> {
|
||
|
|
const tokenHash = hashToken(rawToken);
|
||
|
|
const now = new Date();
|
||
|
|
|
||
|
|
const row = await db.query.portalAuthTokens.findFirst({
|
||
|
|
where: and(
|
||
|
|
eq(portalAuthTokens.tokenHash, tokenHash),
|
||
|
|
eq(portalAuthTokens.type, type),
|
||
|
|
isNull(portalAuthTokens.usedAt),
|
||
|
|
gt(portalAuthTokens.expiresAt, now),
|
||
|
|
),
|
||
|
|
});
|
||
|
|
|
||
|
|
if (!row) {
|
||
|
|
throw new ValidationError('Invalid or expired token');
|
||
|
|
}
|
||
|
|
|
||
|
|
await db.update(portalAuthTokens).set({ usedAt: now }).where(eq(portalAuthTokens.id, row.id));
|
||
|
|
|
||
|
|
return { portalUserId: row.portalUserId };
|
||
|
|
}
|
||
|
|
|
||
|
|
// ─── Email templates ─────────────────────────────────────────────────────────
|
||
|
|
|
||
|
|
function activationEmailHtml(args: { portName: string; link: string; ttlHours: number }): string {
|
||
|
|
return `
|
||
|
|
<!DOCTYPE html>
|
||
|
|
<html><body style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#f5f5f5;padding:40px 0;margin:0;">
|
||
|
|
<div style="max-width:480px;margin:0 auto;background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
|
||
|
|
<div style="background:#1e2844;padding:32px 40px;text-align:center;">
|
||
|
|
<h1 style="color:#fff;margin:0;font-size:22px;font-weight:600;">${args.portName}</h1>
|
||
|
|
<p style="color:#9ca3af;margin:6px 0 0;font-size:14px;">Client Portal</p>
|
||
|
|
</div>
|
||
|
|
<div style="padding:40px;">
|
||
|
|
<p style="color:#374151;font-size:16px;margin:0 0 16px;">Welcome,</p>
|
||
|
|
<p style="color:#6b7280;font-size:15px;line-height:1.6;margin:0 0 32px;">
|
||
|
|
You've been invited to access the ${args.portName} client portal. Click the button below to set your password and activate your account. The link expires in ${args.ttlHours} hours.
|
||
|
|
</p>
|
||
|
|
<div style="text-align:center;margin:0 0 32px;">
|
||
|
|
<a href="${args.link}" style="display:inline-block;background:#1e2844;color:#fff;text-decoration:none;padding:14px 32px;border-radius:6px;font-size:15px;font-weight:500;">Activate account</a>
|
||
|
|
</div>
|
||
|
|
<p style="color:#9ca3af;font-size:13px;margin:0;line-height:1.5;">If the button doesn't work, paste this link into your browser:<br/><a href="${args.link}" style="color:#1e2844;word-break:break-all;">${args.link}</a></p>
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
</body></html>
|
||
|
|
`;
|
||
|
|
}
|
||
|
|
|
||
|
|
function resetEmailHtml(args: { portName: string; link: string; ttlMinutes: number }): string {
|
||
|
|
return `
|
||
|
|
<!DOCTYPE html>
|
||
|
|
<html><body style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#f5f5f5;padding:40px 0;margin:0;">
|
||
|
|
<div style="max-width:480px;margin:0 auto;background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
|
||
|
|
<div style="background:#1e2844;padding:32px 40px;text-align:center;">
|
||
|
|
<h1 style="color:#fff;margin:0;font-size:22px;font-weight:600;">${args.portName}</h1>
|
||
|
|
<p style="color:#9ca3af;margin:6px 0 0;font-size:14px;">Password reset</p>
|
||
|
|
</div>
|
||
|
|
<div style="padding:40px;">
|
||
|
|
<p style="color:#374151;font-size:16px;margin:0 0 16px;">Hello,</p>
|
||
|
|
<p style="color:#6b7280;font-size:15px;line-height:1.6;margin:0 0 32px;">
|
||
|
|
We received a request to reset your client portal password. Click the button below to choose a new one. The link expires in ${args.ttlMinutes} minutes. If you didn't request this, you can ignore this email.
|
||
|
|
</p>
|
||
|
|
<div style="text-align:center;margin:0 0 32px;">
|
||
|
|
<a href="${args.link}" style="display:inline-block;background:#1e2844;color:#fff;text-decoration:none;padding:14px 32px;border-radius:6px;font-size:15px;font-weight:500;">Reset password</a>
|
||
|
|
</div>
|
||
|
|
<p style="color:#9ca3af;font-size:13px;margin:0;line-height:1.5;">If the button doesn't work, paste this link into your browser:<br/><a href="${args.link}" style="color:#1e2844;word-break:break-all;">${args.link}</a></p>
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
</body></html>
|
||
|
|
`;
|
||
|
|
}
|