Files
pn-new-crm/src/lib/services/crm-invite.service.ts
Matt 4b5f85cb7d fix(audit): comprehensive 2026-05-15 audit fix wave + Documenso v2 polish
Bundles the prior session's 50-task fix sweep (Documenso v2 + EOI/signing-
progress redesign + env-to-admin migration + dev-mode banner) with the
2026-05-18 audit fix wave (3 CRITICAL, 14 HIGH, 28 MEDIUM, 6 LOW).

CRITICAL (3):
 - C-01 interest-berths INNER JOIN -> LEFT JOIN so hard-deleted berths
   no longer silently drop interest links
 - C-02 /setup added to PUBLIC_PATHS; fresh-deploy bootstrap loop fixed
 - C-03 generic PATCH /interests/[id] no longer accepts pipelineStage —
   callers must go through /stage with the override-guard chain

HIGH (14/15):
 - H-01 explicit ON DELETE on previously-implicit NO ACTION FKs across
   interests/documents/reservations/reminders/invoices (migration 0070)
 - H-02 login page reads ?redirect= param with same-origin guard
 - H-03 CRM invite token moves to URL fragment so it never lands in
   nginx access logs / Referer headers
 - H-04 Retry-After header on sign-in-by-identifier 429 (RFC 6585 §4)
 - H-05 toggleAccount writes an audit row
 - H-06 upsertSetting masks any value whose key ends with _encrypted
 - H-07 archiveClient cascade fires per-interest audit rows
 - H-08 createSalesTransporter applies SMTP_TIMEOUTS
 - H-09 AppShell stable children — viewport flip across breakpoint no
   longer destroys in-progress form drafts
 - H-10 portal documents page swaps Unicode glyph status icons for
   Lucide CheckCircle2/XCircle/Circle + aria-labels
 - H-12 list components swap alert(...) for toast.warning(...)
 - H-13 5 icon-only buttons gain aria-label
 - H-14 parseBody treats empty bodies as {}
 - H-15 admin layout renders a 403 panel instead of silent bounce
 - H-11 not applicable — mobile-search-overlay IS a mobile bottom-sheet

MEDIUM (28+):
 - M-MT01-05 defense-in-depth port_id/parent-id filters on UPDATE/DELETE
   WHEREs across custom-fields, notes (all 6 entity types x update +
   delete), client-contacts, yacht ownerClient lookup, webhook reads
 - M-D01 documents-hub realtime event-name typo (file:created -> uploaded)
 - M-EM01 portal-auth emails thread through portId
 - M-EM02 sendEmail accepts cc/bcc params
 - M-EM04 notification_digest catalog key
 - M-IN01 portal presigned download URLs use 4h TTL
 - M-IN02 OpenAI client lazy-instantiated
 - M-IN04 stale pdfme refs updated to pdf-lib AcroForm
 - M-IN05 umami.testConnection returns tagged union
 - M-L01 reservations tenure_type unified with berths
 - M-L02 report-generators canonicalize stage values
 - M-AU01 audit log placeholder copy fixed
 - M-AU04 outcome_set / outcome_cleared distinct audit verbs
 - M-NEW-2 activity feed entity name+type separator
 - M-R01 portal allowlist narrowed + portal_session backstop in proxy
 - M-SC02 companies archived partial index
 - M-SC04 audit_logs.searchText documented as DB-managed
 - M-S01 storage_s3_access_key_encrypted admin field
 - M-U01 audit log empty state uses <EmptyState>
 - M-U09 invoice delete dialog -> <AlertDialog>
 - M-U10 toast.success on ClientForm + InterestForm create/edit
 - M-U11 settings-form-card logo preview alt text
 - M-U14 mobile topbar title on clients/yachts/interests/berths
 - M-U15 Invoices in mobile More-sheet

LOW (6/8):
 - L-AU01 severity defaults for security-relevant verbs
 - L-AU02 +13 missing actions in admin audit filter
 - L-AU03 +7 missing entity types in admin audit filter
 - L-AU04 dead listAuditLogs stubbed
 - L-D02 CLAUDE.md Owner-wins chain tightened

