Files
pn-new-crm/src/lib/services/reminders.service.ts
Matt Ciaccio 4eea19a85b sec: lock down 5 cross-tenant FK gaps from fifth-pass review
1. HIGH — reminders.create/updateReminder accepted clientId/interestId/
   berthId from the body and persisted them with no port check; getReminder
   then hydrated the row via Drizzle relations (no port filter on the
   join), so a port-A user with reminders:create could exfiltrate any
   port-B client/interest/berth row by guessing its UUID. New
   assertReminderFksInPort gates create + update.

2. HIGH — listRecommendations(interestId, _portId) discarded portId
   entirely; the route GET /api/v1/interests/[id]/recommendations
   forwarded the URL id straight through. A port-A user with
   interests:view could read any other tenant's recommended berths
   (mooring numbers, dimensions, status). Service now verifies the
   interest belongs to portId and joins berths filtered by port.

3. HIGH — Berth waiting list. The PATCH route did not pre-check that
   the berth belonged to ctx.portId — a port-A user with
   manage_waiting_list could reorder a port-B berth's queue. Separately,
   updateWaitingList accepted arbitrary entries[].clientId and inserted
   them without verifying tenancy, polluting the table with foreign-port
   FKs. Both gaps closed.

4. MEDIUM — setEntityTags (clients/companies/yachts/interests/berths)
   accepted any tagId and inserted into the join table. The tags table
   is per-port but the join only carries a single-column FK. The
   downstream getById join `tags ON join.tag_id = tags.id` has no port
   filter, so a foreign tag's name + color render in the requesting port.
   Helper now batch-validates tagIds belong to portId before insert.

5. MEDIUM — /api/v1/custom-fields/[entityId] PUT had no withPermission
   gate (any role, including viewer, could write) and didn't validate
   that the URL entityId pointed at a port-scoped entity of the field
   definition's entityType. Route now uses
   withPermission('clients','view'/'edit',…); service validates the
   entityId per resolved entityType (client/interest/berth/yacht/company)
   against portId.

Test mocks updated to cover the new entity-port-scope check.
818 vitest tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 03:28:31 +02:00

520 lines
16 KiB
TypeScript

