feat(portal): replace magic-link with email/password + admin-initiated activation
All checks were successful
Build & Push Docker Images / lint (pull_request) Successful in 1m0s
Build & Push Docker Images / build-and-push (pull_request) Has been skipped

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:
Matt Ciaccio
2026-04-26 15:34:02 +02:00
parent 4da8ed3ae4
commit 475b051e29
33 changed files with 10129 additions and 331 deletions

2
.gitignore vendored
View File

@@ -19,3 +19,5 @@ tsconfig.tsbuildinfo
.playwright-mcp/ .playwright-mcp/
docker-compose.override.yml docker-compose.override.yml
.remember/ .remember/
.DS_Store
eoi/

BIN
assets/eoi-template.pdf Normal file

Binary file not shown.

View File

@@ -0,0 +1,24 @@
import { Suspense } from 'react';
import { PasswordSetForm } from '@/components/portal/password-set-form';
export default function PortalActivatePage() {
return (
<Suspense
fallback={
<div className="min-h-screen flex items-center justify-center bg-gray-50 text-sm text-gray-500">
Loading
</div>
}
>
<PasswordSetForm
endpoint="/api/portal/auth/activate"
title="Activate your account"
description="Welcome — choose a password to finish setting up your client portal account."
successTitle="Account activated"
successDescription="You can now sign in with your new password."
submitLabel="Activate account"
/>
</Suspense>
);
}

View File

@@ -0,0 +1,107 @@
'use client';
import Link from 'next/link';
import { useState } from 'react';
import { Loader2, Mail } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
export default function PortalForgotPasswordPage() {
const [email, setEmail] = useState('');
const [loading, setLoading] = useState(false);
const [submitted, setSubmitted] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
try {
// Always returns 200 — caller never sees whether email exists.
await fetch('/api/portal/auth/forgot-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
} finally {
setSubmitted(true);
setLoading(false);
}
}
if (submitted) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
<div className="w-full max-w-md text-center">
<div className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-green-50 mb-4">
<Mail className="h-7 w-7 text-green-600" />
</div>
<h1 className="text-xl font-semibold text-gray-900 mb-2">Check your email</h1>
<p className="text-gray-500 text-sm leading-relaxed">
If <strong>{email}</strong> matches a portal account, we&apos;ve sent a reset link. The
link expires in 30 minutes.
</p>
<Link
href="/portal/login"
className="mt-6 inline-block text-sm text-[#1e2844] hover:underline"
>
Back to sign in
</Link>
</div>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
<div className="w-full max-w-sm">
<div className="bg-white rounded-lg border p-8 shadow-sm">
<div className="text-center mb-6">
<h1 className="text-xl font-semibold text-gray-900">Reset your password</h1>
<p className="text-sm text-gray-500 mt-1">
Enter your email and we&apos;ll send you a reset link.
</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="email">Email address</Label>
<Input
id="email"
type="email"
placeholder="you@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
autoFocus
disabled={loading}
/>
</div>
<Button
type="submit"
className="w-full bg-[#1e2844] hover:bg-[#1e2844]/90 text-white"
disabled={loading || !email}
>
{loading ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Sending
</>
) : (
'Send reset link'
)}
</Button>
</form>
<Link
href="/portal/login"
className="block mt-4 text-center text-xs text-gray-500 hover:underline"
>
Back to sign in
</Link>
</div>
</div>
</div>
);
}

View File

