feat(portal): replace magic-link with email/password + admin-initiated activation
The client portal no longer uses passwordless / magic-link sign-in. Each
client now has a `portal_users` row with a scrypt-hashed password,
created by an admin from the client detail page; the admin's invite
mails an activation link that the client uses to set their own password.
Forgot-password is wired through the same token mechanism.
Schema (migration `0009_outgoing_rumiko_fujikawa.sql`):
- `portal_users` — one per client account, separate from the CRM
`users` table (better-auth) so the auth realms stay isolated. Email
is globally unique, password is null until activation.
- `portal_auth_tokens` — single-use activation / reset tokens. Stores
only the SHA-256 hash so a DB compromise never leaks live tokens.
Services:
- `src/lib/portal/passwords.ts` — scrypt hash/verify (no new deps;
uses node:crypto), token mint+hash helpers.
- `src/lib/services/portal-auth.service.ts` — createPortalUser,
resendActivation, activateAccount, signIn (timing-safe),
requestPasswordReset, resetPassword. Auth failures throw the new
UnauthorizedError (401); enumeration-safe behaviour everywhere.
Routes:
- POST /api/portal/auth/sign-in — sets the existing portal JWT cookie.
- POST /api/portal/auth/forgot-password — always 200.
- POST /api/portal/auth/reset-password — token + new password.
- POST /api/portal/auth/activate — token + initial password.
- POST /api/v1/clients/:id/portal-user — admin invite (and `?action=resend`).
- Removed: /api/portal/auth/request, /api/portal/auth/verify (magic link).
UI:
- /portal/login — replaced email-only magic-link form with email +
password + "forgot password" link.
- /portal/forgot-password, /portal/reset-password, /portal/activate — new.
- New shared `PasswordSetForm` component used by activate + reset.
- New `PortalInviteButton` rendered on the client detail header.
Email send:
- `createTransporter` now wires SMTP auth when SMTP_USER+SMTP_PASS are
set (gmail app-password or marina-server creds, configured via env).
- `SMTP_FROM` env var lets the sender address be overridden without
pinning it to `noreply@${SMTP_HOST}`.
Tests:
- Smoke spec 17 (client-portal) updated to the new flow: 7/7 green.
- Smoke specs 02-crud-spine, 05-invoices, 20-critical-path updated to
match the post-refactor client + invoice forms (drop companyName,
use OwnerPicker + billingEmail).
- Vitest 652/652 still green; type-check clean.
Drops the dead `requestMagicLink` from portal.service.ts.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
32
src/lib/db/migrations/0009_outgoing_rumiko_fujikawa.sql
Normal file
32
src/lib/db/migrations/0009_outgoing_rumiko_fujikawa.sql
Normal file
@@ -0,0 +1,32 @@
|
||||
CREATE TABLE "portal_auth_tokens" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"portal_user_id" text NOT NULL,
|
||||
"token_hash" text NOT NULL,
|
||||
"type" text NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"used_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "portal_users" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"port_id" text NOT NULL,
|
||||
"client_id" text NOT NULL,
|
||||
"email" text NOT NULL,
|
||||
"password_hash" text,
|
||||
"name" text,
|
||||
"is_active" boolean DEFAULT true NOT NULL,
|
||||
"last_login_at" timestamp with time zone,
|
||||
"created_by" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "portal_auth_tokens" ADD CONSTRAINT "portal_auth_tokens_portal_user_id_portal_users_id_fk" FOREIGN KEY ("portal_user_id") REFERENCES "public"."portal_users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "portal_users" ADD CONSTRAINT "portal_users_port_id_ports_id_fk" FOREIGN KEY ("port_id") REFERENCES "public"."ports"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "portal_users" ADD CONSTRAINT "portal_users_client_id_clients_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."clients"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "idx_portal_tokens_hash_unique" ON "portal_auth_tokens" USING btree ("token_hash");--> statement-breakpoint
|
||||
CREATE INDEX "idx_portal_tokens_user" ON "portal_auth_tokens" USING btree ("portal_user_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "idx_portal_users_email_unique" ON "portal_users" USING btree ("email");--> statement-breakpoint
|
||||
CREATE INDEX "idx_portal_users_client" ON "portal_users" USING btree ("client_id");--> statement-breakpoint
|
||||
CREATE INDEX "idx_portal_users_port" ON "portal_users" USING btree ("port_id");
|
||||
8774
src/lib/db/migrations/meta/0009_snapshot.json
Normal file
8774
src/lib/db/migrations/meta/0009_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -64,6 +64,13 @@
|
||||
"when": 1777204563579,
|
||||
"tag": "0008_loud_ikaris",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "7",
|
||||
"when": 1777210206070,
|
||||
"tag": "0009_outgoing_rumiko_fujikawa",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -31,6 +31,9 @@ export * from './financial';
|
||||
// Email
|
||||
export * from './email';
|
||||
|
||||
// Portal (client-portal auth)
|
||||
export * from './portal';
|
||||
|
||||
// Operations
|
||||
export * from './operations';
|
||||
|
||||
|
||||
76
src/lib/db/schema/portal.ts
Normal file
76
src/lib/db/schema/portal.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { pgTable, text, boolean, timestamp, index, uniqueIndex } from 'drizzle-orm/pg-core';
|
||||
|
||||
import { ports } from './ports';
|
||||
import { clients } from './clients';
|
||||
|
||||
/**
|
||||
* Portal users — one per client account that's been invited to the client
|
||||
* portal. Separate from the CRM `users` table (managed by better-auth) so the
|
||||
* authentication realms stay isolated.
|
||||
*
|
||||
* Created by an admin from the client detail page; the admin's invite mails
|
||||
* an activation token that lets the client set their own password.
|
||||
*/
|
||||
export const portalUsers = pgTable(
|
||||
'portal_users',
|
||||
{
|
||||
id: text('id')
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
portId: text('port_id')
|
||||
.notNull()
|
||||
.references(() => ports.id),
|
||||
clientId: text('client_id')
|
||||
.notNull()
|
||||
.references(() => clients.id, { onDelete: 'cascade' }),
|
||||
email: text('email').notNull(),
|
||||
/**
|
||||
* scrypt-hashed password. Format: `salt:keyHex` (both base64url). Null
|
||||
* until the user activates their account.
|
||||
*/
|
||||
passwordHash: text('password_hash'),
|
||||
name: text('name'),
|
||||
isActive: boolean('is_active').notNull().default(true),
|
||||
lastLoginAt: timestamp('last_login_at', { withTimezone: true }),
|
||||
createdBy: text('created_by').notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('idx_portal_users_email_unique').on(table.email),
|
||||
index('idx_portal_users_client').on(table.clientId),
|
||||
index('idx_portal_users_port').on(table.portId),
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* Single-use tokens for portal-account activation and password reset.
|
||||
*
|
||||
* `tokenHash` is a SHA-256 hash of the raw token sent in the email. Lookups
|
||||
* happen by hash so a DB compromise never leaks active tokens.
|
||||
*/
|
||||
export const portalAuthTokens = pgTable(
|
||||
'portal_auth_tokens',
|
||||
{
|
||||
id: text('id')
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
portalUserId: text('portal_user_id')
|
||||
.notNull()
|
||||
.references(() => portalUsers.id, { onDelete: 'cascade' }),
|
||||
tokenHash: text('token_hash').notNull(),
|
||||
type: text('type').notNull(), // 'activation' | 'reset'
|
||||
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
|
||||
usedAt: timestamp('used_at', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('idx_portal_tokens_hash_unique').on(table.tokenHash),
|
||||
index('idx_portal_tokens_user').on(table.portalUserId),
|
||||
],
|
||||
);
|
||||
|
||||
export type PortalUser = typeof portalUsers.$inferSelect;
|
||||
export type NewPortalUser = typeof portalUsers.$inferInsert;
|
||||
export type PortalAuthToken = typeof portalAuthTokens.$inferSelect;
|
||||
export type NewPortalAuthToken = typeof portalAuthTokens.$inferInsert;
|
||||
@@ -16,6 +16,9 @@ export function createTransporter(): Transporter {
|
||||
port: env.SMTP_PORT,
|
||||
// Implicitly secure when port is 465; STARTTLS for all other ports.
|
||||
secure: env.SMTP_PORT === 465,
|
||||
...(env.SMTP_USER && env.SMTP_PASS
|
||||
? { auth: { user: env.SMTP_USER, pass: env.SMTP_PASS } }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -43,7 +46,7 @@ export async function sendEmail(
|
||||
const transporter = createTransporter();
|
||||
|
||||
const info = await transporter.sendMail({
|
||||
from: from ?? `Port Nimara CRM <noreply@${env.SMTP_HOST}>`,
|
||||
from: from ?? env.SMTP_FROM ?? `Port Nimara CRM <noreply@${env.SMTP_HOST}>`,
|
||||
to: Array.isArray(to) ? to.join(', ') : to,
|
||||
subject,
|
||||
html,
|
||||
|
||||
@@ -32,6 +32,9 @@ const envSchema = z.object({
|
||||
// Email
|
||||
SMTP_HOST: z.string().min(1),
|
||||
SMTP_PORT: z.coerce.number().int().positive(),
|
||||
SMTP_USER: z.string().optional(),
|
||||
SMTP_PASS: z.string().optional(),
|
||||
SMTP_FROM: z.string().optional(),
|
||||
|
||||
// Encryption
|
||||
EMAIL_CREDENTIAL_KEY: z
|
||||
|
||||
@@ -26,6 +26,12 @@ export class ForbiddenError extends AppError {
|
||||
}
|
||||
}
|
||||
|
||||
export class UnauthorizedError extends AppError {
|
||||
constructor(message = 'Unauthorized') {
|
||||
super(401, message, 'UNAUTHORIZED');
|
||||
}
|
||||
}
|
||||
|
||||
export class ValidationError extends AppError {
|
||||
constructor(
|
||||
message: string,
|
||||
|
||||
60
src/lib/portal/passwords.ts
Normal file
60
src/lib/portal/passwords.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { randomBytes, scrypt as scryptCb, timingSafeEqual, createHash } from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
const scrypt = promisify(scryptCb) as (
|
||||
password: string,
|
||||
salt: Buffer,
|
||||
keyLen: number,
|
||||
) => Promise<Buffer>;
|
||||
|
||||
const KEY_LENGTH = 64;
|
||||
const SALT_LENGTH = 16;
|
||||
|
||||
/**
|
||||
* Hash a password with a fresh random salt. Stored format is
|
||||
* `salt:keyHex` (both as hex strings) so verification can re-derive without
|
||||
* a separate salt column.
|
||||
*/
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
const salt = randomBytes(SALT_LENGTH);
|
||||
const key = await scrypt(password, salt, KEY_LENGTH);
|
||||
return `${salt.toString('hex')}:${key.toString('hex')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constant-time check of a candidate password against a stored
|
||||
* `salt:keyHex` hash. Returns false on any malformed input rather than
|
||||
* throwing — callers should treat false uniformly.
|
||||
*/
|
||||
export async function verifyPassword(password: string, stored: string): Promise<boolean> {
|
||||
const parts = stored.split(':');
|
||||
if (parts.length !== 2) return false;
|
||||
const [saltHex, keyHex] = parts;
|
||||
if (!saltHex || !keyHex) return false;
|
||||
let salt: Buffer;
|
||||
let expected: Buffer;
|
||||
try {
|
||||
salt = Buffer.from(saltHex, 'hex');
|
||||
expected = Buffer.from(keyHex, 'hex');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (expected.length !== KEY_LENGTH) return false;
|
||||
const candidate = await scrypt(password, salt, KEY_LENGTH);
|
||||
return timingSafeEqual(candidate, expected);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mint a fresh raw token (returned to the caller) and its SHA-256 hash
|
||||
* (stored in the DB). The raw token is meant to be embedded in a one-shot
|
||||
* URL; only the hash persists.
|
||||
*/
|
||||
export function mintToken(byteLength = 32): { raw: string; hash: string } {
|
||||
const raw = randomBytes(byteLength).toString('base64url');
|
||||
const hash = createHash('sha256').update(raw).digest('hex');
|
||||
return { raw, hash };
|
||||
}
|
||||
|
||||
export function hashToken(raw: string): string {
|
||||
return createHash('sha256').update(raw).digest('hex');
|
||||
}
|
||||
286
src/lib/services/portal-auth.service.ts
Normal file
286
src/lib/services/portal-auth.service.ts
Normal file
@@ -0,0 +1,286 @@
|
||||
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>
|
||||
`;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { and, eq, count, inArray, isNull, desc } from 'drizzle-orm';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import { clients, clientContacts } from '@/lib/db/schema/clients';
|
||||
import { clients } from '@/lib/db/schema/clients';
|
||||
import { interests } from '@/lib/db/schema/interests';
|
||||
import { documents, files } from '@/lib/db/schema/documents';
|
||||
import { invoices } from '@/lib/db/schema/financial';
|
||||
@@ -10,95 +10,7 @@ import { ports } from '@/lib/db/schema/ports';
|
||||
import { yachts } from '@/lib/db/schema/yachts';
|
||||
import { companies, companyMemberships } from '@/lib/db/schema/companies';
|
||||
import { berthReservations } from '@/lib/db/schema/reservations';
|
||||
import { createPortalToken } from '@/lib/portal/auth';
|
||||
import { sendEmail } from '@/lib/email';
|
||||
import { getPresignedUrl } from '@/lib/minio';
|
||||
import { env } from '@/lib/env';
|
||||
import { logger } from '@/lib/logger';
|
||||
|
||||
// ─── Magic Link ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Requests a magic link for portal access.
|
||||
* Always returns success — never reveals whether an email exists in the system.
|
||||
*/
|
||||
export async function requestMagicLink(email: string): Promise<void> {
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
// Find client contact with matching email
|
||||
const contact = await db.query.clientContacts.findFirst({
|
||||
where: and(eq(clientContacts.channel, 'email'), eq(clientContacts.value, normalizedEmail)),
|
||||
with: {
|
||||
client: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!contact || !contact.client) {
|
||||
// Don't reveal that the email doesn't exist — silently return
|
||||
logger.debug({ email: normalizedEmail }, 'Portal magic link: no matching client contact');
|
||||
return;
|
||||
}
|
||||
|
||||
const client = contact.client;
|
||||
|
||||
// Build the JWT
|
||||
const token = await createPortalToken({
|
||||
clientId: client.id,
|
||||
portId: client.portId,
|
||||
email: normalizedEmail,
|
||||
});
|
||||
|
||||
const magicLinkUrl = `${env.APP_URL}/verify?token=${encodeURIComponent(token)}`;
|
||||
|
||||
// Fetch port name for the email
|
||||
const port = await db.query.ports.findFirst({
|
||||
where: eq(ports.id, client.portId),
|
||||
});
|
||||
|
||||
const portName = port?.name ?? 'Port Nimara';
|
||||
const clientName = client.fullName;
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
</head>
|
||||
<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: #ffffff; 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: #ffffff; margin: 0; font-size: 22px; font-weight: 600;">${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 8px;">Hello, ${clientName}</p>
|
||||
<p style="color: #6b7280; font-size: 15px; margin: 0 0 32px; line-height: 1.6;">
|
||||
You requested access to your client portal. Click the button below to sign in. This link expires in 24 hours.
|
||||
</p>
|
||||
<div style="text-align: center; margin: 0 0 32px;">
|
||||
<a href="${magicLinkUrl}" style="display: inline-block; background: #1e2844; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 6px; font-size: 15px; font-weight: 500;">
|
||||
Access My Portal
|
||||
</a>
|
||||
</div>
|
||||
<p style="color: #9ca3af; font-size: 13px; margin: 0; line-height: 1.6;">
|
||||
If you didn't request this, you can safely ignore this email. If you're having trouble with the button above, copy and paste this URL into your browser:
|
||||
<br><br>
|
||||
<span style="color: #6b7280; word-break: break-all;">${magicLinkUrl}</span>
|
||||
</p>
|
||||
</div>
|
||||
<div style="background: #f9fafb; padding: 20px 40px; text-align: center; border-top: 1px solid #e5e7eb;">
|
||||
<p style="color: #9ca3af; font-size: 12px; margin: 0;">© ${new Date().getFullYear()} ${portName}. All rights reserved.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
await sendEmail(normalizedEmail, `Your ${portName} portal access link`, html);
|
||||
|
||||
logger.info({ clientId: client.id, portId: client.portId }, 'Portal magic link sent');
|
||||
}
|
||||
|
||||
// ─── Dashboard ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
Reference in New Issue
Block a user