fix(audit-v2): platform-wide post-merge hardening across 5 domains
Five-domain audit (security, routes, DB, integrations, UI/UX) ran after
the cf37d09 merge. Critical + high-impact items landed here; deferred
medium/low items indexed in docs/audit-final-deferred.md (now organised
into a "Audit-final v2" section).
Security:
- Storage proxy tokens now bind to op (`'get'` vs `'put'`). A long-lived
download URL minted by `presignDownload` for an emailed brochure can no
longer be replayed against the proxy PUT to overwrite the original
storage object. `verifyProxyToken` requires `expectedOp` and rejects
mismatches; legacy tokens missing `op` fail-closed. Regression tests
added.
- Markdown email merge values are now markdown-escaped (`[`, `]`, `(`,
`)`, `*`, `_`, `\`, backticks, braces) before substitution into the
rep-authored body. A malicious value like `[click here](https://evil)`
stored in `client.fullName` no longer survives `escapeHtml` to render
as a real `<a href>` in the outbound email. Phishing-via-merge-field
closed; regression tests added.
- Middleware now performs an Origin/Referer check on
POST/PUT/PATCH/DELETE to `/api/v1/**`. Defense-in-depth on top of
better-auth's SameSite=Lax cookie. Webhooks/public/auth/portal routes
exempt as they don't carry the session cookie.
Routes:
- Template management routes were calling `withPermission('documents',
'manage', ...)` — but `documents` doesn't have a `manage` action. The
registry has `document_templates.manage`. Every non-superadmin was
getting 403'd on the seven template endpoints. Fixed across the
/admin/templates surface.
- Custom-fields permission resource is hardcoded to `clients` regardless
of which entity (yacht/company/etc.) the values belong to. Documented
as deferred (requires per-entity routes).
DB:
- documentSends: every parent FK (client_id, interest_id, berth_id,
brochure_id, brochure_version_id) now uses ON DELETE SET NULL so the
audit trail outlasts hard-deletes. The denormalized columns
(recipient_email, document_kind, body_markdown, from_address) were
added precisely for this. Migration 0035.
- Polymorphic discriminators on yachts.current_owner_type and
invoices.billing_entity_type now have CHECK constraints — typos like
`'clients'` vs `'client'` were silently inserting unreachable rows
before. Migration 0036.
Integrations:
- Email attachment resolution (`src/lib/email/index.ts`) was importing
MinIO directly instead of `getStorageBackend()`. Filesystem-backend
deployments would have broken every email-with-attachment send. Now
routes through the pluggable abstraction per CLAUDE.md.
- Documenso DOCUMENT_OPENED webhook filter relaxed: v2 may omit
`readStatus` or send lowercase, so an event that was the SIGNAL of an
open was being silently dropped. Now treats any recipient on a
DOCUMENT_OPENED event as opened.
UI/UX:
- Expense detail used to render `receiptFileIds` as opaque UUID badges —
reps couldn't view the receipt they uploaded. Now renders an image
thumbnail (via `/api/v1/files/[id]/preview`) plus a Download link for
PDFs. Closed the "where's my receipt?" loop in the expense flow.
- Expense detail Edit + Archive buttons now `<PermissionGate>` and the
archive mutation surfaces success/error toasts instead of silent 403s.
- Brochures admin: setDefault/archive/create mutations now have onError
toasts (only onSuccess existed before).
- Removed broken bulk-upload link in scan/page (route doesn't exist;
used a raw `<a>` triggering a full reload to a 404).
Test status: 1168/1168 vitest passing. tsc clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -241,15 +241,6 @@ export default function ScanReceiptPage() {
|
||||
<p className="text-xs text-muted-foreground sm:col-span-2 text-center">
|
||||
JPEG, PNG, HEIC, WebP up to 10 MB
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground sm:col-span-2 text-center">
|
||||
Have many receipts?{' '}
|
||||
<a
|
||||
href={`/${params.portSlug}/expenses/bulk-upload`}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
Bulk upload →
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{/* `image/*` is the broadest accept — includes HEIC on iOS,
|
||||
|
||||
@@ -52,7 +52,7 @@ export async function GET(
|
||||
);
|
||||
}
|
||||
|
||||
const result = verifyProxyToken(token, backend.getHmacSecret());
|
||||
const result = verifyProxyToken(token, backend.getHmacSecret(), 'get');
|
||||
if (!result.ok) {
|
||||
logger.warn({ reason: result.reason }, 'Storage proxy token rejected');
|
||||
return NextResponse.json({ error: 'Invalid or expired token' }, { status: 403 });
|
||||
@@ -145,7 +145,7 @@ export async function PUT(
|
||||
);
|
||||
}
|
||||
|
||||
const result = verifyProxyToken(token, backend.getHmacSecret());
|
||||
const result = verifyProxyToken(token, backend.getHmacSecret(), 'put');
|
||||
if (!result.ok) {
|
||||
logger.warn({ reason: result.reason }, 'Storage proxy upload token rejected');
|
||||
return NextResponse.json({ error: 'Invalid or expired token' }, { status: 403 });
|
||||
|
||||
@@ -14,7 +14,7 @@ import { rollbackAdminTemplateSchema } from '@/lib/validators/document-templates
|
||||
* Body: { version: number }
|
||||
*/
|
||||
export const POST = withAuth(
|
||||
withPermission('documents', 'manage', async (req, ctx, params) => {
|
||||
withPermission('document_templates', 'manage', async (req, ctx, params) => {
|
||||
try {
|
||||
const body = await parseBody(req, rollbackAdminTemplateSchema);
|
||||
const result = await rollbackAdminTemplate(
|
||||
|
||||
@@ -15,7 +15,7 @@ import { updateAdminTemplateSchema } from '@/lib/validators/document-templates';
|
||||
* Retrieve a single TipTap-based document template.
|
||||
*/
|
||||
export const GET = withAuth(
|
||||
withPermission('documents', 'manage', async (req, ctx, params) => {
|
||||
withPermission('document_templates', 'manage', async (req, ctx, params) => {
|
||||
try {
|
||||
const template = await getAdminTemplate(ctx.portId, params.templateId!);
|
||||
return NextResponse.json({ data: template });
|
||||
@@ -30,21 +30,15 @@ export const GET = withAuth(
|
||||
* Update a TipTap-based document template. Increments version if content changes.
|
||||
*/
|
||||
export const PATCH = withAuth(
|
||||
withPermission('documents', 'manage', async (req, ctx, params) => {
|
||||
withPermission('document_templates', 'manage', async (req, ctx, params) => {
|
||||
try {
|
||||
const body = await parseBody(req, updateAdminTemplateSchema);
|
||||
const updated = await updateAdminTemplate(
|
||||
ctx.portId,
|
||||
params.templateId!,
|
||||
ctx.userId,
|
||||
body,
|
||||
{
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
},
|
||||
);
|
||||
const updated = await updateAdminTemplate(ctx.portId, params.templateId!, ctx.userId, body, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ data: updated });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
@@ -57,19 +51,14 @@ export const PATCH = withAuth(
|
||||
* Delete a TipTap-based document template.
|
||||
*/
|
||||
export const DELETE = withAuth(
|
||||
withPermission('documents', 'manage', async (req, ctx, params) => {
|
||||
withPermission('document_templates', 'manage', async (req, ctx, params) => {
|
||||
try {
|
||||
await deleteAdminTemplate(
|
||||
ctx.portId,
|
||||
params.templateId!,
|
||||
ctx.userId,
|
||||
{
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
},
|
||||
);
|
||||
await deleteAdminTemplate(ctx.portId, params.templateId!, ctx.userId, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return new NextResponse(null, { status: 204 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
|
||||
@@ -9,12 +9,9 @@ import { getAdminTemplateVersions } from '@/lib/services/document-templates.serv
|
||||
* Returns version history for a template, sourced from audit_logs.
|
||||
*/
|
||||
export const GET = withAuth(
|
||||
withPermission('documents', 'manage', async (req, ctx, params) => {
|
||||
withPermission('document_templates', 'manage', async (req, ctx, params) => {
|
||||
try {
|
||||
const versions = await getAdminTemplateVersions(
|
||||
ctx.portId,
|
||||
params.templateId!,
|
||||
);
|
||||
const versions = await getAdminTemplateVersions(ctx.portId, params.templateId!);
|
||||
return NextResponse.json({ data: versions });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
|
||||
@@ -25,7 +25,7 @@ import { previewAdminTemplateSchema } from '@/lib/validators/document-templates'
|
||||
* sampleData?: Record<string, string> - variable substitutions
|
||||
*/
|
||||
export const POST = withAuth(
|
||||
withPermission('documents', 'manage', async (req, _ctx) => {
|
||||
withPermission('document_templates', 'manage', async (req, _ctx) => {
|
||||
try {
|
||||
const body = await parseBody(req, previewAdminTemplateSchema);
|
||||
|
||||
|
||||
@@ -3,10 +3,7 @@ import { NextResponse } from 'next/server';
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { parseQuery, parseBody } from '@/lib/api/route-helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import {
|
||||
listAdminTemplates,
|
||||
createAdminTemplate,
|
||||
} from '@/lib/services/document-templates.service';
|
||||
import { listAdminTemplates, createAdminTemplate } from '@/lib/services/document-templates.service';
|
||||
import {
|
||||
listAdminTemplatesSchema,
|
||||
createAdminTemplateSchema,
|
||||
@@ -17,7 +14,7 @@ import {
|
||||
* List TipTap-based document templates for the port.
|
||||
*/
|
||||
export const GET = withAuth(
|
||||
withPermission('documents', 'manage', async (req, ctx) => {
|
||||
withPermission('document_templates', 'manage', async (req, ctx) => {
|
||||
try {
|
||||
const query = parseQuery(req, listAdminTemplatesSchema);
|
||||
const data = await listAdminTemplates(ctx.portId, query);
|
||||
@@ -33,7 +30,7 @@ export const GET = withAuth(
|
||||
* Create a new TipTap-based document template.
|
||||
*/
|
||||
export const POST = withAuth(
|
||||
withPermission('documents', 'manage', async (req, ctx) => {
|
||||
withPermission('document_templates', 'manage', async (req, ctx) => {
|
||||
try {
|
||||
const body = await parseBody(req, createAdminTemplateSchema);
|
||||
const template = await createAdminTemplate(ctx.portId, ctx.userId, body, {
|
||||
|
||||
@@ -111,7 +111,15 @@ export async function POST(req: NextRequest): Promise<NextResponse> {
|
||||
}
|
||||
|
||||
case 'DOCUMENT_OPENED': {
|
||||
const openedRecipients = recipients.filter((r) => r.readStatus === 'OPENED');
|
||||
// Documenso v1 sends `readStatus: 'OPENED'`; v2 has used both
|
||||
// upper and lower case across releases and may omit the field
|
||||
// entirely (the event itself signals the open). Treat the event
|
||||
// as the signal: dispatch a per-recipient open for every
|
||||
// recipient on the document so v2 deployments stop silently
|
||||
// dropping opens.
|
||||
const openedRecipients = recipients.filter(
|
||||
(r) => !r.readStatus || String(r.readStatus).toUpperCase() === 'OPENED',
|
||||
);
|
||||
for (const r of openedRecipients) {
|
||||
await handleDocumentOpened({
|
||||
documentId: documensoId,
|
||||
|
||||
Reference in New Issue
Block a user