@@ -1,15 +1,22 @@
'use client'; 'use client';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useState } from 'react'; import { useState } from 'react';
import { Mail, Loader2 } from 'lucide-react'; import { Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
export default function PortalLoginPage() { export default function PortalLoginPage() {
const router = useRouter();
const search = useSearchParams();
const next = search.get('next') ?? '/portal/dashboard';
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
async function handleSubmit(e: React.FormEvent) { async function handleSubmit(e: React.FormEvent) {
@@ -18,59 +25,35 @@ export default function PortalLoginPage() {
setLoading(true); setLoading(true);
try { try {
const res = await fetch('/api/portal/auth/request', { const res = await fetch('/api/portal/auth/sign-in', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }), body: JSON.stringify({ email, password }),
}); });
if (!res.ok) { if (!res.ok) {
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
setError((data as { error?: string }).error ?? 'Something went wrong. Please try again.'); setError((data as { error?: string }).error ?? 'Invalid email or password');
return; return;
} }
setSubmitted(true); // typedRoutes: `next` is a runtime string we can't statically check.
router.replace(next as never);
router.refresh();
} catch { } catch {
setError('Unable to connect. Please check your connection and try again.'); setError('Unable to connect. Please try again.');
} finally { } finally {
setLoading(false); setLoading(false);
} }
} }
if (submitted) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
<div className="w-full max-w-md text-center">
<div className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-green-50 mb-4">
<Mail className="h-7 w-7 text-green-600" />
</div>
<h1 className="text-xl font-semibold text-gray-900 mb-2">Check your email</h1>
<p className="text-gray-500 text-sm leading-relaxed">
If <strong>{email}</strong> is associated with a client account, you will receive a
sign-in link shortly. The link expires in 24 hours.
</p>
<button
type="button"
onClick={() => { setSubmitted(false); setEmail(''); }}
className="mt-6 text-sm text-[#1e2844] hover:underline"
>
Try a different email
</button>
</div>
</div>
);
}
return ( return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4"> <div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
<div className="w-full max-w-sm"> <div className="w-full max-w-sm">
<div className="bg-white rounded-lg border p-8 shadow-sm"> <div className="bg-white rounded-lg border p-8 shadow-sm">
<div className="text-center mb-6"> <div className="text-center mb-6">
<h1 className="text-xl font-semibold text-gray-900">Client Portal</h1> <h1 className="text-xl font-semibold text-gray-900">Client Portal</h1>
<p className="text-sm text-gray-500 mt-1"> <p className="text-sm text-gray-500 mt-1">Sign in to your account</p>
Enter your email to receive a sign-in link
</p>
</div> </div>
<form onSubmit={handleSubmit} className="space-y-4"> <form onSubmit={handleSubmit} className="space-y-4">
@@ -84,26 +67,46 @@ export default function PortalLoginPage() {
onChange={(e) => setEmail(e.target.value)} onChange={(e) => setEmail(e.target.value)}
required required
autoFocus autoFocus
autoComplete="email"
disabled={loading} disabled={loading}
/> />
</div> </div>
{error && ( <div className="space-y-1.5">
<p className="text-sm text-red-600">{error}</p> <div className="flex items-center justify-between">
)} <Label htmlFor="password">Password</Label>
<Link
href="/portal/forgot-password"
className="text-xs text-[#1e2844] hover:underline"
>
Forgot password?
</Link>
</div>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
autoComplete="current-password"
disabled={loading}
/>
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
<Button <Button
type="submit" type="submit"
className="w-full bg-[#1e2844] hover:bg-[#1e2844]/90 text-white" className="w-full bg-[#1e2844] hover:bg-[#1e2844]/90 text-white"
disabled={loading || !email} disabled={loading || !email || !password}
> >
{loading ? ( {loading ? (
<> <>
<Loader2 className="h-4 w-4 mr-2 animate-spin" /> <Loader2 className="h-4 w-4 mr-2 animate-spin" />
Sending link... Signing in
</> </>
) : ( ) : (
'Send sign-in link' 'Sign in'
)} )}
</Button> </Button>
</form> </form>

View File

@@ -0,0 +1,24 @@
import { Suspense } from 'react';
import { PasswordSetForm } from '@/components/portal/password-set-form';
export default function PortalResetPasswordPage() {
return (
<Suspense
fallback={
<div className="min-h-screen flex items-center justify-center bg-gray-50 text-sm text-gray-500">
Loading
</div>
}
>
<PasswordSetForm
endpoint="/api/portal/auth/reset-password"
title="Choose a new password"
description="Enter a new password to regain access to your client portal."
successTitle="Password updated"
successDescription="You can now sign in with your new password."
submitLabel="Update password"
/>
</Suspense>
);
}

View File

@@ -1,49 +0,0 @@
'use client';
import { Suspense, useEffect, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Loader2 } from 'lucide-react';
function PortalVerifyInner() {
const router = useRouter();
const searchParams = useSearchParams();
const calledRef = useRef(false);
useEffect(() => {
if (calledRef.current) return;
calledRef.current = true;
const token = searchParams.get('token');
if (!token) {
router.replace('/portal/login?error=missing_token');
return;
}
// Redirect to the verify API route which will set the cookie and redirect
window.location.href = `/api/portal/auth/verify?token=${encodeURIComponent(token)}`;
}, [searchParams, router]);
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-center">
<Loader2 className="h-8 w-8 animate-spin text-[#1e2844] mx-auto mb-3" />
<p className="text-sm text-gray-500">Verifying your access...</p>
</div>
</div>
);
}
export default function PortalVerifyPage() {
return (
<Suspense
fallback={
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<Loader2 className="h-8 w-8 animate-spin text-[#1e2844]" />
</div>
}
>
<PortalVerifyInner />
</Suspense>
);
}

View File

@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { errorResponse } from '@/lib/errors';
import { activateAccount } from '@/lib/services/portal-auth.service';
const bodySchema = z.object({
token: z.string().min(1),
password: z.string().min(12),
});
export async function POST(req: NextRequest): Promise<NextResponse> {
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
}
const parsed = bodySchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.errors[0]?.message ?? 'Invalid input' },
{ status: 400 },
);
}
try {
await activateAccount(parsed.data.token, parsed.data.password);
return NextResponse.json({ success: true });
} catch (err) {
return errorResponse(err);
}
}

View File

@@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { logger } from '@/lib/logger';
import { requestPasswordReset } from '@/lib/services/portal-auth.service';
const bodySchema = z.object({ email: z.string().email() });
export async function POST(req: NextRequest): Promise<NextResponse> {
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
}
const parsed = bodySchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid email address' }, { status: 400 });
}
// Always return 200 to prevent account-enumeration. Errors are logged
// server-side, never surfaced to the client.
try {
await requestPasswordReset(parsed.data.email);
} catch (err) {
logger.error({ err }, 'Portal forgot-password failed (swallowed)');
}
return NextResponse.json({ success: true });
}

View File

@@ -1,28 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { requestMagicLink } from '@/lib/services/portal.service';
import { logger } from '@/lib/logger';
const bodySchema = z.object({
email: z.string().email(),
});
export async function POST(req: NextRequest): Promise<NextResponse> {
try {
const body = await req.json();
const parsed = bodySchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid email address' }, { status: 400 });
}
await requestMagicLink(parsed.data.email);
// Always return success to prevent email enumeration
return NextResponse.json({ success: true });
} catch (error) {
logger.error({ error }, 'Portal magic link request failed');
return NextResponse.json({ error: 'Failed to process request' }, { status: 500 });
}
}