import { and, eq, lte, gte, desc, asc, inArray, sql, isNull } from 'drizzle-orm';
import { db } from '@/lib/db';
import { reminders, interests, clients } from '@/lib/db/schema';
import { berths } from '@/lib/db/schema/berths';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { NotFoundError, ValidationError } from '@/lib/errors';
import { emitToRoom } from '@/lib/socket/server';
import { createNotification } from '@/lib/services/notifications.service';
import { logger } from '@/lib/logger';
import type {
CreateReminderInput,
UpdateReminderInput,
SnoozeReminderInput,
ReminderListQuery,
} from '@/lib/validators/reminders';
// ─── List ────────────────────────────────────────────────────────────────────
export async function listReminders(portId: string, query: ReminderListQuery) {
const conditions = [eq(reminders.portId, portId)];
if (query.status) conditions.push(eq(reminders.status, query.status));
if (query.priority) conditions.push(eq(reminders.priority, query.priority));
if (query.assignedTo) conditions.push(eq(reminders.assignedTo, query.assignedTo));
if (query.clientId) conditions.push(eq(reminders.clientId, query.clientId));
if (query.interestId) conditions.push(eq(reminders.interestId, query.interestId));
if (query.berthId) conditions.push(eq(reminders.berthId, query.berthId));
if (query.dueBefore) conditions.push(lte(reminders.dueAt, new Date(query.dueBefore)));
if (query.dueAfter) conditions.push(gte(reminders.dueAt, new Date(query.dueAfter)));
if (query.search) {
conditions.push(sql`${reminders.title} ILIKE ${'%' + query.search + '%'}`);
}
const orderDir = query.order === 'asc' ? asc : desc;
const orderCol = query.sort === 'priority' ? reminders.priority : reminders.dueAt;
const offset = (query.page - 1) * query.limit;
const [data, countResult] = await Promise.all([
db
.select()
.from(reminders)
.where(and(...conditions))
.orderBy(orderDir(orderCol))
.limit(query.limit)
.offset(offset),
db
.select({ count: sql<number>`count(*)` })
.from(reminders)
.where(and(...conditions)),
]);
return {
data,
pagination: {
page: query.page,
limit: query.limit,
total: Number(countResult[0]?.count ?? 0),
},
};
}
export async function getMyReminders(userId: string, portId: string) {
return db
.select()
.from(reminders)
.where(
and(
eq(reminders.portId, portId),
eq(reminders.assignedTo, userId),
inArray(reminders.status, ['pending', 'snoozed']),
),
)
.orderBy(asc(reminders.dueAt));
}
export async function getOverdueReminders(portId: string) {
return db
.select()
.from(reminders)
.where(
and(
eq(reminders.portId, portId),
inArray(reminders.status, ['pending', 'snoozed']),
lte(reminders.dueAt, new Date()),
),
)
.orderBy(asc(reminders.dueAt));
}
export async function getUpcomingReminders(portId: string, days: number = 14) {
const until = new Date();
until.setDate(until.getDate() + days);
return db
.select()
.from(reminders)
.where(
and(
eq(reminders.portId, portId),
inArray(reminders.status, ['pending', 'snoozed']),
lte(reminders.dueAt, until),
gte(reminders.dueAt, new Date()),
),
)
.orderBy(asc(reminders.dueAt));
}
/**
* Validate that the supplied subject FKs (clientId / interestId / berthId)
* all point at rows inside the caller's port. Without this guard, a
* reminder created with a foreign-port FK would later be hydrated with
* `with: { client, interest, berth }` joins (no port filter on the
* relation) — leaking the foreign-tenant rows back to the attacker.
*/
async function assertReminderFksInPort(
portId: string,
fks: { clientId?: string | null; interestId?: string | null; berthId?: string | null },
): Promise<void> {
const checks: Array<Promise<void>> = [];
if (fks.clientId) {
checks.push(
db.query.clients
.findFirst({ where: and(eq(clients.id, fks.clientId), eq(clients.portId, portId)) })
.then((row) => {
if (!row) throw new ValidationError('clientId not found in this port');
}),
);
}
if (fks.interestId) {
checks.push(
db.query.interests
.findFirst({
where: and(eq(interests.id, fks.interestId), eq(interests.portId, portId)),
})
.then((row) => {
if (!row) throw new ValidationError('interestId not found in this port');
}),
);
}
if (fks.berthId) {
checks.push(
db.query.berths
.findFirst({ where: and(eq(berths.id, fks.berthId), eq(berths.portId, portId)) })
.then((row) => {
if (!row) throw new ValidationError('berthId not found in this port');
}),
);
}
await Promise.all(checks);
}
// ─── CRUD ────────────────────────────────────────────────────────────────────
export async function getReminder(id: string, portId: string) {
const reminder = await db.query.reminders.findFirst({
where: and(eq(reminders.id, id), eq(reminders.portId, portId)),
with: { client: true, interest: true, berth: true },
});
if (!reminder) throw new NotFoundError('Reminder');
return reminder;
}
export async function createReminder(portId: string, data: CreateReminderInput, meta: AuditMeta) {
await assertReminderFksInPort(portId, {
clientId: data.clientId,
interestId: data.interestId,
berthId: data.berthId,
});
const [reminder] = await db
.insert(reminders)
.values({
portId,
title: data.title,
note: data.note ?? null,
dueAt: new Date(data.dueAt),
priority: data.priority,
assignedTo: data.assignedTo ?? meta.userId,
createdBy: meta.userId,
clientId: data.clientId ?? null,
interestId: data.interestId ?? null,
berthId: data.berthId ?? null,
})
.returning();
void createAuditLog({
userId: meta.userId,
portId,
action: 'create',
entityType: 'reminder',
entityId: reminder!.id,
newValue: { title: reminder!.title, dueAt: reminder!.dueAt, priority: reminder!.priority },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'reminder:created', {
reminderId: reminder!.id,
title: reminder!.title,
dueAt: reminder!.dueAt.toISOString(),
assignedTo: reminder!.assignedTo ?? meta.userId,
});
if (reminder!.assignedTo) {
emitToRoom(`user:${reminder!.assignedTo}`, 'reminder:created', {
reminderId: reminder!.id,
title: reminder!.title,
dueAt: reminder!.dueAt.toISOString(),
assignedTo: reminder!.assignedTo,
});
}
return reminder!;
}
export async function updateReminder(
id: string,
portId: string,
data: UpdateReminderInput,
meta: AuditMeta,
) {
const existing = await db.query.reminders.findFirst({
where: and(eq(reminders.id, id), eq(reminders.portId, portId)),
});
if (!existing) throw new NotFoundError('Reminder');
const updates: Record<string, unknown> = { updatedAt: new Date() };
if (data.title !== undefined) updates.title = data.title;
if (data.note !== undefined) updates.note = data.note;
if (data.dueAt !== undefined) updates.dueAt = new Date(data.dueAt);
if (data.priority !== undefined) updates.priority = data.priority;
if (data.assignedTo !== undefined) updates.assignedTo = data.assignedTo;
if (data.clientId !== undefined) updates.clientId = data.clientId;
if (data.interestId !== undefined) updates.interestId = data.interestId;
if (data.berthId !== undefined) updates.berthId = data.berthId;
// Re-validate any subject-FK changes against the caller's port.
await assertReminderFksInPort(portId, {
clientId: data.clientId,
interestId: data.interestId,
berthId: data.berthId,
});
const [updated] = await db
.update(reminders)
.set(updates)
.where(and(eq(reminders.id, id), eq(reminders.portId, portId)))
.returning();
void createAuditLog({
userId: meta.userId,
portId,
action: 'update',
entityType: 'reminder',
entityId: id,
oldValue: { title: existing.title, dueAt: existing.dueAt, priority: existing.priority },
newValue: { title: updated!.title, dueAt: updated!.dueAt, priority: updated!.priority },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'reminder:updated', {
reminderId: updated!.id,
changedFields: Object.keys(data),
});
return updated!;
}
export async function deleteReminder(id: string, portId: string, meta: AuditMeta) {
const existing = await db.query.reminders.findFirst({
where: and(eq(reminders.id, id), eq(reminders.portId, portId)),
});
if (!existing) throw new NotFoundError('Reminder');
await db.delete(reminders).where(and(eq(reminders.id, id), eq(reminders.portId, portId)));
void createAuditLog({
userId: meta.userId,
portId,
action: 'delete',
entityType: 'reminder',
entityId: id,
oldValue: { title: existing.title },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
}
// ─── Status Actions ──────────────────────────────────────────────────────────
export async function completeReminder(id: string, portId: string, meta: AuditMeta) {
const existing = await db.query.reminders.findFirst({
where: and(eq(reminders.id, id), eq(reminders.portId, portId)),
});
if (!existing) throw new NotFoundError('Reminder');
if (existing.status === 'completed') throw new ValidationError('Reminder already completed');
const [updated] = await db
.update(reminders)
.set({
status: 'completed',
completedAt: new Date(),
updatedAt: new Date(),
})
.where(and(eq(reminders.id, id), eq(reminders.portId, portId)))
.returning();
void createAuditLog({
userId: meta.userId,
portId,
action: 'update',
entityType: 'reminder',
entityId: id,
oldValue: { status: existing.status },
newValue: { status: 'completed' },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'reminder:completed', {
reminderId: updated!.id,
title: updated!.title,
completedBy: meta.userId,
});
return updated!;
}
export async function snoozeReminder(
id: string,
portId: string,
data: SnoozeReminderInput,
meta: AuditMeta,
) {
const existing = await db.query.reminders.findFirst({
where: and(eq(reminders.id, id), eq(reminders.portId, portId)),
});
if (!existing) throw new NotFoundError('Reminder');
const [updated] = await db
.update(reminders)
.set({
status: 'snoozed',
snoozedUntil: new Date(data.snoozeUntil),
updatedAt: new Date(),
})
.where(and(eq(reminders.id, id), eq(reminders.portId, portId)))
.returning();
void createAuditLog({
userId: meta.userId,
portId,
action: 'update',
entityType: 'reminder',
entityId: id,
oldValue: { status: existing.status },
newValue: { status: 'snoozed', snoozedUntil: data.snoozeUntil },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'reminder:snoozed', {
reminderId: updated!.id,
snoozedUntil: data.snoozeUntil,
});
return updated!;
}
export async function dismissReminder(id: string, portId: string, meta: AuditMeta) {
const existing = await db.query.reminders.findFirst({
where: and(eq(reminders.id, id), eq(reminders.portId, portId)),
});
if (!existing) throw new NotFoundError('Reminder');
const [updated] = await db
.update(reminders)
.set({ status: 'dismissed', updatedAt: new Date() })
.where(and(eq(reminders.id, id), eq(reminders.portId, portId)))
.returning();
void createAuditLog({
userId: meta.userId,
portId,
action: 'update',
entityType: 'reminder',
entityId: id,
oldValue: { status: existing.status },
newValue: { status: 'dismissed' },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
return updated!;
}
// ─── Background Processors ──────────────────────────────────────────────────
/**
* Hourly check: creates auto-follow-up reminders for interests with
* reminderEnabled=true where no activity in reminderDays days (BR-060).
*/
export async function processFollowUpReminders() {
const ports = await db.query.ports.findMany({ where: eq(sql`true`, true) });
for (const port of ports) {
const enabledInterests = await db
.select({
id: interests.id,
clientId: interests.clientId,
reminderDays: interests.reminderDays,
reminderLastFired: interests.reminderLastFired,
updatedAt: interests.updatedAt,
})
.from(interests)
.where(
and(
eq(interests.portId, port.id),
eq(interests.reminderEnabled, true),
isNull(interests.archivedAt),
),
);
const now = new Date();
for (const interest of enabledInterests) {
if (!interest.reminderDays) continue;
// Check if enough days have passed since last activity
const lastActivity = interest.reminderLastFired ?? interest.updatedAt;
const daysSinceActivity = (now.getTime() - lastActivity.getTime()) / (1000 * 60 * 60 * 24);
if (daysSinceActivity < interest.reminderDays) continue;
// Get client name for the reminder title
const client = interest.clientId
? await db.query.clients.findFirst({ where: eq(clients.id, interest.clientId) })
: null;
const title = client ? `Follow up with ${client.fullName}` : 'Follow up on interest';
// Find the assigned user (first userPortRole for this port, or fallback)
// For now, leave assignedTo null — the notification goes to the port room
await db.insert(reminders).values({
portId: port.id,
title,
note: 'Auto-generated: no activity detected within the configured follow-up window.',
dueAt: now,
priority: 'medium',
assignedTo: null,
createdBy: 'system',
interestId: interest.id,
clientId: interest.clientId,
autoGenerated: true,
});
// Update last fired timestamp
await db
.update(interests)
.set({ reminderLastFired: now })
.where(eq(interests.id, interest.id));
// Fire notification to the port room
emitToRoom(`port:${port.id}`, 'system:alert', {
alertType: 'follow_up_created',
message: title,
severity: 'info',
});
logger.info({ interestId: interest.id, portId: port.id }, 'Auto follow-up reminder created');
}
}
}
/**
* Every 15 minutes: checks for past-due reminders and creates overdue notifications.
*/
export async function processOverdueReminders() {
const now = new Date();
// Find pending reminders past their due date
const overdueReminders = await db
.select()
.from(reminders)
.where(and(eq(reminders.status, 'pending'), lte(reminders.dueAt, now)));
for (const reminder of overdueReminders) {
if (reminder.assignedTo) {
void createNotification({
portId: reminder.portId,
userId: reminder.assignedTo,
type: 'reminder_overdue',
title: 'Reminder overdue',
description: reminder.title,
entityType: 'reminder',
entityId: reminder.id,
link: '/reminders',
});
emitToRoom(`user:${reminder.assignedTo}`, 'reminder:overdue', {
reminderId: reminder.id,
title: reminder.title,
dueAt: reminder.dueAt.toISOString(),
});
}
}
// Also un-snooze reminders whose snooze period has passed
await db
.update(reminders)
.set({ status: 'pending', snoozedUntil: null, updatedAt: now })
.where(and(eq(reminders.status, 'snoozed'), lte(reminders.snoozedUntil, now)));
logger.info({ overdueCount: overdueReminders.length }, 'Processed overdue reminders');
}