@reblu/site-next 1.14.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +89 -0
- package/README.md +190 -1
- package/dist/cart.cjs +96 -53
- package/dist/cart.cjs.map +1 -1
- package/dist/cart.d.cts +82 -4
- package/dist/cart.d.ts +82 -4
- package/dist/cart.js +93 -53
- package/dist/cart.js.map +1 -1
- package/dist/{collection-BE5dhf-r.d.cts → collection-gAD_g03I.d.cts} +1 -1
- package/dist/{collection-BE5dhf-r.d.ts → collection-gAD_g03I.d.ts} +1 -1
- package/dist/route-handlers.cjs +8 -1
- package/dist/route-handlers.cjs.map +1 -1
- package/dist/route-handlers.d.cts +11 -0
- package/dist/route-handlers.d.ts +11 -0
- package/dist/route-handlers.js +8 -1
- package/dist/route-handlers.js.map +1 -1
- package/dist/shop-route-handlers.cjs +97 -2
- package/dist/shop-route-handlers.cjs.map +1 -1
- package/dist/shop-route-handlers.d.cts +70 -6
- package/dist/shop-route-handlers.d.ts +70 -6
- package/dist/shop-route-handlers.js +97 -2
- package/dist/shop-route-handlers.js.map +1 -1
- package/dist/shop-server.d.cts +1 -1
- package/dist/shop-server.d.ts +1 -1
- package/dist/shop.cjs +223 -2
- package/dist/shop.cjs.map +1 -1
- package/dist/shop.d.cts +72 -4
- package/dist/shop.d.ts +72 -4
- package/dist/shop.js +220 -1
- package/dist/shop.js.map +1 -1
- package/package.json +4 -4
package/dist/route-handlers.d.ts
CHANGED
|
@@ -99,6 +99,17 @@ interface CreateProxyRouteOptions {
|
|
|
99
99
|
* @default 'Error de conexión con el servidor.'
|
|
100
100
|
*/
|
|
101
101
|
proxyErrorMessage?: string;
|
|
102
|
+
/**
|
|
103
|
+
* Transform the raw request body before it is forwarded upstream (REB-837
|
|
104
|
+
* — `createShopCheckoutRoute`'s successPath/cancelPath default-injection
|
|
105
|
+
* is the first caller). Receives the original `request` so a transform
|
|
106
|
+
* can derive values from it (e.g. `request.nextUrl.origin`). Only called
|
|
107
|
+
* for a non-GET/HEAD request with a non-empty body. A thrown error is
|
|
108
|
+
* logged and the ORIGINAL body is forwarded unchanged — a transform bug
|
|
109
|
+
* must never turn into a hard failure for every request through this
|
|
110
|
+
* route.
|
|
111
|
+
*/
|
|
112
|
+
transformBody?: (rawBody: string, request: NextRequest) => string;
|
|
102
113
|
}
|
|
103
114
|
/**
|
|
104
115
|
* Creates a Next.js Route Handler that proxies `request` to
|
package/dist/route-handlers.js
CHANGED
|
@@ -39,7 +39,14 @@ function createProxyRoute(targetPath, opts = {}) {
|
|
|
39
39
|
const xri = request.headers.get("x-real-ip");
|
|
40
40
|
if (xri) forwardedHeaders["x-real-ip"] = xri;
|
|
41
41
|
const upperMethod = method.toUpperCase();
|
|
42
|
-
|
|
42
|
+
let body = upperMethod === "GET" || upperMethod === "HEAD" ? void 0 : await request.text();
|
|
43
|
+
if (body && opts.transformBody) {
|
|
44
|
+
try {
|
|
45
|
+
body = opts.transformBody(body, request);
|
|
46
|
+
} catch (err) {
|
|
47
|
+
console.error(`[createProxyRoute] transformBody threw for ${targetPath}:`, err);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
43
50
|
const search = request.nextUrl?.search ?? "";
|
|
44
51
|
const controller = new AbortController();
|
|
45
52
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/route-handlers.ts"],"sourcesContent":["/**\n * `@reblu/site-next/route-handlers` — server-only, dependency-free Route\n * Handler factory (REB-510 / design doc \"site-auth-package\").\n *\n * This module MUST stay dependency-free (no `@reblu/site-ui`, no React): it is\n * imported directly by `app/api/*` Route Handler files, and its own tsup entry\n * carries NO `'use client'` directive (mirrors the `cache` subpath's R4\n * precedent for the opposite direction — see `tsup.config.ts`).\n *\n * Scope: this factory covers the `/api/site/auth/*` proxy shape specifically\n * (fixed target path, JSON body passthrough, optional `Set-Cookie` forward) —\n * the same shape as every one of demo-site's 8 auth Route Handlers. It is\n * modeled on `apps/demo-site/src/lib/api/proxy.ts` (`proxyToBaseApi`) but is\n * NOT a drop-in replacement for every one of that helper's call sites: it\n * does not support a per-request DYNAMIC `targetPath` (e.g.\n * `api/shop/order/[sessionId]/route.ts`'s `` `/api/site/shop/order/${id}` ``)\n * or an arbitrary extra-`headers` passthrough — both are genuinely out of\n * scope for REB-510 (auth only). demo-site's non-auth proxy routes keep using\n * `proxyToBaseApi` directly; only the 8 auth routes are candidates to adopt\n * this factory.\n *\n * export const POST = createProxyRoute('/api/site/auth/login')\n *\n * Deliberate behavior change vs the original (R6): `proxy.ts` reads\n * `REBLU_API_BASE_URL`/`REBLU_API_KEY` at MODULE LOAD. This factory reads them\n * LAZILY, inside the returned handler, on every request — `opts.baseUrl` /\n * `opts.apiKey` still take priority when provided.\n *\n * Why this factory reads `process.env` at all, unlike `@reblu/site-client`\n * (whose own docblock states \"the SDK never reads `process.env` itself\"):\n * `site-client` is instantiated ONCE by the consuming SITE, which already\n * owns and injects its env at that single call site. `createProxyRoute` is\n * the opposite shape on purpose — a ZERO-CONFIG one-liner meant to be called\n * once per Route Handler FILE (8+ files in a typical SITE), so requiring\n * every file to re-thread `baseUrl`/`apiKey` would defeat the \"one line\"\n * value proposition documented in the README. The env fallback is this\n * factory's deliberate ergonomic default; `opts.baseUrl`/`opts.apiKey` remain\n * available for a SITE that wants explicit, non-`process.env` control.\n *\n * Trust note on header forwarding: `X-Forwarded-For`/`X-Real-IP` are copied\n * from the incoming request VERBATIM (same as the original `proxy.ts`). On\n * Vercel the platform itself sets/overwrites these ahead of the Route\n * Handler, so they're trustworthy there — but this is a distributable SDK a\n * SITE can deploy anywhere. On a host where nothing strips inbound spoofed\n * values, a client can forge the IP base-api rate-limits on. Deploy this\n * factory only behind a platform that normalizes/overwrites these headers,\n * or in front of infra that strips client-supplied ones.\n */\nimport type { NextRequest } from 'next/server'\n\nexport interface CreateProxyRouteOptions {\n /** Overrides `REBLU_API_BASE_URL`. Read lazily per-request when omitted. */\n baseUrl?: string\n /** Overrides `REBLU_API_KEY`. Read lazily per-request when omitted. */\n apiKey?: string\n /** @default 'POST' */\n method?: string\n /** Forward upstream `Set-Cookie` headers to the browser. @default false */\n forwardSetCookie?: boolean\n /**\n * Reject non-`application/json` requests with a Spanish 400 before ever\n * reaching the network — mirrors `magic-link-exchange/route.ts`'s guard.\n * @default false\n */\n requireJson?: boolean\n /**\n * Overrides the Spanish `message` field of the `requireJson` 400 body, for\n * a non-Spanish-default SITE. The `error` code (`invalid_request`) and\n * shape stay fixed — only the human-facing text is overridable.\n * @default 'Solicitud no válida'\n */\n invalidRequestMessage?: string\n /**\n * Hard timeout (ms) for the upstream fetch, enforced via `AbortController`\n * — mirrors `@reblu/site-client`'s own `timeoutMs` (default `8000`, same\n * value). Without this, a hung base-api response would hang the SITE's\n * Route Handler indefinitely instead of degrading.\n * @default 8000\n */\n timeoutMs?: number\n /**\n * Overrides the `message` field of the 500 body returned when neither\n * `opts.baseUrl`/`opts.apiKey` nor `REBLU_API_BASE_URL`/`REBLU_API_KEY`\n * resolve to a non-empty value.\n * @default 'Error de configuración del servidor.'\n */\n configurationErrorMessage?: string\n /**\n * Overrides the `message` field of the 502 body returned when the\n * upstream fetch times out.\n * @default 'La solicitud ha superado el tiempo de espera.'\n */\n timeoutMessage?: string\n /**\n * Overrides the `message` field of the 502 body returned when the\n * upstream fetch fails for any other reason (DNS, connection refused,\n * etc.).\n * @default 'Error de conexión con el servidor.'\n */\n proxyErrorMessage?: string\n}\n\nfunction jsonErrorResponse(status: number, error: string, message: string): Response {\n return new Response(\n JSON.stringify({ error, message, correlation_id: crypto.randomUUID() }),\n { status, headers: { 'Content-Type': 'application/json; charset=utf-8' } },\n )\n}\n\n/**\n * Creates a Next.js Route Handler that proxies `request` to\n * `${baseUrl}${targetPath}` at base-api, injecting the `X-Reblu-Api-Key`\n * server-side so it never reaches the browser.\n */\nexport function createProxyRoute(targetPath: string, opts: CreateProxyRouteOptions = {}) {\n const {\n method = 'POST',\n forwardSetCookie = false,\n requireJson = false,\n invalidRequestMessage = 'Solicitud no válida',\n timeoutMs = 8000,\n configurationErrorMessage = 'Error de configuración del servidor.',\n timeoutMessage = 'La solicitud ha superado el tiempo de espera.',\n proxyErrorMessage = 'Error de conexión con el servidor.',\n } = opts\n\n return async function handler(request: NextRequest): Promise<Response> {\n if (requireJson) {\n const contentType = request.headers.get('content-type') ?? ''\n if (!contentType.includes('application/json')) {\n return jsonErrorResponse(400, 'invalid_request', invalidRequestMessage)\n }\n }\n\n // Lazy, per-request env read (R6) — opts win when provided.\n const baseUrl = opts.baseUrl ?? process.env.REBLU_API_BASE_URL ?? ''\n const apiKey = opts.apiKey ?? process.env.REBLU_API_KEY ?? ''\n\n if (!baseUrl || !apiKey) {\n console.error(\n `[createProxyRoute] Missing configuration for ${targetPath}: ` +\n `${!baseUrl ? 'baseUrl/REBLU_API_BASE_URL ' : ''}${!apiKey ? 'apiKey/REBLU_API_KEY' : ''}`.trim(),\n )\n return jsonErrorResponse(500, 'missing_configuration', configurationErrorMessage)\n }\n\n const forwardedHeaders: Record<string, string> = {}\n const ua = request.headers.get('user-agent')\n if (ua) forwardedHeaders['user-agent'] = ua\n const xff = request.headers.get('x-forwarded-for')\n if (xff) forwardedHeaders['x-forwarded-for'] = xff\n const xri = request.headers.get('x-real-ip')\n if (xri) forwardedHeaders['x-real-ip'] = xri\n\n const upperMethod = method.toUpperCase()\n const body =\n upperMethod === 'GET' || upperMethod === 'HEAD' ? undefined : await request.text()\n // Forward the original query string (e.g. `?slug=x`) regardless of\n // method — `targetPath` is fixed at factory-call time, so without this a\n // GET route configured via `{ method: 'GET' }` would silently drop it.\n const search = request.nextUrl?.search ?? ''\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n\n try {\n const res = await fetch(`${baseUrl}${targetPath}${search}`, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Reblu-Api-Key': apiKey,\n ...forwardedHeaders,\n },\n ...(body ? { body } : {}),\n cache: 'no-store',\n signal: controller.signal,\n })\n\n const data = await res.text()\n const responseHeaders = new Headers({\n 'Content-Type': res.headers.get('Content-Type') ?? 'application/json',\n })\n\n if (forwardSetCookie) {\n for (const cookie of res.headers.getSetCookie()) {\n responseHeaders.append('set-cookie', cookie)\n }\n }\n\n return new Response(data, { status: res.status, headers: responseHeaders })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n console.error(`[createProxyRoute] Timed out forwarding to ${targetPath} after ${timeoutMs}ms`)\n return jsonErrorResponse(502, 'upstream_timeout', timeoutMessage)\n }\n console.error(`[createProxyRoute] Error forwarding to ${targetPath}:`, err)\n return jsonErrorResponse(502, 'proxy_error', proxyErrorMessage)\n } finally {\n clearTimeout(timer)\n }\n }\n}\n"],"mappings":";AAsGA,SAAS,kBAAkB,QAAgB,OAAe,SAA2B;AACnF,SAAO,IAAI;AAAA,IACT,KAAK,UAAU,EAAE,OAAO,SAAS,gBAAgB,OAAO,WAAW,EAAE,CAAC;AAAA,IACtE,EAAE,QAAQ,SAAS,EAAE,gBAAgB,kCAAkC,EAAE;AAAA,EAC3E;AACF;AAOO,SAAS,iBAAiB,YAAoB,OAAgC,CAAC,GAAG;AACvF,QAAM;AAAA,IACJ,SAAS;AAAA,IACT,mBAAmB;AAAA,IACnB,cAAc;AAAA,IACd,wBAAwB;AAAA,IACxB,YAAY;AAAA,IACZ,4BAA4B;AAAA,IAC5B,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,EACtB,IAAI;AAEJ,SAAO,eAAe,QAAQ,SAAyC;AACrE,QAAI,aAAa;AACf,YAAM,cAAc,QAAQ,QAAQ,IAAI,cAAc,KAAK;AAC3D,UAAI,CAAC,YAAY,SAAS,kBAAkB,GAAG;AAC7C,eAAO,kBAAkB,KAAK,mBAAmB,qBAAqB;AAAA,MACxE;AAAA,IACF;AAGA,UAAM,UAAU,KAAK,WAAW,QAAQ,IAAI,sBAAsB;AAClE,UAAM,SAAS,KA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,UAAU,IAAI,QAAQ,aAAa,GAAG;AAC/C,0BAAgB,OAAO,cAAc,MAAM;AAAA,QAC7C;AAAA,MACF;AAEA,aAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,QAAQ,SAAS,gBAAgB,CAAC;AAAA,IAC5E,SAAS,KAAK;AACZ,UAAI,eAAe,SAAS,IAAI,SAAS,cAAc;AACrD,gBAAQ,MAAM,8CAA8C,UAAU,UAAU,SAAS,IAAI;AAC7F,eAAO,kBAAkB,KAAK,oBAAoB,cAAc;AAAA,MAClE;AACA,cAAQ,MAAM,0CAA0C,UAAU,KAAK,GAAG;AAC1E,aAAO,kBAAkB,KAAK,eAAe,iBAAiB;AAAA,IAChE,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/route-handlers.ts"],"sourcesContent":["/**\n * `@reblu/site-next/route-handlers` — server-only, dependency-free Route\n * Handler factory (REB-510 / design doc \"site-auth-package\").\n *\n * This module MUST stay dependency-free (no `@reblu/site-ui`, no React): it is\n * imported directly by `app/api/*` Route Handler files, and its own tsup entry\n * carries NO `'use client'` directive (mirrors the `cache` subpath's R4\n * precedent for the opposite direction — see `tsup.config.ts`).\n *\n * Scope: this factory covers the `/api/site/auth/*` proxy shape specifically\n * (fixed target path, JSON body passthrough, optional `Set-Cookie` forward) —\n * the same shape as every one of demo-site's 8 auth Route Handlers. It is\n * modeled on `apps/demo-site/src/lib/api/proxy.ts` (`proxyToBaseApi`) but is\n * NOT a drop-in replacement for every one of that helper's call sites: it\n * does not support a per-request DYNAMIC `targetPath` (e.g.\n * `api/shop/order/[sessionId]/route.ts`'s `` `/api/site/shop/order/${id}` ``)\n * or an arbitrary extra-`headers` passthrough — both are genuinely out of\n * scope for REB-510 (auth only). demo-site's non-auth proxy routes keep using\n * `proxyToBaseApi` directly; only the 8 auth routes are candidates to adopt\n * this factory.\n *\n * export const POST = createProxyRoute('/api/site/auth/login')\n *\n * Deliberate behavior change vs the original (R6): `proxy.ts` reads\n * `REBLU_API_BASE_URL`/`REBLU_API_KEY` at MODULE LOAD. This factory reads them\n * LAZILY, inside the returned handler, on every request — `opts.baseUrl` /\n * `opts.apiKey` still take priority when provided.\n *\n * Why this factory reads `process.env` at all, unlike `@reblu/site-client`\n * (whose own docblock states \"the SDK never reads `process.env` itself\"):\n * `site-client` is instantiated ONCE by the consuming SITE, which already\n * owns and injects its env at that single call site. `createProxyRoute` is\n * the opposite shape on purpose — a ZERO-CONFIG one-liner meant to be called\n * once per Route Handler FILE (8+ files in a typical SITE), so requiring\n * every file to re-thread `baseUrl`/`apiKey` would defeat the \"one line\"\n * value proposition documented in the README. The env fallback is this\n * factory's deliberate ergonomic default; `opts.baseUrl`/`opts.apiKey` remain\n * available for a SITE that wants explicit, non-`process.env` control.\n *\n * Trust note on header forwarding: `X-Forwarded-For`/`X-Real-IP` are copied\n * from the incoming request VERBATIM (same as the original `proxy.ts`). On\n * Vercel the platform itself sets/overwrites these ahead of the Route\n * Handler, so they're trustworthy there — but this is a distributable SDK a\n * SITE can deploy anywhere. On a host where nothing strips inbound spoofed\n * values, a client can forge the IP base-api rate-limits on. Deploy this\n * factory only behind a platform that normalizes/overwrites these headers,\n * or in front of infra that strips client-supplied ones.\n */\nimport type { NextRequest } from 'next/server'\n\nexport interface CreateProxyRouteOptions {\n /** Overrides `REBLU_API_BASE_URL`. Read lazily per-request when omitted. */\n baseUrl?: string\n /** Overrides `REBLU_API_KEY`. Read lazily per-request when omitted. */\n apiKey?: string\n /** @default 'POST' */\n method?: string\n /** Forward upstream `Set-Cookie` headers to the browser. @default false */\n forwardSetCookie?: boolean\n /**\n * Reject non-`application/json` requests with a Spanish 400 before ever\n * reaching the network — mirrors `magic-link-exchange/route.ts`'s guard.\n * @default false\n */\n requireJson?: boolean\n /**\n * Overrides the Spanish `message` field of the `requireJson` 400 body, for\n * a non-Spanish-default SITE. The `error` code (`invalid_request`) and\n * shape stay fixed — only the human-facing text is overridable.\n * @default 'Solicitud no válida'\n */\n invalidRequestMessage?: string\n /**\n * Hard timeout (ms) for the upstream fetch, enforced via `AbortController`\n * — mirrors `@reblu/site-client`'s own `timeoutMs` (default `8000`, same\n * value). Without this, a hung base-api response would hang the SITE's\n * Route Handler indefinitely instead of degrading.\n * @default 8000\n */\n timeoutMs?: number\n /**\n * Overrides the `message` field of the 500 body returned when neither\n * `opts.baseUrl`/`opts.apiKey` nor `REBLU_API_BASE_URL`/`REBLU_API_KEY`\n * resolve to a non-empty value.\n * @default 'Error de configuración del servidor.'\n */\n configurationErrorMessage?: string\n /**\n * Overrides the `message` field of the 502 body returned when the\n * upstream fetch times out.\n * @default 'La solicitud ha superado el tiempo de espera.'\n */\n timeoutMessage?: string\n /**\n * Overrides the `message` field of the 502 body returned when the\n * upstream fetch fails for any other reason (DNS, connection refused,\n * etc.).\n * @default 'Error de conexión con el servidor.'\n */\n proxyErrorMessage?: string\n /**\n * Transform the raw request body before it is forwarded upstream (REB-837\n * — `createShopCheckoutRoute`'s successPath/cancelPath default-injection\n * is the first caller). Receives the original `request` so a transform\n * can derive values from it (e.g. `request.nextUrl.origin`). Only called\n * for a non-GET/HEAD request with a non-empty body. A thrown error is\n * logged and the ORIGINAL body is forwarded unchanged — a transform bug\n * must never turn into a hard failure for every request through this\n * route.\n */\n transformBody?: (rawBody: string, request: NextRequest) => string\n}\n\nfunction jsonErrorResponse(status: number, error: string, message: string): Response {\n return new Response(\n JSON.stringify({ error, message, correlation_id: crypto.randomUUID() }),\n { status, headers: { 'Content-Type': 'application/json; charset=utf-8' } },\n )\n}\n\n/**\n * Creates a Next.js Route Handler that proxies `request` to\n * `${baseUrl}${targetPath}` at base-api, injecting the `X-Reblu-Api-Key`\n * server-side so it never reaches the browser.\n */\nexport function createProxyRoute(targetPath: string, opts: CreateProxyRouteOptions = {}) {\n const {\n method = 'POST',\n forwardSetCookie = false,\n requireJson = false,\n invalidRequestMessage = 'Solicitud no válida',\n timeoutMs = 8000,\n configurationErrorMessage = 'Error de configuración del servidor.',\n timeoutMessage = 'La solicitud ha superado el tiempo de espera.',\n proxyErrorMessage = 'Error de conexión con el servidor.',\n } = opts\n\n return async function handler(request: NextRequest): Promise<Response> {\n if (requireJson) {\n const contentType = request.headers.get('content-type') ?? ''\n if (!contentType.includes('application/json')) {\n return jsonErrorResponse(400, 'invalid_request', invalidRequestMessage)\n }\n }\n\n // Lazy, per-request env read (R6) — opts win when provided.\n const baseUrl = opts.baseUrl ?? process.env.REBLU_API_BASE_URL ?? ''\n const apiKey = opts.apiKey ?? process.env.REBLU_API_KEY ?? ''\n\n if (!baseUrl || !apiKey) {\n console.error(\n `[createProxyRoute] Missing configuration for ${targetPath}: ` +\n `${!baseUrl ? 'baseUrl/REBLU_API_BASE_URL ' : ''}${!apiKey ? 'apiKey/REBLU_API_KEY' : ''}`.trim(),\n )\n return jsonErrorResponse(500, 'missing_configuration', configurationErrorMessage)\n }\n\n const forwardedHeaders: Record<string, string> = {}\n const ua = request.headers.get('user-agent')\n if (ua) forwardedHeaders['user-agent'] = ua\n const xff = request.headers.get('x-forwarded-for')\n if (xff) forwardedHeaders['x-forwarded-for'] = xff\n const xri = request.headers.get('x-real-ip')\n if (xri) forwardedHeaders['x-real-ip'] = xri\n\n const upperMethod = method.toUpperCase()\n let body =\n upperMethod === 'GET' || upperMethod === 'HEAD' ? undefined : await request.text()\n if (body && opts.transformBody) {\n try {\n body = opts.transformBody(body, request)\n } catch (err) {\n console.error(`[createProxyRoute] transformBody threw for ${targetPath}:`, err)\n }\n }\n // Forward the original query string (e.g. `?slug=x`) regardless of\n // method — `targetPath` is fixed at factory-call time, so without this a\n // GET route configured via `{ method: 'GET' }` would silently drop it.\n const search = request.nextUrl?.search ?? ''\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n\n try {\n const res = await fetch(`${baseUrl}${targetPath}${search}`, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Reblu-Api-Key': apiKey,\n ...forwardedHeaders,\n },\n ...(body ? { body } : {}),\n cache: 'no-store',\n signal: controller.signal,\n })\n\n const data = await res.text()\n const responseHeaders = new Headers({\n 'Content-Type': res.headers.get('Content-Type') ?? 'application/json',\n })\n\n if (forwardSetCookie) {\n for (const cookie of res.headers.getSetCookie()) {\n responseHeaders.append('set-cookie', cookie)\n }\n }\n\n return new Response(data, { status: res.status, headers: responseHeaders })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n console.error(`[createProxyRoute] Timed out forwarding to ${targetPath} after ${timeoutMs}ms`)\n return jsonErrorResponse(502, 'upstream_timeout', timeoutMessage)\n }\n console.error(`[createProxyRoute] Error forwarding to ${targetPath}:`, err)\n return jsonErrorResponse(502, 'proxy_error', proxyErrorMessage)\n } finally {\n clearTimeout(timer)\n }\n }\n}\n"],"mappings":";AAiHA,SAAS,kBAAkB,QAAgB,OAAe,SAA2B;AACnF,SAAO,IAAI;AAAA,IACT,KAAK,UAAU,EAAE,OAAO,SAAS,gBAAgB,OAAO,WAAW,EAAE,CAAC;AAAA,IACtE,EAAE,QAAQ,SAAS,EAAE,gBAAgB,kCAAkC,EAAE;AAAA,EAC3E;AACF;AAOO,SAAS,iBAAiB,YAAoB,OAAgC,CAAC,GAAG;AACvF,QAAM;AAAA,IACJ,SAAS;AAAA,IACT,mBAAmB;AAAA,IACnB,cAAc;AAAA,IACd,wBAAwB;AAAA,IACxB,YAAY;AAAA,IACZ,4BAA4B;AAAA,IAC5B,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,EACtB,IAAI;AAEJ,SAAO,eAAe,QAAQ,SAAyC;AACrE,QAAI,aAAa;AACf,YAAM,cAAc,QAAQ,QAAQ,IAAI,cAAc,KAAK;AAC3D,UAAI,CAAC,YAAY,SAAS,kBAAkB,GAAG;AAC7C,eAAO,kBAAkB,KAAK,mBAAmB,qBAAqB;AAAA,MACxE;AAAA,IACF;AAGA,UAAM,UAAU,KAAK,WAAW,QAAQ,IAAI,sBAAsB;AAClE,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AA,MACrB,CAAC;AAED,YAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,YAAM,kBAAkB,IAAI,QAAQ;AAAA,QAClC,gBAAgB,IAAI,QAAQ,IAAI,cAAc,KAAK;AAAA,MACrD,CAAC;AAED,UAAI,kBAAkB;AACpB,mBAAW,UAAU,IAAI,QAAQ,aAAa,GAAG;AAC/C,0BAAgB,OAAO,cAAc,MAAM;AAAA,QAC7C;AAAA,MACF;AAEA,aAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,QAAQ,SAAS,gBAAgB,CAAC;AAAA,IAC5E,SAAS,KAAK;AACZ,UAAI,eAAe,SAAS,IAAI,SAAS,cAAc;AACrD,gBAAQ,MAAM,8CAA8C,UAAU,UAAU,SAAS,IAAI;AAC7F,eAAO,kBAAkB,KAAK,oBAAoB,cAAc;AAAA,MAClE;AACA,cAAQ,MAAM,0CAA0C,UAAU,KAAK,GAAG;AAC1E,aAAO,kBAAkB,KAAK,eAAe,iBAAiB;AAAA,IAChE,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF;AACF;","names":[]}
|
|
@@ -69,7 +69,14 @@ function createProxyRoute(targetPath, opts = {}) {
|
|
|
69
69
|
const xri = request.headers.get("x-real-ip");
|
|
70
70
|
if (xri) forwardedHeaders["x-real-ip"] = xri;
|
|
71
71
|
const upperMethod = method.toUpperCase();
|
|
72
|
-
|
|
72
|
+
let body = upperMethod === "GET" || upperMethod === "HEAD" ? void 0 : await request.text();
|
|
73
|
+
if (body && opts.transformBody) {
|
|
74
|
+
try {
|
|
75
|
+
body = opts.transformBody(body, request);
|
|
76
|
+
} catch (err) {
|
|
77
|
+
console.error(`[createProxyRoute] transformBody threw for ${targetPath}:`, err);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
73
80
|
const search = request.nextUrl?.search ?? "";
|
|
74
81
|
const controller = new AbortController();
|
|
75
82
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
@@ -108,10 +115,98 @@ function createProxyRoute(targetPath, opts = {}) {
|
|
|
108
115
|
};
|
|
109
116
|
}
|
|
110
117
|
|
|
118
|
+
// src/shop/checkout-redirect.ts
|
|
119
|
+
var DEFAULT_CHECKOUT_REDIRECT_HOSTS = ["checkout.stripe.com"];
|
|
120
|
+
function isSafeCheckoutRedirectUrl(url, allowedHosts = DEFAULT_CHECKOUT_REDIRECT_HOSTS) {
|
|
121
|
+
let parsed;
|
|
122
|
+
try {
|
|
123
|
+
parsed = new URL(url);
|
|
124
|
+
} catch {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
return parsed.protocol === "https:" && allowedHosts.includes(parsed.hostname);
|
|
128
|
+
}
|
|
129
|
+
|
|
111
130
|
// src/shop/route-handlers.ts
|
|
112
131
|
var DEFAULT_WRITE_OPTS = { requireJson: true };
|
|
132
|
+
function normalizeSitePath(path, fallback) {
|
|
133
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path) || path.startsWith("//")) {
|
|
134
|
+
console.error(
|
|
135
|
+
`[createShopCheckoutRoute] Rejected an absolute/protocol-relative path "${path}" \u2014 using the default instead.`
|
|
136
|
+
);
|
|
137
|
+
return fallback;
|
|
138
|
+
}
|
|
139
|
+
return path.startsWith("/") ? path : `/${path}`;
|
|
140
|
+
}
|
|
141
|
+
function unsafeRedirectResponse(message) {
|
|
142
|
+
return new Response(
|
|
143
|
+
JSON.stringify({ error: "unsafe_redirect", message, correlation_id: crypto.randomUUID() }),
|
|
144
|
+
{ status: 502, headers: { "Content-Type": "application/json; charset=utf-8" } }
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
function extractCheckoutUrl(rawBody) {
|
|
148
|
+
try {
|
|
149
|
+
const parsed = JSON.parse(rawBody);
|
|
150
|
+
return typeof parsed?.data?.url === "string" ? parsed.data.url : void 0;
|
|
151
|
+
} catch {
|
|
152
|
+
return void 0;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
var UNSAFE_PASSTHROUGH_HEADERS = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding"]);
|
|
156
|
+
function safeResponseHeaders(headers) {
|
|
157
|
+
const safe = new Headers();
|
|
158
|
+
for (const [key, value] of headers.entries()) {
|
|
159
|
+
if (!UNSAFE_PASSTHROUGH_HEADERS.has(key.toLowerCase())) safe.set(key, value);
|
|
160
|
+
}
|
|
161
|
+
return safe;
|
|
162
|
+
}
|
|
113
163
|
function createShopCheckoutRoute(opts = {}) {
|
|
114
|
-
|
|
164
|
+
const {
|
|
165
|
+
successPath,
|
|
166
|
+
cancelPath,
|
|
167
|
+
cartPath = "/cart",
|
|
168
|
+
siteOrigin,
|
|
169
|
+
allowedRedirectHosts = DEFAULT_CHECKOUT_REDIRECT_HOSTS,
|
|
170
|
+
unsafeRedirectMessage = "Error de conexi\xF3n con el proveedor de pago.",
|
|
171
|
+
...proxyOpts
|
|
172
|
+
} = opts;
|
|
173
|
+
const resolvedCartPath = normalizeSitePath(cartPath, "/cart");
|
|
174
|
+
const defaultSuccessPath = `${resolvedCartPath}?pago=ok&session_id={CHECKOUT_SESSION_ID}`;
|
|
175
|
+
const defaultCancelPath = `${resolvedCartPath}?pago=cancelado`;
|
|
176
|
+
const resolvedSuccessPath = successPath !== void 0 ? normalizeSitePath(successPath, defaultSuccessPath) : defaultSuccessPath;
|
|
177
|
+
const resolvedCancelPath = cancelPath !== void 0 ? normalizeSitePath(cancelPath, defaultCancelPath) : defaultCancelPath;
|
|
178
|
+
const proxyHandler = createProxyRoute("/api/site/shop/checkout", {
|
|
179
|
+
...DEFAULT_WRITE_OPTS,
|
|
180
|
+
...proxyOpts,
|
|
181
|
+
transformBody: (rawBody, request) => {
|
|
182
|
+
const origin = siteOrigin ?? process.env.NEXT_PUBLIC_SITE_URL ?? request.nextUrl?.origin;
|
|
183
|
+
if (!origin) return rawBody;
|
|
184
|
+
let parsed;
|
|
185
|
+
try {
|
|
186
|
+
parsed = JSON.parse(rawBody);
|
|
187
|
+
} catch {
|
|
188
|
+
return rawBody;
|
|
189
|
+
}
|
|
190
|
+
if (typeof parsed.successUrl !== "string") {
|
|
191
|
+
parsed.successUrl = `${origin}${resolvedSuccessPath}`;
|
|
192
|
+
}
|
|
193
|
+
if (typeof parsed.cancelUrl !== "string") {
|
|
194
|
+
parsed.cancelUrl = `${origin}${resolvedCancelPath}`;
|
|
195
|
+
}
|
|
196
|
+
return JSON.stringify(parsed);
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
return async function handler(request) {
|
|
200
|
+
const response = await proxyHandler(request);
|
|
201
|
+
if (!response.ok) return response;
|
|
202
|
+
const rawBody = await response.text();
|
|
203
|
+
const url = extractCheckoutUrl(rawBody);
|
|
204
|
+
if (!url || !isSafeCheckoutRedirectUrl(url, allowedRedirectHosts)) {
|
|
205
|
+
console.error("[createShopCheckoutRoute] Blocked an unsafe checkout redirect URL");
|
|
206
|
+
return unsafeRedirectResponse(unsafeRedirectMessage);
|
|
207
|
+
}
|
|
208
|
+
return new Response(rawBody, { status: response.status, headers: safeResponseHeaders(response.headers) });
|
|
209
|
+
};
|
|
115
210
|
}
|
|
116
211
|
function createShopValidateCartRoute(opts = {}) {
|
|
117
212
|
return createProxyRoute("/api/site/shop/validate-cart", { ...DEFAULT_WRITE_OPTS, ...opts });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/shop/route-handlers.ts","../src/route-handlers.ts"],"sourcesContent":["/**\n * `@reblu/site-next/shop-route-handlers` (REB-829) — Route Handler factories\n * for the cart/checkout write flow (`/api/site/shop/{checkout, validate-cart,\n * apply-discount, check-email, order/[sessionId]}`). Every demo-site route\n * these replace (`app/api/shop/*`) either hand-rolled the SAME proxy\n * boilerplate `./route-handlers`'s `createProxyRoute` already generalizes\n * (checkout/validate-cart/apply-discount/check-email), or called\n * `proxyToBaseApi` directly for the one dynamic-path route (`order/\n * [sessionId]`) that `createProxyRoute` deliberately does not cover (its own\n * docblock: \"a per-request DYNAMIC targetPath... is genuinely out of scope\").\n * This module is the dynamic-path extension `createProxyRoute` named as a\n * gap, kept as its own file (not folded into `./server`, REB-809's filters/\n * collection glue) because it is a distinct concern — a page that only reads\n * shop data never needs these factories, and a cart/checkout integration\n * never needs the filters glue.\n *\n * Server-only, dependency-free (only `createProxyRoute` + the `next/server`\n * type) — same isolation direction as `./route-handlers`/`./shop/server.ts`:\n * this entry must NEVER carry `'use client'` (see `tsup.config.ts`).\n *\n * Mirrors `createProxyRoute`'s own API-key/server-only handling verbatim —\n * `REBLU_API_KEY` is read lazily, server-side, and injected as\n * `X-Reblu-Api-Key` on the upstream fetch only; it never reaches the\n * Response these handlers return to the browser.\n *\n * // app/api/shop/checkout/route.ts\n * export const POST = createShopCheckoutRoute()\n *\n * // app/api/shop/order/[sessionId]/route.ts\n * export const GET = createShopOrderRoute()\n */\nimport type { NextRequest } from 'next/server'\nimport { createProxyRoute, type CreateProxyRouteOptions } from '../route-handlers'\n\n/** Options for a fixed-path write route. `method` is always `'POST'` here. */\nexport type ShopWriteRouteOptions = Omit<CreateProxyRouteOptions, 'method'>\n\n/**\n * `requireJson: true` by default for every write route below: the browser\n * clients these proxy for (the cart/checkout UI) always set\n * `Content-Type: application/json`, and rejecting anything else with a 400\n * BEFORE the upstream fetch is strictly safer than forwarding an\n * unparseable body to base-api. A SITE with a non-JSON caller can still pass\n * `{ requireJson: false }`.\n */\nconst DEFAULT_WRITE_OPTS: ShopWriteRouteOptions = { requireJson: true }\n\n/** `POST /api/site/shop/checkout` — starts a hosted Stripe Checkout session. */\nexport function createShopCheckoutRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/checkout', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** `POST /api/site/shop/validate-cart` — live stock/price re-check before checkout. */\nexport function createShopValidateCartRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/validate-cart', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** `POST /api/site/shop/apply-discount` — validates a discount code against the cart. */\nexport function createShopApplyDiscountRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/apply-discount', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** `POST /api/site/shop/check-email` — whether a guest's email already has an account. */\nexport function createShopCheckEmailRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/check-email', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** Options for the dynamic order-lookup route. `method` is always `'GET'`. */\nexport type ShopOrderRouteOptions = Omit<CreateProxyRouteOptions, 'method'>\n\n/**\n * `GET /api/site/shop/order/[sessionId]` — the one route in this file with a\n * per-request dynamic target path, so it can't be a one-line\n * `createProxyRoute(...)` call like the others: it reads Next's route\n * `params`, builds `/api/site/shop/order/{sessionId}` per request, and\n * delegates everything else (env, timeout, forwarding, error shaping) to\n * `createProxyRoute`.\n */\nexport function createShopOrderRoute(opts: ShopOrderRouteOptions = {}) {\n return async function handler(\n request: NextRequest,\n context: { params: Promise<{ sessionId: string }> },\n ): Promise<Response> {\n const { sessionId } = await context.params\n const targetPath = `/api/site/shop/order/${encodeURIComponent(sessionId)}`\n return createProxyRoute(targetPath, { ...opts, method: 'GET' })(request)\n }\n}\n","/**\n * `@reblu/site-next/route-handlers` — server-only, dependency-free Route\n * Handler factory (REB-510 / design doc \"site-auth-package\").\n *\n * This module MUST stay dependency-free (no `@reblu/site-ui`, no React): it is\n * imported directly by `app/api/*` Route Handler files, and its own tsup entry\n * carries NO `'use client'` directive (mirrors the `cache` subpath's R4\n * precedent for the opposite direction — see `tsup.config.ts`).\n *\n * Scope: this factory covers the `/api/site/auth/*` proxy shape specifically\n * (fixed target path, JSON body passthrough, optional `Set-Cookie` forward) —\n * the same shape as every one of demo-site's 8 auth Route Handlers. It is\n * modeled on `apps/demo-site/src/lib/api/proxy.ts` (`proxyToBaseApi`) but is\n * NOT a drop-in replacement for every one of that helper's call sites: it\n * does not support a per-request DYNAMIC `targetPath` (e.g.\n * `api/shop/order/[sessionId]/route.ts`'s `` `/api/site/shop/order/${id}` ``)\n * or an arbitrary extra-`headers` passthrough — both are genuinely out of\n * scope for REB-510 (auth only). demo-site's non-auth proxy routes keep using\n * `proxyToBaseApi` directly; only the 8 auth routes are candidates to adopt\n * this factory.\n *\n * export const POST = createProxyRoute('/api/site/auth/login')\n *\n * Deliberate behavior change vs the original (R6): `proxy.ts` reads\n * `REBLU_API_BASE_URL`/`REBLU_API_KEY` at MODULE LOAD. This factory reads them\n * LAZILY, inside the returned handler, on every request — `opts.baseUrl` /\n * `opts.apiKey` still take priority when provided.\n *\n * Why this factory reads `process.env` at all, unlike `@reblu/site-client`\n * (whose own docblock states \"the SDK never reads `process.env` itself\"):\n * `site-client` is instantiated ONCE by the consuming SITE, which already\n * owns and injects its env at that single call site. `createProxyRoute` is\n * the opposite shape on purpose — a ZERO-CONFIG one-liner meant to be called\n * once per Route Handler FILE (8+ files in a typical SITE), so requiring\n * every file to re-thread `baseUrl`/`apiKey` would defeat the \"one line\"\n * value proposition documented in the README. The env fallback is this\n * factory's deliberate ergonomic default; `opts.baseUrl`/`opts.apiKey` remain\n * available for a SITE that wants explicit, non-`process.env` control.\n *\n * Trust note on header forwarding: `X-Forwarded-For`/`X-Real-IP` are copied\n * from the incoming request VERBATIM (same as the original `proxy.ts`). On\n * Vercel the platform itself sets/overwrites these ahead of the Route\n * Handler, so they're trustworthy there — but this is a distributable SDK a\n * SITE can deploy anywhere. On a host where nothing strips inbound spoofed\n * values, a client can forge the IP base-api rate-limits on. Deploy this\n * factory only behind a platform that normalizes/overwrites these headers,\n * or in front of infra that strips client-supplied ones.\n */\nimport type { NextRequest } from 'next/server'\n\nexport interface CreateProxyRouteOptions {\n /** Overrides `REBLU_API_BASE_URL`. Read lazily per-request when omitted. */\n baseUrl?: string\n /** Overrides `REBLU_API_KEY`. Read lazily per-request when omitted. */\n apiKey?: string\n /** @default 'POST' */\n method?: string\n /** Forward upstream `Set-Cookie` headers to the browser. @default false */\n forwardSetCookie?: boolean\n /**\n * Reject non-`application/json` requests with a Spanish 400 before ever\n * reaching the network — mirrors `magic-link-exchange/route.ts`'s guard.\n * @default false\n */\n requireJson?: boolean\n /**\n * Overrides the Spanish `message` field of the `requireJson` 400 body, for\n * a non-Spanish-default SITE. The `error` code (`invalid_request`) and\n * shape stay fixed — only the human-facing text is overridable.\n * @default 'Solicitud no válida'\n */\n invalidRequestMessage?: string\n /**\n * Hard timeout (ms) for the upstream fetch, enforced via `AbortController`\n * — mirrors `@reblu/site-client`'s own `timeoutMs` (default `8000`, same\n * value). Without this, a hung base-api response would hang the SITE's\n * Route Handler indefinitely instead of degrading.\n * @default 8000\n */\n timeoutMs?: number\n /**\n * Overrides the `message` field of the 500 body returned when neither\n * `opts.baseUrl`/`opts.apiKey` nor `REBLU_API_BASE_URL`/`REBLU_API_KEY`\n * resolve to a non-empty value.\n * @default 'Error de configuración del servidor.'\n */\n configurationErrorMessage?: string\n /**\n * Overrides the `message` field of the 502 body returned when the\n * upstream fetch times out.\n * @default 'La solicitud ha superado el tiempo de espera.'\n */\n timeoutMessage?: string\n /**\n * Overrides the `message` field of the 502 body returned when the\n * upstream fetch fails for any other reason (DNS, connection refused,\n * etc.).\n * @default 'Error de conexión con el servidor.'\n */\n proxyErrorMessage?: string\n}\n\nfunction jsonErrorResponse(status: number, error: string, message: string): Response {\n return new Response(\n JSON.stringify({ error, message, correlation_id: crypto.randomUUID() }),\n { status, headers: { 'Content-Type': 'application/json; charset=utf-8' } },\n )\n}\n\n/**\n * Creates a Next.js Route Handler that proxies `request` to\n * `${baseUrl}${targetPath}` at base-api, injecting the `X-Reblu-Api-Key`\n * server-side so it never reaches the browser.\n */\nexport function createProxyRoute(targetPath: string, opts: CreateProxyRouteOptions = {}) {\n const {\n method = 'POST',\n forwardSetCookie = false,\n requireJson = false,\n invalidRequestMessage = 'Solicitud no válida',\n timeoutMs = 8000,\n configurationErrorMessage = 'Error de configuración del servidor.',\n timeoutMessage = 'La solicitud ha superado el tiempo de espera.',\n proxyErrorMessage = 'Error de conexión con el servidor.',\n } = opts\n\n return async function handler(request: NextRequest): Promise<Response> {\n if (requireJson) {\n const contentType = request.headers.get('content-type') ?? ''\n if (!contentType.includes('application/json')) {\n return jsonErrorResponse(400, 'invalid_request', invalidRequestMessage)\n }\n }\n\n // Lazy, per-request env read (R6) — opts win when provided.\n const baseUrl = opts.baseUrl ?? process.env.REBLU_API_BASE_URL ?? ''\n const apiKey = opts.apiKey ?? process.env.REBLU_API_KEY ?? ''\n\n if (!baseUrl || !apiKey) {\n console.error(\n `[createProxyRoute] Missing configuration for ${targetPath}: ` +\n `${!baseUrl ? 'baseUrl/REBLU_API_BASE_URL ' : ''}${!apiKey ? 'apiKey/REBLU_API_KEY' : ''}`.trim(),\n )\n return jsonErrorResponse(500, 'missing_configuration', configurationErrorMessage)\n }\n\n const forwardedHeaders: Record<string, string> = {}\n const ua = request.headers.get('user-agent')\n if (ua) forwardedHeaders['user-agent'] = ua\n const xff = request.headers.get('x-forwarded-for')\n if (xff) forwardedHeaders['x-forwarded-for'] = xff\n const xri = request.headers.get('x-real-ip')\n if (xri) forwardedHeaders['x-real-ip'] = xri\n\n const upperMethod = method.toUpperCase()\n const body =\n upperMethod === 'GET' || upperMethod === 'HEAD' ? undefined : await request.text()\n // Forward the original query string (e.g. `?slug=x`) regardless of\n // method — `targetPath` is fixed at factory-call time, so without this a\n // GET route configured via `{ method: 'GET' }` would silently drop it.\n const search = request.nextUrl?.search ?? ''\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n\n try {\n const res = await fetch(`${baseUrl}${targetPath}${search}`, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Reblu-Api-Key': apiKey,\n ...forwardedHeaders,\n },\n ...(body ? { body } : {}),\n cache: 'no-store',\n signal: controller.signal,\n })\n\n const data = await res.text()\n const responseHeaders = new Headers({\n 'Content-Type': res.headers.get('Content-Type') ?? 'application/json',\n })\n\n if (forwardSetCookie) {\n for (const cookie of res.headers.getSetCookie()) {\n responseHeaders.append('set-cookie', cookie)\n }\n }\n\n return new Response(data, { status: res.status, headers: responseHeaders })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n console.error(`[createProxyRoute] Timed out forwarding to ${targetPath} after ${timeoutMs}ms`)\n return jsonErrorResponse(502, 'upstream_timeout', timeoutMessage)\n }\n console.error(`[createProxyRoute] Error forwarding to ${targetPath}:`, err)\n return jsonErrorResponse(502, 'proxy_error', proxyErrorMessage)\n } finally {\n clearTimeout(timer)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsGA,SAAS,kBAAkB,QAAgB,OAAe,SAA2B;AACnF,SAAO,IAAI;AAAA,IACT,KAAK,UAAU,EAAE,OAAO,SAAS,gBAAgB,OAAO,WAAW,EAAE,CAAC;AAAA,IACtE,EAAE,QAAQ,SAAS,EAAE,gBAAgB,kCAAkC,EAAE;AAAA,EAC3E;AACF;AAOO,SAAS,iBAAiB,YAAoB,OAAgC,CAAC,GAAG;AACvF,QAAM;AAAA,IACJ,SAAS;AAAA,IACT,mBAAmB;AAAA,IACnB,cAAc;AAAA,IACd,wBAAwB;AAAA,IACxB,YAAY;AAAA,IACZ,4BAA4B;AAAA,IAC5B,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,EACtB,IAAI;AAEJ,SAAO,eAAe,QAAQ,SAAyC;AACrE,QAAI,aAAa;AACf,YAAM,cAAc,QAAQ,QAAQ,IAAI,cAAc,KAAK;AAC3D,UAAI,CAAC,YAAY,SAAS,kBAAkB,GAAG;AAC7C,eAAO,kBAAkB,KAAK,mBAAmB,qBAAqB;AAAA,MACxE;AAAA,IACF;AAGA,UAAM,UAAU,KAAK,WAAW,QAAQ,IAAI,sBAAsB;AAClE,UAAM,SAAS,KAAK,UAAU,QAAQ,IAAI,iBAAiB;AAE3D,QAAI,CAAC,WAAW,CAAC,Q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handlers.ts","../src/route-handlers.ts","../src/shop/checkout-redirect.ts"],"sourcesContent":["/**\n * `@reblu/site-next/shop-route-handlers` (REB-829) — Route Handler factories\n * for the cart/checkout write flow (`/api/site/shop/{checkout, validate-cart,\n * apply-discount, check-email, order/[sessionId]}`). Every demo-site route\n * these replace (`app/api/shop/*`) either hand-rolled the SAME proxy\n * boilerplate `./route-handlers`'s `createProxyRoute` already generalizes\n * (checkout/validate-cart/apply-discount/check-email), or called\n * `proxyToBaseApi` directly for the one dynamic-path route (`order/\n * [sessionId]`) that `createProxyRoute` deliberately does not cover (its own\n * docblock: \"a per-request DYNAMIC targetPath... is genuinely out of scope\").\n * This module is the dynamic-path extension `createProxyRoute` named as a\n * gap, kept as its own file (not folded into `./server`, REB-809's filters/\n * collection glue) because it is a distinct concern — a page that only reads\n * shop data never needs these factories, and a cart/checkout integration\n * never needs the filters glue.\n *\n * Server-only, dependency-free (only `createProxyRoute`, the local\n * `./checkout-redirect` helper, and the `next/server` type) — same isolation\n * direction as `./route-handlers`/`./shop/server.ts`: this entry must NEVER\n * carry `'use client'` (see `tsup.config.ts`).\n *\n * Mirrors `createProxyRoute`'s own API-key/server-only handling verbatim —\n * `REBLU_API_KEY` is read lazily, server-side, and injected as\n * `X-Reblu-Api-Key` on the upstream fetch only; it never reaches the\n * Response these handlers return to the browser.\n *\n * // app/api/shop/checkout/route.ts\n * export const POST = createShopCheckoutRoute()\n *\n * // app/api/shop/order/[sessionId]/route.ts\n * export const GET = createShopOrderRoute()\n */\nimport type { NextRequest } from 'next/server'\nimport { createProxyRoute, type CreateProxyRouteOptions } from '../route-handlers'\nimport { DEFAULT_CHECKOUT_REDIRECT_HOSTS, isSafeCheckoutRedirectUrl } from './checkout-redirect'\n\n/** Options for a fixed-path write route. `method` is always `'POST'` here. */\nexport type ShopWriteRouteOptions = Omit<CreateProxyRouteOptions, 'method'>\n\n/**\n * `requireJson: true` by default for every write route below: the browser\n * clients these proxy for (the cart/checkout UI) always set\n * `Content-Type: application/json`, and rejecting anything else with a 400\n * BEFORE the upstream fetch is strictly safer than forwarding an\n * unparseable body to base-api. A SITE with a non-JSON caller can still pass\n * `{ requireJson: false }`.\n */\nconst DEFAULT_WRITE_OPTS: ShopWriteRouteOptions = { requireJson: true }\n\n/** Options for `createShopCheckoutRoute` — standard success/cancel URLs (REB-837) + the redirect-origin re-check (REB-836). */\nexport interface ShopCheckoutRouteOptions extends ShopWriteRouteOptions {\n /**\n * Path (relative to the resolved SITE origin — see `siteOrigin` below,\n * never a caller-supplied value, so this can never redirect off-SITE)\n * used to build a default `successUrl` when the posted body doesn't\n * already include one. The literal `{CHECKOUT_SESSION_ID}` placeholder is\n * preserved verbatim — Stripe substitutes it at redirect time, same as\n * `cartPath`'s `{cart}` shorthand in the issue brief. Normalized (REB-837\n * review fix): must resolve to a single SITE-relative path starting with\n * `/` — an absolute URL or a protocol-relative `//` is rejected (logged,\n * falls back to the default) rather than silently building an off-SITE\n * redirect.\n * @default `${cartPath}?pago=ok&session_id={CHECKOUT_SESSION_ID}`\n */\n successPath?: string\n /**\n * Path used to build a default `cancelUrl`, same normalization and origin\n * rule as `successPath`.\n * @default `${cartPath}?pago=cancelado`\n */\n cancelPath?: string\n /** Base path the `successPath`/`cancelPath` defaults are built from. @default '/cart' */\n cartPath?: string\n /**\n * Explicit SITE origin to build `successUrl`/`cancelUrl` from, overriding\n * `request.nextUrl.origin` (REB-837 review fix). Needed behind a reverse\n * proxy or when the Route Handler's own request origin doesn't match the\n * SITE's real public origin. Falls back to `NEXT_PUBLIC_SITE_URL` when\n * omitted, then to `request.nextUrl.origin`.\n */\n siteOrigin?: string\n /** Allowed hosts for base-api's returned Checkout URL. @default ['checkout.stripe.com'] */\n allowedRedirectHosts?: string[]\n /**\n * Overrides the `message` field of the 502 body returned when base-api's\n * Checkout URL fails the redirect-origin re-check.\n * @default 'Error de conexión con el proveedor de pago.'\n */\n unsafeRedirectMessage?: string\n}\n\n/**\n * Normalizes a SITE-relative path for `successPath`/`cancelPath`/`cartPath`\n * (REB-837 review fix): must start with exactly one `/`, never an absolute\n * URL (`scheme://…`) or a protocol-relative `//…` — either would let a\n * misconfigured caller build a redirect off the SITE's own origin despite\n * the origin itself being trustworthy (request-derived or explicit\n * `siteOrigin`). A path missing its leading slash is PREFIXED with one; an\n * absolute/protocol-relative path is REJECTED outright (logged once) and\n * falls back to `fallback` rather than silently building a dangerous URL.\n */\nfunction normalizeSitePath(path: string, fallback: string): string {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(path) || path.startsWith('//')) {\n console.error(\n `[createShopCheckoutRoute] Rejected an absolute/protocol-relative path \"${path}\" — using the default instead.`,\n )\n return fallback\n }\n return path.startsWith('/') ? path : `/${path}`\n}\n\nfunction unsafeRedirectResponse(message: string): Response {\n return new Response(\n JSON.stringify({ error: 'unsafe_redirect', message, correlation_id: crypto.randomUUID() }),\n { status: 502, headers: { 'Content-Type': 'application/json; charset=utf-8' } },\n )\n}\n\n/** Extracts `data.url` from a JSON response body, or `undefined` if absent/malformed. */\nfunction extractCheckoutUrl(rawBody: string): string | undefined {\n try {\n const parsed = JSON.parse(rawBody) as { data?: { url?: unknown } }\n return typeof parsed?.data?.url === 'string' ? parsed.data.url : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Transport headers that describe the UPSTREAM byte stream, not `rawBody`\n * (re-serialized text `fetch` already decoded) — forwarding them verbatim\n * would tell the browser to gunzip/measure plain JSON and break checkout.\n * Review follow-up (native review on REB-836): this is an explicit blocklist,\n * not reliance on `createProxyRoute`'s current header set, so a future change\n * to that shared factory (e.g. the parallel REB-837 work) can't silently\n * reintroduce the leak here.\n */\nconst UNSAFE_PASSTHROUGH_HEADERS = new Set(['content-encoding', 'content-length', 'transfer-encoding'])\n\n/** Copies `headers` minus {@link UNSAFE_PASSTHROUGH_HEADERS} — safe to pair with a re-serialized body. */\nfunction safeResponseHeaders(headers: Headers): Headers {\n const safe = new Headers()\n for (const [key, value] of headers.entries()) {\n if (!UNSAFE_PASSTHROUGH_HEADERS.has(key.toLowerCase())) safe.set(key, value)\n }\n return safe\n}\n\n/**\n * `POST /api/site/shop/checkout` — starts a hosted Stripe Checkout session.\n *\n * REB-837: when the posted body doesn't already carry `successUrl`/\n * `cancelUrl` (an explicit value on the body always wins — this never\n * overrides a caller that builds its own), injects them built from\n * `successPath`/`cancelPath` and the resolved SITE origin (`siteOrigin` >\n * `NEXT_PUBLIC_SITE_URL` > `request.nextUrl.origin` — see `siteOrigin`'s\n * docblock). If no origin resolves, the body is forwarded unchanged —\n * base-api's own required-field validation is the backstop, not a second\n * origin check here.\n *\n * REB-836 (defence in depth): every SITE hands the response's `url` straight\n * to `window.location.assign`, so on a successful upstream response this\n * RE-CHECKS that `url` is `https:` on an allowed host (default\n * `checkout.stripe.com`) before ever returning it to the browser — a\n * compromised/misconfigured base-api or a tampered response in transit must\n * never redirect a buyer off Stripe's domain. Mirrors `@reblu/site-client`'s\n * own `shop.checkout()` guard (`./checkout-redirect.ts`'s docblock explains\n * why this is a deliberate duplicate, not a shared import). Non-2xx upstream\n * responses (validation errors, 404s, etc.) pass through unchanged — there is\n * no redirect URL to check.\n */\nexport function createShopCheckoutRoute(opts: ShopCheckoutRouteOptions = {}) {\n const {\n successPath,\n cancelPath,\n cartPath = '/cart',\n siteOrigin,\n allowedRedirectHosts = DEFAULT_CHECKOUT_REDIRECT_HOSTS,\n unsafeRedirectMessage = 'Error de conexión con el proveedor de pago.',\n ...proxyOpts\n } = opts\n\n const resolvedCartPath = normalizeSitePath(cartPath, '/cart')\n const defaultSuccessPath = `${resolvedCartPath}?pago=ok&session_id={CHECKOUT_SESSION_ID}`\n const defaultCancelPath = `${resolvedCartPath}?pago=cancelado`\n const resolvedSuccessPath =\n successPath !== undefined ? normalizeSitePath(successPath, defaultSuccessPath) : defaultSuccessPath\n const resolvedCancelPath =\n cancelPath !== undefined ? normalizeSitePath(cancelPath, defaultCancelPath) : defaultCancelPath\n\n const proxyHandler = createProxyRoute('/api/site/shop/checkout', {\n ...DEFAULT_WRITE_OPTS,\n ...proxyOpts,\n transformBody: (rawBody, request) => {\n // Lazy, per-request (R6): `siteOrigin` wins (explicit, proxy-safe),\n // then `NEXT_PUBLIC_SITE_URL` (env fallback for a SITE behind a\n // reverse proxy where `request.nextUrl.origin` doesn't match its real\n // public origin), then the request's own origin.\n const origin = siteOrigin ?? process.env.NEXT_PUBLIC_SITE_URL ?? request.nextUrl?.origin\n if (!origin) return rawBody\n\n let parsed: Record<string, unknown>\n try {\n parsed = JSON.parse(rawBody) as Record<string, unknown>\n } catch {\n return rawBody\n }\n\n if (typeof parsed.successUrl !== 'string') {\n parsed.successUrl = `${origin}${resolvedSuccessPath}`\n }\n if (typeof parsed.cancelUrl !== 'string') {\n parsed.cancelUrl = `${origin}${resolvedCancelPath}`\n }\n return JSON.stringify(parsed)\n },\n })\n\n return async function handler(request: NextRequest): Promise<Response> {\n const response = await proxyHandler(request)\n if (!response.ok) return response\n\n const rawBody = await response.text()\n const url = extractCheckoutUrl(rawBody)\n if (!url || !isSafeCheckoutRedirectUrl(url, allowedRedirectHosts)) {\n console.error('[createShopCheckoutRoute] Blocked an unsafe checkout redirect URL')\n return unsafeRedirectResponse(unsafeRedirectMessage)\n }\n\n return new Response(rawBody, { status: response.status, headers: safeResponseHeaders(response.headers) })\n }\n}\n\n/** `POST /api/site/shop/validate-cart` — live stock/price re-check before checkout. */\nexport function createShopValidateCartRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/validate-cart', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** `POST /api/site/shop/apply-discount` — validates a discount code against the cart. */\nexport function createShopApplyDiscountRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/apply-discount', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** `POST /api/site/shop/check-email` — whether a guest's email already has an account. */\nexport function createShopCheckEmailRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/check-email', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** Options for the dynamic order-lookup route. `method` is always `'GET'`. */\nexport type ShopOrderRouteOptions = Omit<CreateProxyRouteOptions, 'method'>\n\n/**\n * `GET /api/site/shop/order/[sessionId]` — the one route in this file with a\n * per-request dynamic target path, so it can't be a one-line\n * `createProxyRoute(...)` call like the others: it reads Next's route\n * `params`, builds `/api/site/shop/order/{sessionId}` per request, and\n * delegates everything else (env, timeout, forwarding, error shaping) to\n * `createProxyRoute`.\n */\nexport function createShopOrderRoute(opts: ShopOrderRouteOptions = {}) {\n return async function handler(\n request: NextRequest,\n context: { params: Promise<{ sessionId: string }> },\n ): Promise<Response> {\n const { sessionId } = await context.params\n const targetPath = `/api/site/shop/order/${encodeURIComponent(sessionId)}`\n return createProxyRoute(targetPath, { ...opts, method: 'GET' })(request)\n }\n}\n","/**\n * `@reblu/site-next/route-handlers` — server-only, dependency-free Route\n * Handler factory (REB-510 / design doc \"site-auth-package\").\n *\n * This module MUST stay dependency-free (no `@reblu/site-ui`, no React): it is\n * imported directly by `app/api/*` Route Handler files, and its own tsup entry\n * carries NO `'use client'` directive (mirrors the `cache` subpath's R4\n * precedent for the opposite direction — see `tsup.config.ts`).\n *\n * Scope: this factory covers the `/api/site/auth/*` proxy shape specifically\n * (fixed target path, JSON body passthrough, optional `Set-Cookie` forward) —\n * the same shape as every one of demo-site's 8 auth Route Handlers. It is\n * modeled on `apps/demo-site/src/lib/api/proxy.ts` (`proxyToBaseApi`) but is\n * NOT a drop-in replacement for every one of that helper's call sites: it\n * does not support a per-request DYNAMIC `targetPath` (e.g.\n * `api/shop/order/[sessionId]/route.ts`'s `` `/api/site/shop/order/${id}` ``)\n * or an arbitrary extra-`headers` passthrough — both are genuinely out of\n * scope for REB-510 (auth only). demo-site's non-auth proxy routes keep using\n * `proxyToBaseApi` directly; only the 8 auth routes are candidates to adopt\n * this factory.\n *\n * export const POST = createProxyRoute('/api/site/auth/login')\n *\n * Deliberate behavior change vs the original (R6): `proxy.ts` reads\n * `REBLU_API_BASE_URL`/`REBLU_API_KEY` at MODULE LOAD. This factory reads them\n * LAZILY, inside the returned handler, on every request — `opts.baseUrl` /\n * `opts.apiKey` still take priority when provided.\n *\n * Why this factory reads `process.env` at all, unlike `@reblu/site-client`\n * (whose own docblock states \"the SDK never reads `process.env` itself\"):\n * `site-client` is instantiated ONCE by the consuming SITE, which already\n * owns and injects its env at that single call site. `createProxyRoute` is\n * the opposite shape on purpose — a ZERO-CONFIG one-liner meant to be called\n * once per Route Handler FILE (8+ files in a typical SITE), so requiring\n * every file to re-thread `baseUrl`/`apiKey` would defeat the \"one line\"\n * value proposition documented in the README. The env fallback is this\n * factory's deliberate ergonomic default; `opts.baseUrl`/`opts.apiKey` remain\n * available for a SITE that wants explicit, non-`process.env` control.\n *\n * Trust note on header forwarding: `X-Forwarded-For`/`X-Real-IP` are copied\n * from the incoming request VERBATIM (same as the original `proxy.ts`). On\n * Vercel the platform itself sets/overwrites these ahead of the Route\n * Handler, so they're trustworthy there — but this is a distributable SDK a\n * SITE can deploy anywhere. On a host where nothing strips inbound spoofed\n * values, a client can forge the IP base-api rate-limits on. Deploy this\n * factory only behind a platform that normalizes/overwrites these headers,\n * or in front of infra that strips client-supplied ones.\n */\nimport type { NextRequest } from 'next/server'\n\nexport interface CreateProxyRouteOptions {\n /** Overrides `REBLU_API_BASE_URL`. Read lazily per-request when omitted. */\n baseUrl?: string\n /** Overrides `REBLU_API_KEY`. Read lazily per-request when omitted. */\n apiKey?: string\n /** @default 'POST' */\n method?: string\n /** Forward upstream `Set-Cookie` headers to the browser. @default false */\n forwardSetCookie?: boolean\n /**\n * Reject non-`application/json` requests with a Spanish 400 before ever\n * reaching the network — mirrors `magic-link-exchange/route.ts`'s guard.\n * @default false\n */\n requireJson?: boolean\n /**\n * Overrides the Spanish `message` field of the `requireJson` 400 body, for\n * a non-Spanish-default SITE. The `error` code (`invalid_request`) and\n * shape stay fixed — only the human-facing text is overridable.\n * @default 'Solicitud no válida'\n */\n invalidRequestMessage?: string\n /**\n * Hard timeout (ms) for the upstream fetch, enforced via `AbortController`\n * — mirrors `@reblu/site-client`'s own `timeoutMs` (default `8000`, same\n * value). Without this, a hung base-api response would hang the SITE's\n * Route Handler indefinitely instead of degrading.\n * @default 8000\n */\n timeoutMs?: number\n /**\n * Overrides the `message` field of the 500 body returned when neither\n * `opts.baseUrl`/`opts.apiKey` nor `REBLU_API_BASE_URL`/`REBLU_API_KEY`\n * resolve to a non-empty value.\n * @default 'Error de configuración del servidor.'\n */\n configurationErrorMessage?: string\n /**\n * Overrides the `message` field of the 502 body returned when the\n * upstream fetch times out.\n * @default 'La solicitud ha superado el tiempo de espera.'\n */\n timeoutMessage?: string\n /**\n * Overrides the `message` field of the 502 body returned when the\n * upstream fetch fails for any other reason (DNS, connection refused,\n * etc.).\n * @default 'Error de conexión con el servidor.'\n */\n proxyErrorMessage?: string\n /**\n * Transform the raw request body before it is forwarded upstream (REB-837\n * — `createShopCheckoutRoute`'s successPath/cancelPath default-injection\n * is the first caller). Receives the original `request` so a transform\n * can derive values from it (e.g. `request.nextUrl.origin`). Only called\n * for a non-GET/HEAD request with a non-empty body. A thrown error is\n * logged and the ORIGINAL body is forwarded unchanged — a transform bug\n * must never turn into a hard failure for every request through this\n * route.\n */\n transformBody?: (rawBody: string, request: NextRequest) => string\n}\n\nfunction jsonErrorResponse(status: number, error: string, message: string): Response {\n return new Response(\n JSON.stringify({ error, message, correlation_id: crypto.randomUUID() }),\n { status, headers: { 'Content-Type': 'application/json; charset=utf-8' } },\n )\n}\n\n/**\n * Creates a Next.js Route Handler that proxies `request` to\n * `${baseUrl}${targetPath}` at base-api, injecting the `X-Reblu-Api-Key`\n * server-side so it never reaches the browser.\n */\nexport function createProxyRoute(targetPath: string, opts: CreateProxyRouteOptions = {}) {\n const {\n method = 'POST',\n forwardSetCookie = false,\n requireJson = false,\n invalidRequestMessage = 'Solicitud no válida',\n timeoutMs = 8000,\n configurationErrorMessage = 'Error de configuración del servidor.',\n timeoutMessage = 'La solicitud ha superado el tiempo de espera.',\n proxyErrorMessage = 'Error de conexión con el servidor.',\n } = opts\n\n return async function handler(request: NextRequest): Promise<Response> {\n if (requireJson) {\n const contentType = request.headers.get('content-type') ?? ''\n if (!contentType.includes('application/json')) {\n return jsonErrorResponse(400, 'invalid_request', invalidRequestMessage)\n }\n }\n\n // Lazy, per-request env read (R6) — opts win when provided.\n const baseUrl = opts.baseUrl ?? process.env.REBLU_API_BASE_URL ?? ''\n const apiKey = opts.apiKey ?? process.env.REBLU_API_KEY ?? ''\n\n if (!baseUrl || !apiKey) {\n console.error(\n `[createProxyRoute] Missing configuration for ${targetPath}: ` +\n `${!baseUrl ? 'baseUrl/REBLU_API_BASE_URL ' : ''}${!apiKey ? 'apiKey/REBLU_API_KEY' : ''}`.trim(),\n )\n return jsonErrorResponse(500, 'missing_configuration', configurationErrorMessage)\n }\n\n const forwardedHeaders: Record<string, string> = {}\n const ua = request.headers.get('user-agent')\n if (ua) forwardedHeaders['user-agent'] = ua\n const xff = request.headers.get('x-forwarded-for')\n if (xff) forwardedHeaders['x-forwarded-for'] = xff\n const xri = request.headers.get('x-real-ip')\n if (xri) forwardedHeaders['x-real-ip'] = xri\n\n const upperMethod = method.toUpperCase()\n let body =\n upperMethod === 'GET' || upperMethod === 'HEAD' ? undefined : await request.text()\n if (body && opts.transformBody) {\n try {\n body = opts.transformBody(body, request)\n } catch (err) {\n console.error(`[createProxyRoute] transformBody threw for ${targetPath}:`, err)\n }\n }\n // Forward the original query string (e.g. `?slug=x`) regardless of\n // method — `targetPath` is fixed at factory-call time, so without this a\n // GET route configured via `{ method: 'GET' }` would silently drop it.\n const search = request.nextUrl?.search ?? ''\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n\n try {\n const res = await fetch(`${baseUrl}${targetPath}${search}`, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Reblu-Api-Key': apiKey,\n ...forwardedHeaders,\n },\n ...(body ? { body } : {}),\n cache: 'no-store',\n signal: controller.signal,\n })\n\n const data = await res.text()\n const responseHeaders = new Headers({\n 'Content-Type': res.headers.get('Content-Type') ?? 'application/json',\n })\n\n if (forwardSetCookie) {\n for (const cookie of res.headers.getSetCookie()) {\n responseHeaders.append('set-cookie', cookie)\n }\n }\n\n return new Response(data, { status: res.status, headers: responseHeaders })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n console.error(`[createProxyRoute] Timed out forwarding to ${targetPath} after ${timeoutMs}ms`)\n return jsonErrorResponse(502, 'upstream_timeout', timeoutMessage)\n }\n console.error(`[createProxyRoute] Error forwarding to ${targetPath}:`, err)\n return jsonErrorResponse(502, 'proxy_error', proxyErrorMessage)\n } finally {\n clearTimeout(timer)\n }\n }\n}\n","/**\n * Stripe Checkout redirect-origin guard (REB-836, defence in depth) — the\n * server-side half. `createShopCheckoutRoute` re-checks base-api's Checkout\n * URL before handing it to the browser, which otherwise immediately\n * `window.location.assign`s it.\n *\n * This is a DELIBERATE DUPLICATE of `@reblu/site-client`'s\n * `isSafeCheckoutRedirectUrl` (`packages/site-client/src/checkout-redirect.ts`),\n * not a shared import: the `./shop-route-handlers` entry is dependency-free by\n * design (see `../route-handlers.ts`'s docblock — \"must stay dependency-free\n * (no `@reblu/site-ui`)... so importing it from an `app/api/*` route never\n * drags in client components\"), and pulling in `@reblu/site-client` here\n * would break that isolation. Update both together if Stripe's Checkout host\n * ever changes.\n */\n\n/** The only Checkout redirect host trusted by default. */\nexport const DEFAULT_CHECKOUT_REDIRECT_HOSTS: readonly string[] = ['checkout.stripe.com']\n\n/**\n * True only when `url` parses as an absolute URL, uses `https:`, and its\n * hostname is in `allowedHosts` (default: {@link DEFAULT_CHECKOUT_REDIRECT_HOSTS}).\n * Never throws — an unparsable `url` is simply unsafe.\n */\nexport function isSafeCheckoutRedirectUrl(\n url: string,\n allowedHosts: readonly string[] = DEFAULT_CHECKOUT_REDIRECT_HOSTS,\n): boolean {\n let parsed: URL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AC9B;AAAA,EACF,CAAC;AAED,SAAO,eAAe,QAAQ,SAAyC;AACrE,UAAM,WAAW,MAAM,aAAa,OAAO;AAC3C,QAAI,CAAC,SAAS,GAAI,QAAO;AAEzB,UAAM,UAAU,MAAM,SAAS,KAAK;AACpC,UAAM,MAAM,mBAAmB,OAAO;AACtC,QAAI,CAAC,OAAO,CAAC,0BAA0B,KAAK,oBAAoB,GAAG;AACjE,cAAQ,MAAM,mEAAmE;AACjF,aAAO,uBAAuB,qBAAqB;AAAA,IACrD;AAEA,WAAO,IAAI,SAAS,SAAS,EAAE,QAAQ,SAAS,QAAQ,SAAS,oBAAoB,SAAS,OAAO,EAAE,CAAC;AAAA,EAC1G;AACF;AAGO,SAAS,4BAA4B,OAA8B,CAAC,GAAG;AAC5E,SAAO,iBAAiB,gCAAgC,EAAE,GAAG,oBAAoB,GAAG,KAAK,CAAC;AAC5F;AAGO,SAAS,6BAA6B,OAA8B,CAAC,GAAG;AAC7E,SAAO,iBAAiB,iCAAiC,EAAE,GAAG,oBAAoB,GAAG,KAAK,CAAC;AAC7F;AAGO,SAAS,0BAA0B,OAA8B,CAAC,GAAG;AAC1E,SAAO,iBAAiB,8BAA8B,EAAE,GAAG,oBAAoB,GAAG,KAAK,CAAC;AAC1F;AAaO,SAAS,qBAAqB,OAA8B,CAAC,GAAG;AACrE,SAAO,eAAe,QACpB,SACA,SACmB;AACnB,UAAM,EAAE,UAAU,IAAI,MAAM,QAAQ;AACpC,UAAM,aAAa,wBAAwB,mBAAmB,SAAS,CAAC;AACxE,WAAO,iBAAiB,YAAY,EAAE,GAAG,MAAM,QAAQ,MAAM,CAAC,EAAE,OAAO;AAAA,EACzE;AACF;","names":[]}
|
|
@@ -17,9 +17,10 @@ import { CreateProxyRouteOptions } from './route-handlers.cjs';
|
|
|
17
17
|
* shop data never needs these factories, and a cart/checkout integration
|
|
18
18
|
* never needs the filters glue.
|
|
19
19
|
*
|
|
20
|
-
* Server-only, dependency-free (only `createProxyRoute
|
|
21
|
-
* type) — same isolation
|
|
22
|
-
* this entry must NEVER
|
|
20
|
+
* Server-only, dependency-free (only `createProxyRoute`, the local
|
|
21
|
+
* `./checkout-redirect` helper, and the `next/server` type) — same isolation
|
|
22
|
+
* direction as `./route-handlers`/`./shop/server.ts`: this entry must NEVER
|
|
23
|
+
* carry `'use client'` (see `tsup.config.ts`).
|
|
23
24
|
*
|
|
24
25
|
* Mirrors `createProxyRoute`'s own API-key/server-only handling verbatim —
|
|
25
26
|
* `REBLU_API_KEY` is read lazily, server-side, and injected as
|
|
@@ -35,8 +36,71 @@ import { CreateProxyRouteOptions } from './route-handlers.cjs';
|
|
|
35
36
|
|
|
36
37
|
/** Options for a fixed-path write route. `method` is always `'POST'` here. */
|
|
37
38
|
type ShopWriteRouteOptions = Omit<CreateProxyRouteOptions, 'method'>;
|
|
38
|
-
/**
|
|
39
|
-
|
|
39
|
+
/** Options for `createShopCheckoutRoute` — standard success/cancel URLs (REB-837) + the redirect-origin re-check (REB-836). */
|
|
40
|
+
interface ShopCheckoutRouteOptions extends ShopWriteRouteOptions {
|
|
41
|
+
/**
|
|
42
|
+
* Path (relative to the resolved SITE origin — see `siteOrigin` below,
|
|
43
|
+
* never a caller-supplied value, so this can never redirect off-SITE)
|
|
44
|
+
* used to build a default `successUrl` when the posted body doesn't
|
|
45
|
+
* already include one. The literal `{CHECKOUT_SESSION_ID}` placeholder is
|
|
46
|
+
* preserved verbatim — Stripe substitutes it at redirect time, same as
|
|
47
|
+
* `cartPath`'s `{cart}` shorthand in the issue brief. Normalized (REB-837
|
|
48
|
+
* review fix): must resolve to a single SITE-relative path starting with
|
|
49
|
+
* `/` — an absolute URL or a protocol-relative `//` is rejected (logged,
|
|
50
|
+
* falls back to the default) rather than silently building an off-SITE
|
|
51
|
+
* redirect.
|
|
52
|
+
* @default `${cartPath}?pago=ok&session_id={CHECKOUT_SESSION_ID}`
|
|
53
|
+
*/
|
|
54
|
+
successPath?: string;
|
|
55
|
+
/**
|
|
56
|
+
* Path used to build a default `cancelUrl`, same normalization and origin
|
|
57
|
+
* rule as `successPath`.
|
|
58
|
+
* @default `${cartPath}?pago=cancelado`
|
|
59
|
+
*/
|
|
60
|
+
cancelPath?: string;
|
|
61
|
+
/** Base path the `successPath`/`cancelPath` defaults are built from. @default '/cart' */
|
|
62
|
+
cartPath?: string;
|
|
63
|
+
/**
|
|
64
|
+
* Explicit SITE origin to build `successUrl`/`cancelUrl` from, overriding
|
|
65
|
+
* `request.nextUrl.origin` (REB-837 review fix). Needed behind a reverse
|
|
66
|
+
* proxy or when the Route Handler's own request origin doesn't match the
|
|
67
|
+
* SITE's real public origin. Falls back to `NEXT_PUBLIC_SITE_URL` when
|
|
68
|
+
* omitted, then to `request.nextUrl.origin`.
|
|
69
|
+
*/
|
|
70
|
+
siteOrigin?: string;
|
|
71
|
+
/** Allowed hosts for base-api's returned Checkout URL. @default ['checkout.stripe.com'] */
|
|
72
|
+
allowedRedirectHosts?: string[];
|
|
73
|
+
/**
|
|
74
|
+
* Overrides the `message` field of the 502 body returned when base-api's
|
|
75
|
+
* Checkout URL fails the redirect-origin re-check.
|
|
76
|
+
* @default 'Error de conexión con el proveedor de pago.'
|
|
77
|
+
*/
|
|
78
|
+
unsafeRedirectMessage?: string;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* `POST /api/site/shop/checkout` — starts a hosted Stripe Checkout session.
|
|
82
|
+
*
|
|
83
|
+
* REB-837: when the posted body doesn't already carry `successUrl`/
|
|
84
|
+
* `cancelUrl` (an explicit value on the body always wins — this never
|
|
85
|
+
* overrides a caller that builds its own), injects them built from
|
|
86
|
+
* `successPath`/`cancelPath` and the resolved SITE origin (`siteOrigin` >
|
|
87
|
+
* `NEXT_PUBLIC_SITE_URL` > `request.nextUrl.origin` — see `siteOrigin`'s
|
|
88
|
+
* docblock). If no origin resolves, the body is forwarded unchanged —
|
|
89
|
+
* base-api's own required-field validation is the backstop, not a second
|
|
90
|
+
* origin check here.
|
|
91
|
+
*
|
|
92
|
+
* REB-836 (defence in depth): every SITE hands the response's `url` straight
|
|
93
|
+
* to `window.location.assign`, so on a successful upstream response this
|
|
94
|
+
* RE-CHECKS that `url` is `https:` on an allowed host (default
|
|
95
|
+
* `checkout.stripe.com`) before ever returning it to the browser — a
|
|
96
|
+
* compromised/misconfigured base-api or a tampered response in transit must
|
|
97
|
+
* never redirect a buyer off Stripe's domain. Mirrors `@reblu/site-client`'s
|
|
98
|
+
* own `shop.checkout()` guard (`./checkout-redirect.ts`'s docblock explains
|
|
99
|
+
* why this is a deliberate duplicate, not a shared import). Non-2xx upstream
|
|
100
|
+
* responses (validation errors, 404s, etc.) pass through unchanged — there is
|
|
101
|
+
* no redirect URL to check.
|
|
102
|
+
*/
|
|
103
|
+
declare function createShopCheckoutRoute(opts?: ShopCheckoutRouteOptions): (request: NextRequest) => Promise<Response>;
|
|
40
104
|
/** `POST /api/site/shop/validate-cart` — live stock/price re-check before checkout. */
|
|
41
105
|
declare function createShopValidateCartRoute(opts?: ShopWriteRouteOptions): (request: NextRequest) => Promise<Response>;
|
|
42
106
|
/** `POST /api/site/shop/apply-discount` — validates a discount code against the cart. */
|
|
@@ -59,4 +123,4 @@ declare function createShopOrderRoute(opts?: ShopOrderRouteOptions): (request: N
|
|
|
59
123
|
}>;
|
|
60
124
|
}) => Promise<Response>;
|
|
61
125
|
|
|
62
|
-
export { type ShopOrderRouteOptions, type ShopWriteRouteOptions, createShopApplyDiscountRoute, createShopCheckEmailRoute, createShopCheckoutRoute, createShopOrderRoute, createShopValidateCartRoute };
|
|
126
|
+
export { type ShopCheckoutRouteOptions, type ShopOrderRouteOptions, type ShopWriteRouteOptions, createShopApplyDiscountRoute, createShopCheckEmailRoute, createShopCheckoutRoute, createShopOrderRoute, createShopValidateCartRoute };
|
|
@@ -17,9 +17,10 @@ import { CreateProxyRouteOptions } from './route-handlers.js';
|
|
|
17
17
|
* shop data never needs these factories, and a cart/checkout integration
|
|
18
18
|
* never needs the filters glue.
|
|
19
19
|
*
|
|
20
|
-
* Server-only, dependency-free (only `createProxyRoute
|
|
21
|
-
* type) — same isolation
|
|
22
|
-
* this entry must NEVER
|
|
20
|
+
* Server-only, dependency-free (only `createProxyRoute`, the local
|
|
21
|
+
* `./checkout-redirect` helper, and the `next/server` type) — same isolation
|
|
22
|
+
* direction as `./route-handlers`/`./shop/server.ts`: this entry must NEVER
|
|
23
|
+
* carry `'use client'` (see `tsup.config.ts`).
|
|
23
24
|
*
|
|
24
25
|
* Mirrors `createProxyRoute`'s own API-key/server-only handling verbatim —
|
|
25
26
|
* `REBLU_API_KEY` is read lazily, server-side, and injected as
|
|
@@ -35,8 +36,71 @@ import { CreateProxyRouteOptions } from './route-handlers.js';
|
|
|
35
36
|
|
|
36
37
|
/** Options for a fixed-path write route. `method` is always `'POST'` here. */
|
|
37
38
|
type ShopWriteRouteOptions = Omit<CreateProxyRouteOptions, 'method'>;
|
|
38
|
-
/**
|
|
39
|
-
|
|
39
|
+
/** Options for `createShopCheckoutRoute` — standard success/cancel URLs (REB-837) + the redirect-origin re-check (REB-836). */
|
|
40
|
+
interface ShopCheckoutRouteOptions extends ShopWriteRouteOptions {
|
|
41
|
+
/**
|
|
42
|
+
* Path (relative to the resolved SITE origin — see `siteOrigin` below,
|
|
43
|
+
* never a caller-supplied value, so this can never redirect off-SITE)
|
|
44
|
+
* used to build a default `successUrl` when the posted body doesn't
|
|
45
|
+
* already include one. The literal `{CHECKOUT_SESSION_ID}` placeholder is
|
|
46
|
+
* preserved verbatim — Stripe substitutes it at redirect time, same as
|
|
47
|
+
* `cartPath`'s `{cart}` shorthand in the issue brief. Normalized (REB-837
|
|
48
|
+
* review fix): must resolve to a single SITE-relative path starting with
|
|
49
|
+
* `/` — an absolute URL or a protocol-relative `//` is rejected (logged,
|
|
50
|
+
* falls back to the default) rather than silently building an off-SITE
|
|
51
|
+
* redirect.
|
|
52
|
+
* @default `${cartPath}?pago=ok&session_id={CHECKOUT_SESSION_ID}`
|
|
53
|
+
*/
|
|
54
|
+
successPath?: string;
|
|
55
|
+
/**
|
|
56
|
+
* Path used to build a default `cancelUrl`, same normalization and origin
|
|
57
|
+
* rule as `successPath`.
|
|
58
|
+
* @default `${cartPath}?pago=cancelado`
|
|
59
|
+
*/
|
|
60
|
+
cancelPath?: string;
|
|
61
|
+
/** Base path the `successPath`/`cancelPath` defaults are built from. @default '/cart' */
|
|
62
|
+
cartPath?: string;
|
|
63
|
+
/**
|
|
64
|
+
* Explicit SITE origin to build `successUrl`/`cancelUrl` from, overriding
|
|
65
|
+
* `request.nextUrl.origin` (REB-837 review fix). Needed behind a reverse
|
|
66
|
+
* proxy or when the Route Handler's own request origin doesn't match the
|
|
67
|
+
* SITE's real public origin. Falls back to `NEXT_PUBLIC_SITE_URL` when
|
|
68
|
+
* omitted, then to `request.nextUrl.origin`.
|
|
69
|
+
*/
|
|
70
|
+
siteOrigin?: string;
|
|
71
|
+
/** Allowed hosts for base-api's returned Checkout URL. @default ['checkout.stripe.com'] */
|
|
72
|
+
allowedRedirectHosts?: string[];
|
|
73
|
+
/**
|
|
74
|
+
* Overrides the `message` field of the 502 body returned when base-api's
|
|
75
|
+
* Checkout URL fails the redirect-origin re-check.
|
|
76
|
+
* @default 'Error de conexión con el proveedor de pago.'
|
|
77
|
+
*/
|
|
78
|
+
unsafeRedirectMessage?: string;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* `POST /api/site/shop/checkout` — starts a hosted Stripe Checkout session.
|
|
82
|
+
*
|
|
83
|
+
* REB-837: when the posted body doesn't already carry `successUrl`/
|
|
84
|
+
* `cancelUrl` (an explicit value on the body always wins — this never
|
|
85
|
+
* overrides a caller that builds its own), injects them built from
|
|
86
|
+
* `successPath`/`cancelPath` and the resolved SITE origin (`siteOrigin` >
|
|
87
|
+
* `NEXT_PUBLIC_SITE_URL` > `request.nextUrl.origin` — see `siteOrigin`'s
|
|
88
|
+
* docblock). If no origin resolves, the body is forwarded unchanged —
|
|
89
|
+
* base-api's own required-field validation is the backstop, not a second
|
|
90
|
+
* origin check here.
|
|
91
|
+
*
|
|
92
|
+
* REB-836 (defence in depth): every SITE hands the response's `url` straight
|
|
93
|
+
* to `window.location.assign`, so on a successful upstream response this
|
|
94
|
+
* RE-CHECKS that `url` is `https:` on an allowed host (default
|
|
95
|
+
* `checkout.stripe.com`) before ever returning it to the browser — a
|
|
96
|
+
* compromised/misconfigured base-api or a tampered response in transit must
|
|
97
|
+
* never redirect a buyer off Stripe's domain. Mirrors `@reblu/site-client`'s
|
|
98
|
+
* own `shop.checkout()` guard (`./checkout-redirect.ts`'s docblock explains
|
|
99
|
+
* why this is a deliberate duplicate, not a shared import). Non-2xx upstream
|
|
100
|
+
* responses (validation errors, 404s, etc.) pass through unchanged — there is
|
|
101
|
+
* no redirect URL to check.
|
|
102
|
+
*/
|
|
103
|
+
declare function createShopCheckoutRoute(opts?: ShopCheckoutRouteOptions): (request: NextRequest) => Promise<Response>;
|
|
40
104
|
/** `POST /api/site/shop/validate-cart` — live stock/price re-check before checkout. */
|
|
41
105
|
declare function createShopValidateCartRoute(opts?: ShopWriteRouteOptions): (request: NextRequest) => Promise<Response>;
|
|
42
106
|
/** `POST /api/site/shop/apply-discount` — validates a discount code against the cart. */
|
|
@@ -59,4 +123,4 @@ declare function createShopOrderRoute(opts?: ShopOrderRouteOptions): (request: N
|
|
|
59
123
|
}>;
|
|
60
124
|
}) => Promise<Response>;
|
|
61
125
|
|
|
62
|
-
export { type ShopOrderRouteOptions, type ShopWriteRouteOptions, createShopApplyDiscountRoute, createShopCheckEmailRoute, createShopCheckoutRoute, createShopOrderRoute, createShopValidateCartRoute };
|
|
126
|
+
export { type ShopCheckoutRouteOptions, type ShopOrderRouteOptions, type ShopWriteRouteOptions, createShopApplyDiscountRoute, createShopCheckEmailRoute, createShopCheckoutRoute, createShopOrderRoute, createShopValidateCartRoute };
|
|
@@ -39,7 +39,14 @@ function createProxyRoute(targetPath, opts = {}) {
|
|
|
39
39
|
const xri = request.headers.get("x-real-ip");
|
|
40
40
|
if (xri) forwardedHeaders["x-real-ip"] = xri;
|
|
41
41
|
const upperMethod = method.toUpperCase();
|
|
42
|
-
|
|
42
|
+
let body = upperMethod === "GET" || upperMethod === "HEAD" ? void 0 : await request.text();
|
|
43
|
+
if (body && opts.transformBody) {
|
|
44
|
+
try {
|
|
45
|
+
body = opts.transformBody(body, request);
|
|
46
|
+
} catch (err) {
|
|
47
|
+
console.error(`[createProxyRoute] transformBody threw for ${targetPath}:`, err);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
43
50
|
const search = request.nextUrl?.search ?? "";
|
|
44
51
|
const controller = new AbortController();
|
|
45
52
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
@@ -78,10 +85,98 @@ function createProxyRoute(targetPath, opts = {}) {
|
|
|
78
85
|
};
|
|
79
86
|
}
|
|
80
87
|
|
|
88
|
+
// src/shop/checkout-redirect.ts
|
|
89
|
+
var DEFAULT_CHECKOUT_REDIRECT_HOSTS = ["checkout.stripe.com"];
|
|
90
|
+
function isSafeCheckoutRedirectUrl(url, allowedHosts = DEFAULT_CHECKOUT_REDIRECT_HOSTS) {
|
|
91
|
+
let parsed;
|
|
92
|
+
try {
|
|
93
|
+
parsed = new URL(url);
|
|
94
|
+
} catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
return parsed.protocol === "https:" && allowedHosts.includes(parsed.hostname);
|
|
98
|
+
}
|
|
99
|
+
|
|
81
100
|
// src/shop/route-handlers.ts
|
|
82
101
|
var DEFAULT_WRITE_OPTS = { requireJson: true };
|
|
102
|
+
function normalizeSitePath(path, fallback) {
|
|
103
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path) || path.startsWith("//")) {
|
|
104
|
+
console.error(
|
|
105
|
+
`[createShopCheckoutRoute] Rejected an absolute/protocol-relative path "${path}" \u2014 using the default instead.`
|
|
106
|
+
);
|
|
107
|
+
return fallback;
|
|
108
|
+
}
|
|
109
|
+
return path.startsWith("/") ? path : `/${path}`;
|
|
110
|
+
}
|
|
111
|
+
function unsafeRedirectResponse(message) {
|
|
112
|
+
return new Response(
|
|
113
|
+
JSON.stringify({ error: "unsafe_redirect", message, correlation_id: crypto.randomUUID() }),
|
|
114
|
+
{ status: 502, headers: { "Content-Type": "application/json; charset=utf-8" } }
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
function extractCheckoutUrl(rawBody) {
|
|
118
|
+
try {
|
|
119
|
+
const parsed = JSON.parse(rawBody);
|
|
120
|
+
return typeof parsed?.data?.url === "string" ? parsed.data.url : void 0;
|
|
121
|
+
} catch {
|
|
122
|
+
return void 0;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
var UNSAFE_PASSTHROUGH_HEADERS = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding"]);
|
|
126
|
+
function safeResponseHeaders(headers) {
|
|
127
|
+
const safe = new Headers();
|
|
128
|
+
for (const [key, value] of headers.entries()) {
|
|
129
|
+
if (!UNSAFE_PASSTHROUGH_HEADERS.has(key.toLowerCase())) safe.set(key, value);
|
|
130
|
+
}
|
|
131
|
+
return safe;
|
|
132
|
+
}
|
|
83
133
|
function createShopCheckoutRoute(opts = {}) {
|
|
84
|
-
|
|
134
|
+
const {
|
|
135
|
+
successPath,
|
|
136
|
+
cancelPath,
|
|
137
|
+
cartPath = "/cart",
|
|
138
|
+
siteOrigin,
|
|
139
|
+
allowedRedirectHosts = DEFAULT_CHECKOUT_REDIRECT_HOSTS,
|
|
140
|
+
unsafeRedirectMessage = "Error de conexi\xF3n con el proveedor de pago.",
|
|
141
|
+
...proxyOpts
|
|
142
|
+
} = opts;
|
|
143
|
+
const resolvedCartPath = normalizeSitePath(cartPath, "/cart");
|
|
144
|
+
const defaultSuccessPath = `${resolvedCartPath}?pago=ok&session_id={CHECKOUT_SESSION_ID}`;
|
|
145
|
+
const defaultCancelPath = `${resolvedCartPath}?pago=cancelado`;
|
|
146
|
+
const resolvedSuccessPath = successPath !== void 0 ? normalizeSitePath(successPath, defaultSuccessPath) : defaultSuccessPath;
|
|
147
|
+
const resolvedCancelPath = cancelPath !== void 0 ? normalizeSitePath(cancelPath, defaultCancelPath) : defaultCancelPath;
|
|
148
|
+
const proxyHandler = createProxyRoute("/api/site/shop/checkout", {
|
|
149
|
+
...DEFAULT_WRITE_OPTS,
|
|
150
|
+
...proxyOpts,
|
|
151
|
+
transformBody: (rawBody, request) => {
|
|
152
|
+
const origin = siteOrigin ?? process.env.NEXT_PUBLIC_SITE_URL ?? request.nextUrl?.origin;
|
|
153
|
+
if (!origin) return rawBody;
|
|
154
|
+
let parsed;
|
|
155
|
+
try {
|
|
156
|
+
parsed = JSON.parse(rawBody);
|
|
157
|
+
} catch {
|
|
158
|
+
return rawBody;
|
|
159
|
+
}
|
|
160
|
+
if (typeof parsed.successUrl !== "string") {
|
|
161
|
+
parsed.successUrl = `${origin}${resolvedSuccessPath}`;
|
|
162
|
+
}
|
|
163
|
+
if (typeof parsed.cancelUrl !== "string") {
|
|
164
|
+
parsed.cancelUrl = `${origin}${resolvedCancelPath}`;
|
|
165
|
+
}
|
|
166
|
+
return JSON.stringify(parsed);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
return async function handler(request) {
|
|
170
|
+
const response = await proxyHandler(request);
|
|
171
|
+
if (!response.ok) return response;
|
|
172
|
+
const rawBody = await response.text();
|
|
173
|
+
const url = extractCheckoutUrl(rawBody);
|
|
174
|
+
if (!url || !isSafeCheckoutRedirectUrl(url, allowedRedirectHosts)) {
|
|
175
|
+
console.error("[createShopCheckoutRoute] Blocked an unsafe checkout redirect URL");
|
|
176
|
+
return unsafeRedirectResponse(unsafeRedirectMessage);
|
|
177
|
+
}
|
|
178
|
+
return new Response(rawBody, { status: response.status, headers: safeResponseHeaders(response.headers) });
|
|
179
|
+
};
|
|
85
180
|
}
|
|
86
181
|
function createShopValidateCartRoute(opts = {}) {
|
|
87
182
|
return createProxyRoute("/api/site/shop/validate-cart", { ...DEFAULT_WRITE_OPTS, ...opts });
|