View File

@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { errorResponse } from '@/lib/errors';
import { resetPassword } from '@/lib/services/portal-auth.service';
const bodySchema = z.object({
token: z.string().min(1),
password: z.string().min(12),
});
export async function POST(req: NextRequest): Promise<NextResponse> {
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
}
const parsed = bodySchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.errors[0]?.message ?? 'Invalid input' },
{ status: 400 },
);
}
try {
await resetPassword(parsed.data.token, parsed.data.password);
return NextResponse.json({ success: true });
} catch (err) {
return errorResponse(err);
}
}

View File

@@ -0,0 +1,42 @@
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { errorResponse } from '@/lib/errors';
import { PORTAL_COOKIE } from '@/lib/portal/auth';
import { signIn } from '@/lib/services/portal-auth.service';
const bodySchema = z.object({
email: z.string().email(),
password: z.string().min(1),
});
const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24; // 24h, matches createPortalToken
export async function POST(req: NextRequest): Promise<NextResponse> {
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
}
const parsed = bodySchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid email or password' }, { status: 400 });
}
try {
const result = await signIn(parsed.data);
const res = NextResponse.json({ success: true });
res.cookies.set(PORTAL_COOKIE, result.token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: SESSION_MAX_AGE_SECONDS,
});
return res;
} catch (err) {
return errorResponse(err);
}
}

View File

@@ -1,38 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyPortalToken, PORTAL_COOKIE } from '@/lib/portal/auth';
import { env } from '@/lib/env';
import { logger } from '@/lib/logger';
export async function GET(req: NextRequest): Promise<NextResponse> {
try {
const token = req.nextUrl.searchParams.get('token');
if (!token) {
return NextResponse.redirect(new URL('/portal/login?error=missing_token', env.APP_URL));
}
const session = await verifyPortalToken(token);
if (!session) {
return NextResponse.redirect(new URL('/portal/login?error=invalid_token', env.APP_URL));
}
const response = NextResponse.redirect(new URL('/portal/dashboard', env.APP_URL));
response.cookies.set(PORTAL_COOKIE, token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24, // 24 hours
});
logger.info({ clientId: session.clientId }, 'Portal session created');
return response;
} catch (error) {
logger.error({ error }, 'Portal token verification failed');
return NextResponse.redirect(new URL('/portal/login?error=server_error', env.APP_URL));
}
}

View File

@@ -0,0 +1,59 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { createPortalUser, resendActivation } from '@/lib/services/portal-auth.service';
import { db } from '@/lib/db';
import { eq } from 'drizzle-orm';
import { portalUsers } from '@/lib/db/schema/portal';
const inviteSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(200).optional(),
});
/**
* POST /api/v1/clients/:id/portal-user
*
* Admin creates a portal account for a client and triggers the activation
* email. Idempotent in spirit: if a portal user already exists for the
* email, returns 409 — the admin can resend the activation via
* ?action=resend.
*/
export const POST = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
const url = new URL(req.url);
const action = url.searchParams.get('action');
if (action === 'resend') {
// Body is optional in resend mode; the portal user id is the path id
// in this case (not the client id). Looking up by client+email so
// admins don't have to track portal-user ids.
const body = await parseBody(req, inviteSchema);
const existing = await db.query.portalUsers.findFirst({
where: eq(portalUsers.email, body.email.toLowerCase().trim()),
});
if (!existing) {
return NextResponse.json({ error: 'Portal user not found' }, { status: 404 });
}
await resendActivation(existing.id, ctx.portId);
return NextResponse.json({ success: true });
}
const body = await parseBody(req, inviteSchema);
const result = await createPortalUser({
clientId: params.id!,
portId: ctx.portId,
email: body.email,
name: body.name,
createdBy: ctx.userId,
});
return NextResponse.json({ data: result }, { status: 201 });
} catch (err) {
return errorResponse(err);
}
}),
);

View File