Bonus — Document detail polish (#67 partial, 3/6 deliverables):
 - state-aware action button per signer
 - watcher Add UI with display-name resolution
 - cleanSignerName cleanup

Prior session work bundled in:
 - Documenso v2 webhook + envelope-ID normalization + sequential signing
 - SigningProgress UI redesign (avatars, per-signer state, timestamps)
 - env->admin settings registry + RegistryDrivenForm + encrypted creds
 - Embedded-signing card + Test connection + setup help
 - Dev-mode EMAIL_REDIRECT_TO banner
 - Pipeline rules admin page
 - Sales email config card
 - Audit log details Sheet
 - EOI tab: Finalising badge, absolute timestamps, sequential indicator
 - Notes pipeline_stage_at_creation (migration 0069)
 - Documenso numeric ID dual-key webhook (migration 0068)
 - Dimensions criterion copy (migration 0067)

Tests: 1374/1374 vitest pass. tsc clean. lint clean.

See docs/AUDIT-FIX-WAVE-2026-05-18.md for the full progress report and
the user-input items still pending.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 13:28:50 +02:00

281 lines
8.9 KiB
TypeScript

import { and, desc, eq, gt, isNull } from 'drizzle-orm';
import postgres from 'postgres';
import { auth } from '@/lib/auth';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { db } from '@/lib/db';
import { crmUserInvites } from '@/lib/db/schema/crm-invites';
import { userProfiles } from '@/lib/db/schema/users';
import { env } from '@/lib/env';
import { sendEmail } from '@/lib/email';
import { crmInviteEmail } from '@/lib/email/templates/crm-invite';
import { resolveSubject } from '@/lib/email/resolve-subject';
import { getBrandingShell } from '@/lib/email/branding-resolver';
import { CodedError, ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
import { hashToken, mintToken } from '@/lib/portal/passwords';
const INVITE_TTL_HOURS = 72;
const MIN_PASSWORD_LENGTH = 9;
export async function createCrmInvite(args: {
email: string;
name?: string;
isSuperAdmin?: boolean;
/**
* Caller identity. Required when minting a super-admin invitation so the
* service can fail closed if the caller isn't already a super-admin -
* defense-in-depth for the route's authorization gate.
*/
invitedBy?: { userId: string; isSuperAdmin: boolean };
}): Promise<{ inviteId: string; link: string }> {
const email = args.email.toLowerCase().trim();
const isSuperAdmin = args.isSuperAdmin ?? false;
if (isSuperAdmin && !args.invitedBy?.isSuperAdmin) {
throw new ValidationError('Only super admins can mint super-admin invitations');
}
// Reject if there's already a better-auth user with this email - they
// should reset their password instead.
const sql = postgres(env.DATABASE_URL);
try {
const existing = await sql<{ id: string }[]>`
SELECT id FROM "user" WHERE email = ${email} LIMIT 1
`;
if (existing.length > 0) {
throw new ConflictError(`A CRM user already exists for ${email}`);
}
} finally {
await sql.end();
}
const { raw, hash } = mintToken();
const expiresAt = new Date(Date.now() + INVITE_TTL_HOURS * 3600 * 1000);
const [row] = await db
.insert(crmUserInvites)
.values({
email,
name: args.name ?? null,
tokenHash: hash,
isSuperAdmin,
expiresAt,
})
.returning({ id: crmUserInvites.id });
if (!row)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to create CRM invite',
});
// H-03: token moves to the URL fragment so it never lands in nginx/Caddy
// access logs (or any HTTP-Referer-leaking middlebox). The fragment is
// browser-only; the server only sees the path. set-password/page.tsx
// reads either `#token=` or `?token=` (back-compat for outstanding
// links). encodeURIComponent guards against `#`/`&` in the token.
const link = `${env.APP_URL}/set-password#token=${encodeURIComponent(raw)}`;
const result = await crmInviteEmail({
link,
ttlHours: INVITE_TTL_HOURS,
recipientName: args.name,
isSuperAdmin,
});
// CRM invites are global (no portId at create-invite time). The
// override resolver returns the fallback when portId is null.
const subject = await resolveSubject({
key: 'crm_invite',
portId: null,
fallback: result.subject,
tokens: {
portName: 'Port Nimara',
recipientName: args.name ?? '',
ttlHours: INVITE_TTL_HOURS,
},
});
await sendEmail(email, subject, result.html, undefined, result.text);
return { inviteId: row.id, link };
}
export async function consumeCrmInvite(args: {
token: string;
password: string;
}): Promise<{ userId: string; email: string }> {
if (args.password.length < MIN_PASSWORD_LENGTH) {
throw new ValidationError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`);
}
const tokenHash = hashToken(args.token);
const invite = await db.query.crmUserInvites.findFirst({
where: and(
eq(crmUserInvites.tokenHash, tokenHash),
isNull(crmUserInvites.usedAt),
gt(crmUserInvites.expiresAt, new Date()),
),
});
if (!invite) {
throw new NotFoundError('Invite link is invalid or has expired');
}
// Create the better-auth user with the chosen password.
const result = await auth.api.signUpEmail({
body: {
email: invite.email,
password: args.password,
name: invite.name ?? invite.email.split('@')[0] ?? 'User',
},
});
const userId = result.user.id;
// Create the matching user_profiles extension row.
await db
.insert(userProfiles)
.values({
id: crypto.randomUUID(),
userId,
displayName: invite.name ?? invite.email,
isSuperAdmin: invite.isSuperAdmin,
isActive: true,
preferences: {},
})
.onConflictDoNothing();
await db
.update(crmUserInvites)
.set({ usedAt: new Date() })
.where(eq(crmUserInvites.id, invite.id));
return { userId, email: invite.email };
}
// ─── Admin operations ────────────────────────────────────────────────────────
export interface InviteRow {
id: string;
email: string;
name: string | null;
isSuperAdmin: boolean;
expiresAt: Date;
usedAt: Date | null;
createdAt: Date;
status: 'pending' | 'accepted' | 'expired';
}
export async function listCrmInvites(): Promise<InviteRow[]> {
const rows = await db
.select({
id: crmUserInvites.id,
email: crmUserInvites.email,
name: crmUserInvites.name,
isSuperAdmin: crmUserInvites.isSuperAdmin,
expiresAt: crmUserInvites.expiresAt,
usedAt: crmUserInvites.usedAt,
createdAt: crmUserInvites.createdAt,
})
.from(crmUserInvites)
.orderBy(desc(crmUserInvites.createdAt))
.limit(200);
const now = Date.now();
return rows.map((r) => {
let status: InviteRow['status'];
if (r.usedAt) status = 'accepted';
else if (r.expiresAt.getTime() < now) status = 'expired';
else status = 'pending';
return { ...r, status };
});
}
export async function revokeCrmInvite(inviteId: string, meta: AuditMeta): Promise<void> {
const invite = await db.query.crmUserInvites.findFirst({
where: eq(crmUserInvites.id, inviteId),
});
if (!invite) throw new NotFoundError('Invite');
if (invite.usedAt) throw new ConflictError('Invite already accepted - cannot revoke');
// Force expiration; tokenHash stays in place so any in-flight click fails
// the `expiresAt > now` check at consume time.
await db
.update(crmUserInvites)
.set({ expiresAt: new Date(0) })
.where(eq(crmUserInvites.id, inviteId));
void createAuditLog({
userId: meta.userId,
portId: meta.portId,
action: 'revoke_invite',
entityType: 'crm_invite',
entityId: inviteId,
metadata: { email: invite.email },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
}
export async function resendCrmInvite(
inviteId: string,
meta: AuditMeta,
): Promise<{ link: string }> {
const invite = await db.query.crmUserInvites.findFirst({
where: eq(crmUserInvites.id, inviteId),
});
if (!invite) throw new NotFoundError('Invite');
if (invite.usedAt) throw new ConflictError('Invite already accepted - nothing to resend');
// Mint a fresh token + push expiry forward so the resent link is the only
// working one. The old token hash is overwritten so prior emails become
// dead links.
const { raw, hash } = mintToken();
const expiresAt = new Date(Date.now() + INVITE_TTL_HOURS * 3600 * 1000);
await db
.update(crmUserInvites)
.set({ tokenHash: hash, expiresAt })
.where(eq(crmUserInvites.id, inviteId));
// H-03: token moves to the URL fragment so it never lands in nginx/Caddy
// access logs (or any HTTP-Referer-leaking middlebox). The fragment is
// browser-only; the server only sees the path. set-password/page.tsx
// reads either `#token=` or `?token=` (back-compat for outstanding
// links). encodeURIComponent guards against `#`/`&` in the token.
const link = `${env.APP_URL}/set-password#token=${encodeURIComponent(raw)}`;
const branding = await getBrandingShell(meta.portId);
const result = await crmInviteEmail(
{
link,
ttlHours: INVITE_TTL_HOURS,
recipientName: invite.name ?? undefined,
isSuperAdmin: invite.isSuperAdmin,
},
{ branding },
);
// Resend uses the dedicated portal_invite_resend key so admins can
// word the resend differently from the original.
const subject = await resolveSubject({
key: 'portal_invite_resend',
portId: meta.portId ?? null,
fallback: result.subject,
tokens: {
portName: 'Port Nimara',
recipientName: invite.name ?? '',
ttlHours: INVITE_TTL_HOURS,
},
});
await sendEmail(invite.email, subject, result.html, undefined, result.text, meta.portId);
void createAuditLog({
userId: meta.userId,
portId: meta.portId,
action: 'resend_invite',
entityType: 'crm_invite',
entityId: inviteId,
metadata: { email: invite.email },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
return { link };
}