import "server-only"; import { NextResponse } from "next/server"; import type { ApiResult } from "@/app/lib/types"; import { isSessionReplaced, markReplacedOn } from "@/app/lib/server/signedInElsewhere"; /** Build the error response for a failed ApiResult. * 401 is reserved for expired/absent session (the client redirects to /login); * a genuine upstream 4xx (e.g. 404 for a missing record, 409 for a conflict) * is forwarded as-is so the page can branch on the real status instead of * sniffing the message text; any other failure (5xx, unknown) falls back to * 400 so the page can show the message inline. */ export function errorResponse(r: Extract, { ok: false }>): NextResponse { const status = r.expired ? 401 : r.status && r.status >= 400 && r.status < 500 ? r.status : 400; const body: { error: string; code?: string; errors?: string[]; details?: Record; } = { error: r.error }; if (r.code) body.code = r.code; if (r.errors) body.errors = r.errors; if (r.details) body.details = r.details; const res = NextResponse.json(body, { status }); // one-session-per-account: a newer sign-in ended this session; end it here and tell the login page why. return isSessionReplaced(r) ? markReplacedOn(res) : res; } export function unauthorized(message = "Not authenticated"): NextResponse { return NextResponse.json({ error: message }, { status: 401 }); } export function badRequest(message: string, extra?: Record): NextResponse { return NextResponse.json({ error: message, ...(extra ?? {}) }, { status: 400 }); } /** A `linkKind: "URL"` reference must be either a site-relative path or an absolute http(s) URL. * It later renders verbatim as an anchor href on the anonymous storefront, so anything else * (e.g. `javascript:...`) is an XSS/open-redirect surface and must be rejected at the boundary. * A leading `//` (or `/\`) is protocol-relative — browsers resolve it against the current * scheme onto whatever host follows, i.e. it is effectively an absolute off-site URL wearing a * single leading slash — so a "starts with /" check alone is not sufficient and must exclude it. */ export function isSafeUrlLinkReference(value: string): boolean { if (/^https?:\/\//i.test(value)) return true; return value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\"); }