@@ -9,6 +9,7 @@ import { Badge } from '@/components/ui/badge';
import { TagBadge } from '@/components/shared/tag-badge'; import { TagBadge } from '@/components/shared/tag-badge';
import { ArchiveConfirmDialog } from '@/components/shared/archive-confirm-dialog'; import { ArchiveConfirmDialog } from '@/components/shared/archive-confirm-dialog';
import { ClientForm } from '@/components/clients/client-form'; import { ClientForm } from '@/components/clients/client-form';
import { PortalInviteButton } from '@/components/clients/portal-invite-button';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
interface ClientDetailHeaderProps { interface ClientDetailHeaderProps {
@@ -127,6 +128,13 @@ export function ClientDetailHeader({ client }: ClientDetailHeaderProps) {
{/* Actions */} {/* Actions */}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{!isArchived && (
<PortalInviteButton
clientId={client.id}
clientName={client.fullName}
defaultEmail={primaryEmail?.value}
/>
)}
<Button variant="outline" size="sm" onClick={() => setEditOpen(true)}> <Button variant="outline" size="sm" onClick={() => setEditOpen(true)}>
<Pencil className="mr-1.5 h-3.5 w-3.5" /> <Pencil className="mr-1.5 h-3.5 w-3.5" />
Edit Edit

View File

@@ -0,0 +1,154 @@
'use client';
import { useState } from 'react';
import { UserPlus, Loader2, Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { apiFetch } from '@/lib/api/client';
interface PortalInviteButtonProps {
clientId: string;
clientName: string;
defaultEmail?: string;
}
/**
* Admin button on the client detail header that creates a portal user for
* the client and sends them an activation email. Uses the client's primary
* email as the default but lets the admin override.
*/
export function PortalInviteButton({
clientId,
clientName,
defaultEmail,
}: PortalInviteButtonProps) {
const [open, setOpen] = useState(false);
const [email, setEmail] = useState(defaultEmail ?? '');
const [name, setName] = useState(clientName);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState(false);
function reset() {
setEmail(defaultEmail ?? '');
setName(clientName);
setError('');
setSuccess(false);
setLoading(false);
}
async function submit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError('');
try {
await apiFetch(`/api/v1/clients/${clientId}/portal-user`, {
method: 'POST',
body: { email, name },
});
setSuccess(true);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to send invitation');
} finally {
setLoading(false);
}
}
return (
<>
<Button
variant="outline"
size="sm"
onClick={() => {
reset();
setOpen(true);
}}
>
<UserPlus className="mr-1.5 h-3.5 w-3.5" />
Invite to portal
</Button>
<Dialog
open={open}
onOpenChange={(o) => {
if (!o) reset();
setOpen(o);
}}
>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Invite to client portal</DialogTitle>
<DialogDescription>
We&apos;ll email an activation link. The client picks their own password from there.
</DialogDescription>
</DialogHeader>
{success ? (
<div className="py-4 flex items-center gap-3 text-sm text-green-700">
<Check className="h-5 w-5" />
Activation email sent to <strong>{email}</strong>.
</div>
) : (
<form onSubmit={submit} className="space-y-4 py-2">
<div className="space-y-1.5">
<Label htmlFor="invite-email">Email address</Label>
<Input
id="invite-email"
type="email"
required
autoFocus
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={loading}
placeholder="client@example.com"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="invite-name">Display name (optional)</Label>
<Input
id="invite-name"
value={name}
onChange={(e) => setName(e.target.value)}
disabled={loading}
/>
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
</form>
)}
<DialogFooter>
{success ? (
<Button onClick={() => setOpen(false)}>Done</Button>
) : (
<>
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button onClick={submit} disabled={loading || !email}>
{loading ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Sending
</>
) : (
'Send invitation'
)}
</Button>
</>
)}
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}

View File

@@ -0,0 +1,181 @@
'use client';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useState } from 'react';
import { CheckCircle2, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
interface PasswordSetFormProps {
/** API endpoint that accepts `{ token, password }` and sets / resets the password. */
endpoint: string;
title: string;
description: string;
successTitle: string;
successDescription: string;
submitLabel: string;
}
const MIN_LENGTH = 12;
/**
* Shared form used by both the activation and password-reset flows. The
* activation token is read from the `?token=` query string. Empty / missing
* tokens land the user in an explicit error state instead of submitting a
* doomed request.
*/
export function PasswordSetForm({
endpoint,
title,
description,
successTitle,
successDescription,
submitLabel,
}: PasswordSetFormProps) {
const search = useSearchParams();
const token = search.get('token') ?? '';
const [password, setPassword] = useState('');
const [confirm, setConfirm] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [done, setDone] = useState(false);
const tooShort = password.length > 0 && password.length < MIN_LENGTH;
const mismatch = confirm.length > 0 && password !== confirm;
const canSubmit = !!token && password.length >= MIN_LENGTH && password === confirm && !loading;
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!canSubmit) return;
setLoading(true);
setError('');
try {
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, password }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError((data as { error?: string }).error ?? 'Something went wrong. Please try again.');
return;
}
setDone(true);
} catch {
setError('Unable to connect. Please try again.');
} finally {
setLoading(false);
}
}
if (!token) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
<div className="w-full max-w-md text-center space-y-3">
<h1 className="text-xl font-semibold text-gray-900">Link is missing or invalid</h1>
<p className="text-sm text-gray-500">
Please use the link from the email we sent you. If the link is broken, request a new
one.
</p>
<Link
href="/portal/forgot-password"
className="inline-block text-sm text-[#1e2844] hover:underline"
>
Request a new link
</Link>
</div>
</div>
);
}
if (done) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
<div className="w-full max-w-md text-center">
<div className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-green-50 mb-4">
<CheckCircle2 className="h-7 w-7 text-green-600" />
</div>
<h1 className="text-xl font-semibold text-gray-900 mb-2">{successTitle}</h1>
<p className="text-gray-500 text-sm">{successDescription}</p>
<Link
href="/portal/login"
className="mt-6 inline-block text-sm text-[#1e2844] hover:underline"
>
Sign in
</Link>
</div>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
<div className="w-full max-w-sm">
<div className="bg-white rounded-lg border p-8 shadow-sm">
<div className="mb-6">
<h1 className="text-xl font-semibold text-gray-900">{title}</h1>
<p className="text-sm text-gray-500 mt-1">{description}</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="password">New password</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
autoFocus
autoComplete="new-password"
minLength={MIN_LENGTH}
disabled={loading}
/>
<p className="text-xs text-gray-500">At least {MIN_LENGTH} characters.</p>
{tooShort && (
<p className="text-xs text-red-600">
Password must be at least {MIN_LENGTH} characters.
</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="confirm">Confirm password</Label>
<Input
id="confirm"
type="password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
required
autoComplete="new-password"
disabled={loading}
/>
{mismatch && <p className="text-xs text-red-600">Passwords don&apos;t match.</p>}
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
<Button
type="submit"
className="w-full bg-[#1e2844] hover:bg-[#1e2844]/90 text-white"
disabled={!canSubmit}
>
{loading ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Saving
</>
) : (
submitLabel
)}
</Button>
</form>
</div>
</div>
</div>
);
}

