Files
property-management-network/app/api/files/[...key]/route.ts
T
Leon SerfatyandClaude Opus 4.8 c9968531e4 Consolidate audit-fixes branch: webhooks, integrations, and deploy hardening
Batch commit of the pending working tree on security/audit-fixes-2026-07.
Major areas:
- Outbound webhooks / Zapier: schema + signed delivery with retries, public
  v1 API (REST-hook subscribe/unsubscribe), settings UI, cron drain.
- Deploy hardening: email via SMTP2GO (Resend fully removed), verified DB TLS
  (DATABASE_SSL=require + DATABASE_CA), storage fails loud in production when
  Spaces is unconfigured instead of silently using ephemeral disk.
- Integrations & features (concurrent work): accounting (QuickBooks/Xero),
  e-signature (DocuSign/Dropbox Sign), PayPal, geocoding/maps, onboarding,
  expanded legal pages.
- DB migrations 0006–0009.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 13:42:34 -04:00

70 lines
3.1 KiB
TypeScript

import { NextResponse } from "next/server"
import { getSessionUser } from "@/lib/session"
import { getEffectiveOwnerId } from "@/lib/account"
import { readFile, contentTypeForKey, usingSpaces, presignGetUrl } from "@/lib/storage"
// Only these image types are safe to render inline from our origin. Everything
// else (including svg, html, documents) is forced to download as an attachment.
const INLINE_EXTENSIONS = ["png", "jpg", "jpeg", "gif", "webp"]
// Auth-gated file serving. Storage keys are namespaced by the portfolio's owner
// id (`<ownerId>/<scope>/<file>`), so a file belongs to the requester iff the
// key's first segment equals their EFFECTIVE owner id — this lets active team
// members view the owner's files while preserving isolation between accounts.
//
// When object storage (Spaces) is configured we issue a short-lived presigned
// redirect so the bytes stream straight from the bucket to the browser instead
// of through the app. The auth + ownership checks below still gate every request
// (the presigned URL is only minted for the rightful owner and expires quickly).
export async function GET(_: Request, { params }: { params: Promise<{ key: string[] }> }) {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const ownerId = await getEffectiveOwnerId(user.id)
const { key: segments } = await params
// Reject traversal / malformed segments (no double-decode — params are already decoded).
const badSegment = segments.some(
(s) => s === "" || s === "." || s === ".." || s.includes("/") || s.includes("\\")
)
// Ownership: the first path segment must be EXACTLY the caller's effective owner id.
if (badSegment || segments[0] !== ownerId) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 })
}
const key = segments.join("/")
const ext = key.split(".").pop()?.toLowerCase() ?? ""
const disposition = INLINE_EXTENSIONS.includes(ext) ? "inline" : "attachment"
const basename = (key.split("/").pop() ?? "file").replace(/["\\\r\n]/g, "")
// Object storage: redirect to a presigned URL (bytes served by Spaces).
if (usingSpaces()) {
try {
const url = await presignGetUrl(key, { disposition, filename: basename, expiresIn: 3600 })
const res = NextResponse.redirect(url, 302)
// Let the browser reuse the redirect for a while (< the URL's TTL) so
// repeat views skip the app hop entirely, without outliving the signature.
res.headers.set("Cache-Control", "private, max-age=1800")
return res
} catch {
return NextResponse.json({ error: "Not found" }, { status: 404 })
}
}
// Local-disk fallback: stream the bytes through the app.
try {
const buffer = await readFile(key)
return new NextResponse(new Uint8Array(buffer), {
headers: {
"Content-Type": contentTypeForKey(key),
"Content-Disposition": `${disposition}; filename="${basename}"`,
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, max-age=3600",
},
})
} catch {
return NextResponse.json({ error: "Not found" }, { status: 404 })
}
}