View 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");

File diff suppressed because it is too large Load Diff

View File

@@ -64,6 +64,13 @@
"when": 1777204563579, "when": 1777204563579,
"tag": "0008_loud_ikaris", "tag": "0008_loud_ikaris",
"breakpoints": true "breakpoints": true
},
{
"idx": 9,
"version": "7",
"when": 1777210206070,
"tag": "0009_outgoing_rumiko_fujikawa",
"breakpoints": true
} }
] ]
} }

View File

@@ -31,6 +31,9 @@ export * from './financial';
// Email // Email
export * from './email'; export * from './email';
// Portal (client-portal auth)
export * from './portal';
// Operations // Operations
export * from './operations'; export * from './operations';

View 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;

View File

@@ -16,6 +16,9 @@ export function createTransporter(): Transporter {
port: env.SMTP_PORT, port: env.SMTP_PORT,
// Implicitly secure when port is 465; STARTTLS for all other ports. // Implicitly secure when port is 465; STARTTLS for all other ports.
secure: env.SMTP_PORT === 465, 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 transporter = createTransporter();
const info = await transporter.sendMail({ 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, to: Array.isArray(to) ? to.join(', ') : to,
subject, subject,
html, html,

View File

@@ -32,6 +32,9 @@ const envSchema = z.object({
// Email // Email
SMTP_HOST: z.string().min(1), SMTP_HOST: z.string().min(1),
SMTP_PORT: z.coerce.number().int().positive(), SMTP_PORT: z.coerce.number().int().positive(),
SMTP_USER: z.string().optional(),
SMTP_PASS: z.string().optional(),
SMTP_FROM: z.string().optional(),
// Encryption // Encryption
EMAIL_CREDENTIAL_KEY: z EMAIL_CREDENTIAL_KEY: z

View File

@@ -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 { export class ValidationError extends AppError {
constructor( constructor(
message: string, message: string,

View 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');
}

View 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>
`;
}

View File

@@ -1,7 +1,7 @@
import { and, eq, count, inArray, isNull, desc } from 'drizzle-orm'; import { and, eq, count, inArray, isNull, desc } from 'drizzle-orm';
import { db } from '@/lib/db'; 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 { interests } from '@/lib/db/schema/interests';
import { documents, files } from '@/lib/db/schema/documents'; import { documents, files } from '@/lib/db/schema/documents';
import { invoices } from '@/lib/db/schema/financial'; 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 { yachts } from '@/lib/db/schema/yachts';
import { companies, companyMemberships } from '@/lib/db/schema/companies'; import { companies, companyMemberships } from '@/lib/db/schema/companies';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthReservations } from '@/lib/db/schema/reservations';
import { createPortalToken } from '@/lib/portal/auth';
import { sendEmail } from '@/lib/email';
import { getPresignedUrl } from '@/lib/minio'; 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;">&copy; ${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 ──────────────────────────────────────────────────────────────── // ─── Dashboard ────────────────────────────────────────────────────────────────

View File

@@ -12,12 +12,14 @@ test.describe('CRUD Spine', () => {
await navigateTo(page, '/clients'); await navigateTo(page, '/clients');
// Click "New Client" button (use first() in case of duplicates in empty state) // Click "New Client" button (use first() in case of duplicates in empty state)
await page.getByRole('button', { name: /new client/i }).first().click(); await page
.getByRole('button', { name: /new client/i })
.first()
.click();
await waitForSheet(page); await waitForSheet(page);
const sheet = page.locator('[role="dialog"]'); const sheet = page.locator('[role="dialog"]');
await sheet.locator('input[name="fullName"]').fill(TEST_CLIENT_NAME); await sheet.locator('input[name="fullName"]').fill(TEST_CLIENT_NAME);
await sheet.locator('input[name="companyName"]').fill('E2E Test Corp');
await sheet.locator('input[name="nationality"]').fill('British'); await sheet.locator('input[name="nationality"]').fill('British');
await sheet.locator('input[name="contacts.0.value"]').fill('e2e@test.com'); await sheet.locator('input[name="contacts.0.value"]').fill('e2e@test.com');
@@ -34,7 +36,10 @@ test.describe('CRUD Spine', () => {
await page.waitForTimeout(2000); await page.waitForTimeout(2000);
// The client name should appear somewhere in the table or page // The client name should appear somewhere in the table or page
const hasClient = await page.getByText(TEST_CLIENT_NAME).isVisible({ timeout: 5_000 }).catch(() => false); const hasClient = await page
.getByText(TEST_CLIENT_NAME)
.isVisible({ timeout: 5_000 })
.catch(() => false);
if (!hasClient) { if (!hasClient) {
// Maybe the table loaded empty and we need to wait for data // Maybe the table loaded empty and we need to wait for data
await page.waitForTimeout(3000); await page.waitForTimeout(3000);
@@ -92,7 +97,10 @@ test.describe('CRUD Spine', () => {
await page.waitForTimeout(2000); await page.waitForTimeout(2000);
// Client should disappear from active list // Client should disappear from active list
const stillVisible = await page.getByText(TEST_CLIENT_NAME).isVisible({ timeout: 3_000 }).catch(() => false); const stillVisible = await page
.getByText(TEST_CLIENT_NAME)
.isVisible({ timeout: 3_000 })
.catch(() => false);
if (!stillVisible) { if (!stillVisible) {
console.log(' ✓ Client archived and removed from list'); console.log(' ✓ Client archived and removed from list');
} }

View File

@@ -1,5 +1,5 @@
import { test, expect } from '@playwright/test'; import { test, expect } from '@playwright/test';
import { login, navigateTo, PORT_SLUG } from './helpers'; import { login, navigateTo, apiHeaders, PORT_SLUG } from './helpers';
test.describe('Invoicing', () => { test.describe('Invoicing', () => {
test.beforeEach(async ({ page }) => { test.beforeEach(async ({ page }) => {
@@ -15,18 +15,40 @@ test.describe('Invoicing', () => {
}); });
test('create a new invoice with 3 line items', async ({ page }) => { test('create a new invoice with 3 line items', async ({ page }) => {
// Seed a client via API to pick in the billing-entity picker.
const clientName = `Invoice Test Client ${Date.now()}`;
const createRes = await page.request.post('/api/v1/clients', {
headers: await apiHeaders(page),
data: {
fullName: clientName,
contacts: [{ channel: 'email', value: 'billing@test.com', isPrimary: true }],
},
});
expect(createRes.ok(), `client create returned ${createRes.status()}`).toBe(true);
await navigateTo(page, '/invoices'); await navigateTo(page, '/invoices');
await page.waitForLoadState('networkidle'); await page.waitForLoadState('networkidle');
// Click "New Invoice" (use first() for strict mode) const newBtn = page
const newBtn = page.getByRole('link', { name: /new invoice/i }).first() .getByRole('link', { name: /new invoice/i })
.first()
.or(page.getByRole('button', { name: /new invoice/i }).first()); .or(page.getByRole('button', { name: /new invoice/i }).first());
await newBtn.first().click(); await newBtn.first().click();
// Step 1: Client Info
await page.waitForURL(`**/${PORT_SLUG}/invoices/new**`, { timeout: 10_000 }); await page.waitForURL(`**/${PORT_SLUG}/invoices/new**`, { timeout: 10_000 });
await page.fill('#clientName', 'Invoice Test Client'); // Step 1: pick the client in the OwnerPicker. The trigger renders as a
// button with role="combobox" and the placeholder "Select owner..." while
// empty.
const ownerTrigger = page.locator('button[role="combobox"]:has-text("Select owner")').first();
await expect(ownerTrigger).toBeVisible({ timeout: 5_000 });
await ownerTrigger.click();
const searchInput = page.getByPlaceholder(/search clients/i);
await expect(searchInput).toBeVisible({ timeout: 5_000 });
await searchInput.fill(clientName);
await page.waitForTimeout(500); // let the debounced query fire
await page.getByRole('option', { name: clientName }).first().click();
await page.fill('#billingEmail', 'billing@test.com'); await page.fill('#billingEmail', 'billing@test.com');
const dueDate = new Date(); const dueDate = new Date();
@@ -36,7 +58,6 @@ test.describe('Invoicing', () => {
await page.getByRole('button', { name: /next/i }).click(); await page.getByRole('button', { name: /next/i }).click();
await page.waitForTimeout(1000); await page.waitForTimeout(1000);
// Step 2: Line Items — add 3 items
for (let i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
await page.getByRole('button', { name: /add line item/i }).click(); await page.getByRole('button', { name: /add line item/i }).click();
await page.waitForTimeout(300); await page.waitForTimeout(300);
@@ -54,21 +75,16 @@ test.describe('Invoicing', () => {
await page.locator('input[name="lineItems.2.quantity"]').fill('4'); await page.locator('input[name="lineItems.2.quantity"]').fill('4');
await page.locator('input[name="lineItems.2.unitPrice"]').fill('500'); await page.locator('input[name="lineItems.2.unitPrice"]').fill('500');
// Verify subtotal appears (53800 formatted per locale)
await expect(page.getByText(/53[,.]?800/).first()).toBeVisible({ timeout: 5_000 }); await expect(page.getByText(/53[,.]?800/).first()).toBeVisible({ timeout: 5_000 });
// Click Next to Review await page.getByRole('button', { name: /^next$/i }).click();
await page.getByRole('button', { name: /next/i }).click(); const createBtn = page.getByRole('button', { name: /create invoice/i });
await page.waitForTimeout(1000); await expect(createBtn).toBeVisible({ timeout: 10_000 });
// Step 3: Review — verify summary
await expect(page.getByText('Invoice Test Client')).toBeVisible();
await expect(page.getByText(/53[,.]?800/).first()).toBeVisible(); await expect(page.getByText(/53[,.]?800/).first()).toBeVisible();
// Submit await createBtn.click();
await page.getByRole('button', { name: /create invoice/i }).click();
// Should redirect to invoice detail or list
await page.waitForURL( await page.waitForURL(
(url) => url.pathname.includes('/invoices') && !url.pathname.includes('/new'), (url) => url.pathname.includes('/invoices') && !url.pathname.includes('/new'),
{ timeout: 15_000 }, { timeout: 15_000 },

View File

@@ -2,63 +2,35 @@ import { test, expect } from '@playwright/test';
import { PORT_SLUG } from './helpers'; import { PORT_SLUG } from './helpers';
test.describe('Client Portal', () => { test.describe('Client Portal', () => {
// Test 34: Portal login page is separate from CRM login // Test 34: Portal login page renders the email + password form.
test('portal login page loads at separate URL', async ({ page }) => { test('portal login page shows email + password form', async ({ page }) => {
await page.goto('/login'); await page.context().clearCookies();
await page.waitForTimeout(1_000); await page.goto('/portal/login');
await page.waitForLoadState('networkidle');
// The portal login should be at a different path await expect(page.getByText(/client portal/i).first()).toBeVisible({ timeout: 5_000 });
// Try common portal paths await expect(page.locator('#email')).toBeVisible();
const portalPaths = ['/portal/login', '/login?portal=true']; await expect(page.locator('#password')).toBeVisible();
let portalFound = false; await expect(page.getByRole('button', { name: /^sign in$/i })).toBeVisible();
await expect(page.getByRole('link', { name: /forgot password/i })).toBeVisible();
for (const path of portalPaths) {
await page.goto(path);
await page.waitForTimeout(1_000);
// Check if we got a portal-specific login page
const portalHeading = page.getByText(/client portal|portal login|access your account/i).first();
if (await portalHeading.isVisible({ timeout: 3_000 }).catch(() => false)) {
portalFound = true;
break;
}
// Check for email-only input (magic link flow)
const emailInput = page.locator('#email, input[type="email"], input[placeholder*="email" i]').first();
const passwordInput = page.locator('#password, input[type="password"]').first();
const hasEmail = await emailInput.isVisible({ timeout: 2_000 }).catch(() => false);
const hasPassword = await passwordInput.isVisible({ timeout: 1_000 }).catch(() => false);
if (hasEmail && !hasPassword) {
// Magic link flow — email only, no password
portalFound = true;
break;
}
}
// Portal page should exist at one of the paths
expect(portalFound).toBeTruthy();
}); });
// Test 35: Portal authentication via magic link // Test 35: Portal sign-in with bad credentials returns 401.
test('portal accepts email for magic link', async ({ page }) => { test('portal sign-in rejects bad credentials with 401', async ({ page }) => {
await page.goto('/portal/login'); await page.context().clearCookies();
await page.waitForTimeout(1_000); const res = await page.request.post('/api/portal/auth/sign-in', {
data: { email: 'noone@example.com', password: 'definitelywrong123' },
});
expect(res.status()).toBe(401);
});
const emailInput = page.locator('input[type="email"], input[placeholder*="email" i], #email').first(); // Test 35b: Forgot-password endpoint always returns 200 (anti-enumeration).
if (await emailInput.isVisible({ timeout: 5_000 }).catch(() => false)) { test('portal forgot-password returns 200 for any email', async ({ page }) => {
await emailInput.fill('client@example.com'); await page.context().clearCookies();
const res = await page.request.post('/api/portal/auth/forgot-password', {
const submitBtn = page.getByRole('button', { name: /send|submit|access|login/i }).first(); data: { email: 'unknown@example.com' },
if (await submitBtn.isVisible({ timeout: 3_000 }).catch(() => false)) { });
await submitBtn.click(); expect(res.status()).toBe(200);
await page.waitForTimeout(3_000);
// Should show a "check your email" confirmation
const confirmation = page.getByText(/check your email|link sent|magic link/i).first();
await expect(confirmation).toBeVisible({ timeout: 5_000 });
}
}
}); });
// Test 36: Portal shows client-specific data (simulated via API) // Test 36: Portal shows client-specific data (simulated via API)
@@ -91,7 +63,10 @@ test.describe('Client Portal', () => {
const url = page.url(); const url = page.url();
const isOnLogin = url.includes('/login'); const isOnLogin = url.includes('/login');
const isOnClients = url.includes('/clients'); const isOnClients = url.includes('/clients');
const hasAuthError = await page.getByText(/authentication required|sign in/i).isVisible({ timeout: 2_000 }).catch(() => false); const hasAuthError = await page
.getByText(/authentication required|sign in/i)
.isVisible({ timeout: 2_000 })
.catch(() => false);
// If on clients page, it means we still have CRM auth from previous tests — that's expected // If on clients page, it means we still have CRM auth from previous tests — that's expected
// The key point is that portal auth (separate JWT) wouldn't grant CRM access // The key point is that portal auth (separate JWT) wouldn't grant CRM access

View File

@@ -39,7 +39,10 @@ test.describe('Critical Path: Client → Interest → Invoice', () => {
await page.waitForTimeout(2_000); await page.waitForTimeout(2_000);
// Retry if data hasn't loaded yet // Retry if data hasn't loaded yet
const hasClient = await page.getByText(TEST_CLIENT_NAME).isVisible({ timeout: 5_000 }).catch(() => false); const hasClient = await page
.getByText(TEST_CLIENT_NAME)
.isVisible({ timeout: 5_000 })
.catch(() => false);
if (!hasClient) { if (!hasClient) {
await page.waitForTimeout(3_000); await page.waitForTimeout(3_000);
} }
@@ -94,7 +97,10 @@ test.describe('Critical Path: Client → Interest → Invoice', () => {
for (let attempt = 0; attempt < 5; attempt++) { for (let attempt = 0; attempt < 5; attempt++) {
const count = await cmdItems.count(); const count = await cmdItems.count();
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
const text = await cmdItems.nth(i).textContent().catch(() => ''); const text = await cmdItems
.nth(i)
.textContent()
.catch(() => '');
if (text && text.includes('Critical Path')) { if (text && text.includes('Critical Path')) {
await cmdItems.nth(i).click(); await cmdItems.nth(i).click();
selected = true; selected = true;
@@ -161,7 +167,9 @@ test.describe('Critical Path: Client → Interest → Invoice', () => {
.or(page.getByRole('combobox').first()) .or(page.getByRole('combobox').first())
.or(page.getByRole('button', { name: /stage|pipeline/i }).first()); .or(page.getByRole('button', { name: /stage|pipeline/i }).first());
const stageSelectorVisible = await stageSelector.isVisible({ timeout: 5_000 }).catch(() => false); const stageSelectorVisible = await stageSelector
.isVisible({ timeout: 5_000 })
.catch(() => false);
if (stageSelectorVisible) { if (stageSelectorVisible) {
await stageSelector.click(); await stageSelector.click();
@@ -195,10 +203,18 @@ test.describe('Critical Path: Client → Interest → Invoice', () => {
.or(page.getByRole('button', { name: /new invoice/i }).first()); .or(page.getByRole('button', { name: /new invoice/i }).first());
await newBtn.first().click(); await newBtn.first().click();
// Step 1: Client Info
await page.waitForURL(`**/${PORT_SLUG}/invoices/new**`, { timeout: 10_000 }); await page.waitForURL(`**/${PORT_SLUG}/invoices/new**`, { timeout: 10_000 });
await page.fill('#clientName', TEST_CLIENT_NAME); // Step 1: pick the previously-created client via the OwnerPicker.
const ownerTrigger = page.locator('button[role="combobox"]:has-text("Select owner")').first();
await expect(ownerTrigger).toBeVisible({ timeout: 5_000 });
await ownerTrigger.click();
const searchInput = page.getByPlaceholder(/search clients/i);
await expect(searchInput).toBeVisible({ timeout: 5_000 });
await searchInput.fill(TEST_CLIENT_NAME);
await page.waitForTimeout(500);
await page.getByRole('option', { name: TEST_CLIENT_NAME }).first().click();
await page.fill('#billingEmail', TEST_CLIENT_EMAIL); await page.fill('#billingEmail', TEST_CLIENT_EMAIL);
const dueDate = new Date(); const dueDate = new Date();
@@ -226,14 +242,14 @@ test.describe('Critical Path: Client → Interest → Invoice', () => {
await expect(page.getByText(/52[,.]?000/).first()).toBeVisible({ timeout: 5_000 }); await expect(page.getByText(/52[,.]?000/).first()).toBeVisible({ timeout: 5_000 });
// Step 3: Review // Step 3: Review
await page.getByRole('button', { name: /next/i }).click(); await page.getByRole('button', { name: /^next$/i }).click();
await page.waitForTimeout(1_000); const createBtn = page.getByRole('button', { name: /create invoice/i });
await expect(createBtn).toBeVisible({ timeout: 10_000 });
await expect(page.getByText(TEST_CLIENT_NAME)).toBeVisible({ timeout: 5_000 });
await expect(page.getByText(/52[,.]?000/).first()).toBeVisible({ timeout: 5_000 }); await expect(page.getByText(/52[,.]?000/).first()).toBeVisible({ timeout: 5_000 });
// Submit // Submit
await page.getByRole('button', { name: /create invoice/i }).click(); await createBtn.click();
// Should redirect away from /invoices/new on success // Should redirect away from /invoices/new on success
await page.waitForURL( await page.waitForURL(

View File

@@ -21,10 +21,7 @@ export const USERS = {
* Log in as a specific user via the UI login page. * Log in as a specific user via the UI login page.
* Waits for the dashboard to load after successful login. * Waits for the dashboard to load after successful login.
*/ */
export async function login( export async function login(page: Page, role: keyof typeof USERS = 'super_admin') {
page: Page,
role: keyof typeof USERS = 'super_admin',
) {
const user = USERS[role]; const user = USERS[role];
await page.goto('/login'); await page.goto('/login');
@@ -90,3 +87,40 @@ export async function waitForSheet(page: Page) {
timeout: 5_000, timeout: 5_000,
}); });
} }
/**
* Resolve the port-nimara port ID via API.
*
* Used by tests that drive the JSON API directly with `page.request.*`.
* The server-side `withAuth` helper resolves port context from the
* `X-Port-Id` header (or the user's default-port preference), so any
* direct API call outside a port-scoped URL has to set the header. This
* caches the lookup per page so the lookup happens once.
*/
const portIdCache = new WeakMap<Page, string>();
export async function getPortId(page: Page): Promise<string> {
const cached = portIdCache.get(page);
if (cached) return cached;
const res = await page.request.get('/api/v1/admin/ports');
if (!res.ok()) {
throw new Error(`Failed to resolve port id: ${res.status()} ${await res.text()}`);
}
const body = (await res.json()) as { data?: Array<{ id: string; slug: string }> };
const port = body.data?.find((p) => p.slug === PORT_SLUG);
if (!port) {
throw new Error(`Port ${PORT_SLUG} not in admin ports response`);
}
portIdCache.set(page, port.id);
return port.id;
}
/**
* Build headers for direct JSON-API calls inside tests, including the
* `X-Port-Id` that the auth helper requires.
*/
export async function apiHeaders(page: Page): Promise<Record<string, string>> {
return {
'Content-Type': 'application/json',
'X-Port-Id': await getPortId(page),
};
}