@ecomweb/storefront-kit 0.14.1 → 0.16.0

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.
Files changed (69) hide show
  1. package/README.md +25 -1
  2. package/bin/check-client-bundle-lib.d.mts +16 -0
  3. package/bin/check-client-bundle-lib.mjs +58 -0
  4. package/bin/check-client-bundle.d.mts +11 -0
  5. package/bin/check-client-bundle.mjs +8 -0
  6. package/dist/api/client.js +52 -1
  7. package/dist/api/client.js.map +1 -1
  8. package/dist/api/index.js.map +1 -1
  9. package/dist/api/proxy-guard.js +29 -0
  10. package/dist/api/proxy-guard.js.map +1 -0
  11. package/dist/api/proxy-routes.js +126 -0
  12. package/dist/api/proxy-routes.js.map +1 -0
  13. package/dist/api/proxy.js +17 -4
  14. package/dist/api/proxy.js.map +1 -1
  15. package/dist/api/server-sdk.js +41 -0
  16. package/dist/api/server-sdk.js.map +1 -0
  17. package/dist/api/store-preview-header.js.map +1 -1
  18. package/dist/auth/sdk.js +21 -6
  19. package/dist/auth/sdk.js.map +1 -1
  20. package/dist/auth/session-refresh.js +7 -4
  21. package/dist/auth/session-refresh.js.map +1 -1
  22. package/dist/cart/api.js.map +1 -1
  23. package/dist/checkout/get-payment-state.js +4 -8
  24. package/dist/checkout/get-payment-state.js.map +1 -1
  25. package/dist/checkout/initiate-gateway-payment.js +5 -7
  26. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  27. package/dist/checkout/order-handoff.js.map +1 -1
  28. package/dist/checkout/payment-redirect.js.map +1 -1
  29. package/dist/client-info.js +1 -1
  30. package/dist/config/public.js +2 -0
  31. package/dist/config/public.js.map +1 -1
  32. package/dist/config/schema.js +16 -4
  33. package/dist/config/schema.js.map +1 -1
  34. package/dist/config/secret-guard.js +20 -0
  35. package/dist/config/secret-guard.js.map +1 -0
  36. package/dist/config/server.js +15 -8
  37. package/dist/config/server.js.map +1 -1
  38. package/dist/config.d.ts +14 -4
  39. package/dist/config.js +2 -0
  40. package/dist/config.js.map +1 -1
  41. package/dist/index.d.ts +27 -68
  42. package/dist/index.js.map +1 -1
  43. package/dist/middleware/create-storefront-middleware.js +14 -3
  44. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  45. package/dist/middleware.d.ts +2 -2
  46. package/dist/{mode-DXo-EhTJ.d.ts → mode-oVZCQxrc.d.ts} +1 -1
  47. package/dist/orders/api-client.js +3 -3
  48. package/dist/orders/api-client.js.map +1 -1
  49. package/dist/orders/bank-transfer.js +1 -1
  50. package/dist/orders/bank-transfer.js.map +1 -1
  51. package/dist/orders/use-order-status.js +2 -2
  52. package/dist/orders/use-order-status.js.map +1 -1
  53. package/dist/promotions/use-promotion-validation.js +2 -2
  54. package/dist/promotions/use-promotion-validation.js.map +1 -1
  55. package/dist/request/served-store.js +5 -0
  56. package/dist/request/served-store.js.map +1 -0
  57. package/dist/{schema-DIF0CZNV.d.ts → schema-B3nAYiwT.d.ts} +1 -1
  58. package/dist/sdk.js +3 -3
  59. package/dist/sdk.js.map +1 -1
  60. package/dist/server/routes.js +16 -9
  61. package/dist/server/routes.js.map +1 -1
  62. package/dist/server.d.ts +38 -5
  63. package/dist/server.js +2 -0
  64. package/dist/server.js.map +1 -1
  65. package/dist/shipping/use-shipping-calculation.js +2 -2
  66. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  67. package/package.json +6 -2
  68. package/dist/api/server-client.js +0 -162
  69. package/dist/api/server-client.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/proxy.ts"],"sourcesContent":["import \"server-only\";\n\nimport { NextResponse, type NextRequest } from \"next/server\";\n\nimport {\n authCookiePathFor,\n readAuthCookies,\n writeAuthCookies,\n} from \"../auth/cookies\";\nimport {\n clientIpFrom,\n FORWARDER_SECRET_HEADER,\n forwardingHeaders,\n} from \"../auth/client-ip\";\nimport { backendBaseUrl, createAuthApi, storefrontApiKey } from \"../auth/sdk\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport {\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewTokenFrom,\n} from \"../stores/store-preview-cookie\";\n\n/**\n * Same-origin server proxy for the storefront's authenticated backend calls.\n *\n * Session tokens live in httpOnly, store-scoped cookies (`lib/auth/cookies.ts`)\n * that browser JS cannot read, and the backend runs on a different origin, so a\n * direct browser->backend call carries neither cookie nor bearer token. The\n * browser therefore calls `/store/<storeRef>/api/backend/<path>` — same origin,\n * so the cookie is sent — and this handler, running on the server, attaches the\n * bearer token and the storefront API key before forwarding.\n *\n * This is the same shape as `lib/auth/route-handlers.ts`, which is why this\n * module is the third (and last) place allowed to touch auth cookies. It still\n * goes through `lib/auth/cookies.ts` rather than naming cookies itself.\n */\n\n/**\n * Never forwarded upstream:\n * - hop-by-hop headers (RFC 9110 s7.6.1) are per-connection by definition;\n * - `host`/`content-length`/`accept-encoding` are owned by `fetch`;\n * - `origin` describes the browser->proxy hop, not the proxy->backend one;\n * - `authorization` and `cookie` because the httpOnly cookie is the ONLY\n * trusted source of identity here — a browser-supplied `Authorization`\n * header must never reach the backend through this route;\n * - `x-storefront-api-key` because the server attaches its own;\n * - `x-forwarded-for` and `x-real-ip` because neither is a Fetch-forbidden\n * header name, so browser JS can set them — and the backend derives the\n * client IP from exactly those, for the auth throttle key and for API-key IP\n * allowlisting. They are dropped here and re-set below from the value the\n * platform edge gave *this* server. Block first, then set: the reverse order\n * would hand the choice back to the caller;\n * - `x-ecomweb-forwarder-secret` because it is what makes the backend trust\n * `x-forwarded-for`. Only this server attaches it, from a server-only env\n * var; a browser-supplied one must never pass through, least of all when\n * the var is unset here and nothing would overwrite it;\n * - `x-store-preview` and the middleware's internal store preview token\n * header, because the token sent upstream comes only from this request's\n * cookie or the middleware's stamp (`storePreviewTokenFor` below).\n */\nconst BLOCKED_REQUEST_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n \"content-length\",\n \"accept-encoding\",\n \"origin\",\n \"authorization\",\n \"cookie\",\n \"x-storefront-api-key\",\n \"x-forwarded-for\",\n \"x-real-ip\",\n \"cf-connecting-ip\",\n FORWARDER_SECRET_HEADER,\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n]);\n\nconst METHODS_WITH_BODY = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\nfunction jsonError(status: number, message: string, code: string) {\n return NextResponse.json({ code, message }, { status });\n}\n\n/**\n * Rebuilds the upstream URL from the catch-all segments. Next has already\n * percent-decoded them, so `..` arrives literally and is rejected here; the\n * origin/prefix check afterwards is the backstop that keeps this route from\n * becoming an open forward proxy.\n */\nfunction resolveTarget(segments: string[], search: string): URL | null {\n if (segments.length === 0) return null;\n\n for (const segment of segments) {\n if (\n segment === \"\" ||\n segment === \".\" ||\n segment === \"..\" ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\")\n ) {\n return null;\n }\n }\n\n const base = new URL(backendBaseUrl());\n const prefix = base.pathname.replace(/\\/$/, \"\");\n const target = new URL(\n `${prefix}/${segments.map(encodeURIComponent).join(\"/\")}`,\n base\n );\n\n if (target.origin !== base.origin) return null;\n if (!target.pathname.startsWith(`${prefix}/`)) return null;\n\n target.search = search;\n return target;\n}\n\n/**\n * The store preview token to send upstream as `X-Store-Preview`, or null:\n * a preview host's token the middleware stamped, else the store preview\n * cookie, else the theme preview cookie (`storePreviewTokenFrom`).\n *\n * The stamp is trusted only under `/store/<ref>/`: the middleware's matcher\n * covers that path, and every response there that reaches this route drops\n * a client's copy of the header first. Root `/api/*` (the single-store\n * proxy) is outside the matcher, so the header there is whatever the client\n * sent, and only the cookies count.\n */\nexport function storePreviewTokenFor(\n request: NextRequest,\n storeRef: string\n): string | null {\n const stamped = request.nextUrl.pathname.startsWith(\n `${multiTenantStorePath(storeRef)}/`\n );\n return storePreviewTokenFrom(\n request.cookies,\n stamped\n ? request\n : {\n headers: {\n get: name =>\n name.toLowerCase() === STORE_PREVIEW_TOKEN_HEADER\n ? null\n : request.headers.get(name),\n },\n }\n );\n}\n\nfunction forwardedHeaders(\n request: NextRequest,\n storeRef: string,\n accessToken?: string\n) {\n const headers = new Headers();\n\n request.headers.forEach((value, key) => {\n if (!BLOCKED_REQUEST_HEADERS.has(key.toLowerCase())) {\n headers.set(key, value);\n }\n });\n\n headers.set(\"x-storefront-api-key\", storefrontApiKey());\n\n // Set only after the blocklist has stripped whatever the browser sent.\n for (const [key, value] of Object.entries(\n forwardingHeaders(clientIpFrom(request.headers))\n )) {\n headers.set(key, value);\n }\n\n // Set only after the blocklist has dropped whatever the browser sent.\n const previewToken = storePreviewTokenFor(request, storeRef);\n if (previewToken) headers.set(STORE_PREVIEW_HEADER, previewToken);\n\n if (accessToken) headers.set(\"authorization\", `Bearer ${accessToken}`);\n\n return headers;\n}\n\ninterface UpstreamResult {\n status: number;\n body: string;\n contentType: string | null;\n}\n\nasync function callUpstream(\n request: NextRequest,\n storeRef: string,\n target: URL,\n body: string | undefined,\n accessToken?: string\n): Promise<UpstreamResult> {\n const response = await fetch(target, {\n method: request.method,\n headers: forwardedHeaders(request, storeRef, accessToken),\n body,\n cache: \"no-store\",\n redirect: \"manual\",\n });\n\n return {\n status: response.status,\n body: await response.text(),\n contentType: response.headers.get(\"content-type\"),\n };\n}\n\n/**\n * Passes the backend's status and body through untouched — callers read\n * `{ code, message }` off the body, so rewriting it would break their error\n * handling.\n */\nfunction respond(result: UpstreamResult): NextResponse {\n return new NextResponse(result.body || null, {\n status: result.status,\n headers: result.contentType\n ? { \"content-type\": result.contentType }\n : undefined,\n });\n}\n\nexport async function handleBackendProxy(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const target = resolveTarget(segments, request.nextUrl.search);\n\n if (!target) {\n return jsonError(400, \"Invalid proxy path\", \"PROXY_INVALID_PATH\");\n }\n\n // Buffered once so the 401 retry below can replay it.\n const body = METHODS_WITH_BODY.has(request.method)\n ? await request.text()\n : undefined;\n\n const tokens = readAuthCookies(\n request.cookies,\n storeRef,\n authCookiePathFor(request, storeRef)\n );\n\n let result: UpstreamResult;\n\n try {\n result = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n tokens?.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n // Anonymous callers and non-401 answers are done: public endpoints must keep\n // working through this proxy.\n if (result.status !== 401 || !tokens) return respond(result);\n\n // Exactly one refresh + retry. Never a loop.\n const refreshed = await createAuthApi(\n storeRef,\n clientIpFrom(request.headers)\n ).refresh(tokens.refresh_token);\n\n // A failed refresh does NOT clear the cookies, because \"failed\" and \"the\n // session is dead\" are not the same thing here. `SessionService.rotate()`\n // revokes the presented refresh token before issuing its replacement, so a\n // token can be rejected simply for having lost a race: `proxy.ts` refreshes\n // near-expiry tokens on every matched request, this route refreshes again on\n // a 401, and a page load fires several of both at once. Each of those reads\n // the refresh token from its own request snapshot, so whichever rotation\n // lands second presents an already-revoked token through no fault of the\n // shopper. Clearing here would log them out mid-page.\n //\n // Leaving stale cookies in place is safe: the `(protected)` layout resolves\n // the session server-side on the next navigation and redirects to /login if\n // it really is gone, and signing in overwrites them.\n if (\n !refreshed.success ||\n !refreshed.data?.access_token ||\n !refreshed.data.refresh_token\n ) {\n return respond(result);\n }\n\n let retry: UpstreamResult;\n\n try {\n retry = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n refreshed.data.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n const response = respond(retry);\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: refreshed.data.access_token,\n refresh_token: refreshed.data.refresh_token,\n },\n authCookiePathFor(request, storeRef)\n );\n\n return response;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,oBAAsC;AAE/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAA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E,cAAc,UAAU,KAAK;AAAA,MAC7B,eAAe,UAAU,KAAK;AAAA,IAChC;AAAA,IACA,kBAAkB,SAAS,QAAQ;AAAA,EACrC;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/api/proxy.ts"],"sourcesContent":["import \"server-only\";\n\nimport { NextResponse, type NextRequest } from \"next/server\";\n\nimport {\n authCookiePathFor,\n readAuthCookies,\n writeAuthCookies,\n} from \"../auth/cookies\";\nimport {\n clientIpFrom,\n FORWARDER_SECRET_HEADER,\n forwardingHeaders,\n} from \"../auth/client-ip\";\nimport { backendBaseUrl, createAuthApi, storefrontSecretKey } from \"../auth/sdk\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport {\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewTokenFrom,\n} from \"../stores/store-preview-cookie\";\nimport { isSameOriginRequest, proxyNotFound } from \"./proxy-guard\";\nimport { matchProxiedRoute } from \"./proxy-routes\";\n\n/**\n * Same-origin server proxy for every private storefront call the browser\n * makes, guest calls included (cart, checkout, orders, payments, review\n * invitations, account), plus the public reads that need the shopper's\n * session.\n *\n * The browser holds only the publishable key, and session tokens live in\n * httpOnly, store-scoped cookies (`lib/auth/cookies.ts`) that browser JS\n * cannot read. So the browser calls `/store/<storeRef>/api/backend/<path>`\n * (same origin, so the cookie is sent) and this handler, on the server,\n * attaches the storefront secret key and the bearer token before forwarding.\n * In the shared app that secret is a platform key valid for every store, so\n * the proxy is locked down: only same-origin callers, only the routes in\n * `PROXIED_STOREFRONT_ROUTES` (closed by default), and only for the store\n * this request serves (the route's store, which `createBackendProxy` has\n * already checked against the middleware's stamp, must equal the store the\n * forwarded API path names). Every refusal is the same 404 `NOT_FOUND`.\n *\n * This is the same shape as `lib/auth/route-handlers.ts`, which is why this\n * module is the third (and last) place allowed to touch auth cookies. It still\n * goes through `lib/auth/cookies.ts` rather than naming cookies itself.\n */\n\n/**\n * Never forwarded upstream:\n * - hop-by-hop headers (RFC 9110 s7.6.1) are per-connection by definition;\n * - `host`/`content-length`/`accept-encoding` are owned by `fetch`;\n * - `origin` describes the browser->proxy hop, not the proxy->backend one;\n * - `authorization` and `cookie` because the httpOnly cookie is the ONLY\n * trusted source of identity here — a browser-supplied `Authorization`\n * header must never reach the backend through this route;\n * - `x-storefront-api-key` because the server attaches its own;\n * - `x-forwarded-for` and `x-real-ip` because neither is a Fetch-forbidden\n * header name, so browser JS can set them — and the backend derives the\n * client IP from exactly those, for the auth throttle key and for API-key IP\n * allowlisting. They are dropped here and re-set below from the value the\n * platform edge gave *this* server. Block first, then set: the reverse order\n * would hand the choice back to the caller;\n * - `x-ecomweb-forwarder-secret` because it is what makes the backend trust\n * `x-forwarded-for`. Only this server attaches it, from a server-only env\n * var; a browser-supplied one must never pass through, least of all when\n * the var is unset here and nothing would overwrite it;\n * - `x-store-preview` and the middleware's internal store preview token\n * header, because the token sent upstream comes only from this request's\n * cookie or the middleware's stamp (`storePreviewTokenFor` below).\n */\nconst BLOCKED_REQUEST_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n \"content-length\",\n \"accept-encoding\",\n \"origin\",\n \"authorization\",\n \"cookie\",\n \"x-storefront-api-key\",\n \"x-forwarded-for\",\n \"x-real-ip\",\n \"cf-connecting-ip\",\n FORWARDER_SECRET_HEADER,\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n]);\n\nconst METHODS_WITH_BODY = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\nfunction jsonError(status: number, message: string, code: string) {\n return NextResponse.json({ code, message }, { status });\n}\n\ntype RefusalReason =\n | \"cross-site\"\n | \"invalid-path\"\n | \"not-proxied\"\n | \"store-mismatch\";\n\n/**\n * Logs the reason, store and method only: never the path (it can carry review\n * tokens and order codes), headers or body.\n */\nfunction refuse(\n reason: RefusalReason,\n storeRef: string,\n method: string\n): NextResponse {\n console.debug(\"backend proxy refused\", { reason, storeRef, method });\n return proxyNotFound();\n}\n\n/**\n * Rebuilds the upstream URL from the catch-all segments, each one passed\n * through `encodeURIComponent`. Next has already percent-decoded them, so\n * `..` arrives literally and is rejected here; the origin/prefix check\n * afterwards is the backstop that keeps this route from becoming an open\n * forward proxy.\n */\nfunction resolveTarget(segments: string[], search: string): URL | null {\n if (segments.length === 0) return null;\n\n for (const segment of segments) {\n if (\n segment === \"\" ||\n segment === \".\" ||\n segment === \"..\" ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\")\n ) {\n return null;\n }\n }\n\n const base = new URL(backendBaseUrl());\n const prefix = base.pathname.replace(/\\/$/, \"\");\n const target = new URL(\n `${prefix}/${segments.map(encodeURIComponent).join(\"/\")}`,\n base\n );\n\n if (target.origin !== base.origin) return null;\n if (!target.pathname.startsWith(`${prefix}/`)) return null;\n\n target.search = search;\n return target;\n}\n\n/**\n * The store preview token to send upstream as `X-Store-Preview`, or null:\n * a preview host's token the middleware stamped, else the store preview\n * cookie, else the theme preview cookie (`storePreviewTokenFrom`).\n *\n * The stamp is trusted only under `/store/<ref>/`: the middleware's matcher\n * covers that path, and every response there that reaches this route drops\n * a client's copy of the header first. Root `/api/*` (the single-store\n * proxy) is outside the matcher, so the header there is whatever the client\n * sent, and only the cookies count.\n */\nexport function storePreviewTokenFor(\n request: NextRequest,\n storeRef: string\n): string | null {\n const stamped = request.nextUrl.pathname.startsWith(\n `${multiTenantStorePath(storeRef)}/`\n );\n return storePreviewTokenFrom(\n request.cookies,\n stamped\n ? request\n : {\n headers: {\n get: name =>\n name.toLowerCase() === STORE_PREVIEW_TOKEN_HEADER\n ? null\n : request.headers.get(name),\n },\n }\n );\n}\n\nfunction forwardedHeaders(\n request: NextRequest,\n storeRef: string,\n accessToken?: string\n) {\n const headers = new Headers();\n\n request.headers.forEach((value, key) => {\n if (!BLOCKED_REQUEST_HEADERS.has(key.toLowerCase())) {\n headers.set(key, value);\n }\n });\n\n headers.set(\"x-storefront-api-key\", storefrontSecretKey());\n\n // Set only after the blocklist has stripped whatever the browser sent.\n for (const [key, value] of Object.entries(\n forwardingHeaders(clientIpFrom(request.headers))\n )) {\n headers.set(key, value);\n }\n\n // Set only after the blocklist has dropped whatever the browser sent.\n const previewToken = storePreviewTokenFor(request, storeRef);\n if (previewToken) headers.set(STORE_PREVIEW_HEADER, previewToken);\n\n if (accessToken) headers.set(\"authorization\", `Bearer ${accessToken}`);\n\n return headers;\n}\n\ninterface UpstreamResult {\n status: number;\n body: string;\n contentType: string | null;\n}\n\nasync function callUpstream(\n request: NextRequest,\n storeRef: string,\n target: URL,\n body: string | undefined,\n accessToken?: string\n): Promise<UpstreamResult> {\n const response = await fetch(target, {\n method: request.method,\n headers: forwardedHeaders(request, storeRef, accessToken),\n body,\n cache: \"no-store\",\n redirect: \"manual\",\n });\n\n return {\n status: response.status,\n body: await response.text(),\n contentType: response.headers.get(\"content-type\"),\n };\n}\n\n/**\n * Passes the backend's status and body through untouched — callers read\n * `{ code, message }` off the body, so rewriting it would break their error\n * handling.\n */\nfunction respond(result: UpstreamResult): NextResponse {\n return new NextResponse(result.body || null, {\n status: result.status,\n headers: result.contentType\n ? { \"content-type\": result.contentType }\n : undefined,\n });\n}\n\n/**\n * Forwards one browser call to the API under the storefront secret key, or\n * answers 404 `NOT_FOUND` when the caller is not same-origin, the path is\n * malformed or not in `PROXIED_STOREFRONT_ROUTES`, or the path names a store\n * other than `storeRef`. Retries once after a token refresh on a 401.\n */\nexport async function handleBackendProxy(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const method = request.method;\n if (!isSameOriginRequest(request)) {\n return refuse(\"cross-site\", storeRef, method);\n }\n\n const target = resolveTarget(segments, request.nextUrl.search);\n if (!target) return refuse(\"invalid-path\", storeRef, method);\n\n const match = matchProxiedRoute(method, segments);\n if (!match) return refuse(\"not-proxied\", storeRef, method);\n // The API picks the store from the forwarded path, not from this route.\n if (match.storeRef !== storeRef) {\n return refuse(\"store-mismatch\", storeRef, method);\n }\n\n // Buffered once so the 401 retry below can replay it.\n const body = METHODS_WITH_BODY.has(request.method)\n ? await request.text()\n : undefined;\n\n const tokens = readAuthCookies(\n request.cookies,\n storeRef,\n authCookiePathFor(request, storeRef)\n );\n\n let result: UpstreamResult;\n\n try {\n result = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n tokens?.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n // Anonymous callers and non-401 answers are done: public endpoints must keep\n // working through this proxy.\n if (result.status !== 401 || !tokens) return respond(result);\n\n // Exactly one refresh + retry. Never a loop.\n const refreshed = await createAuthApi(\n storeRef,\n clientIpFrom(request.headers)\n ).refresh(tokens.refresh_token);\n\n // A failed refresh does NOT clear the cookies, because \"failed\" and \"the\n // session is dead\" are not the same thing here. `SessionService.rotate()`\n // revokes the presented refresh token before issuing its replacement, so a\n // token can be rejected simply for having lost a race: `proxy.ts` refreshes\n // near-expiry tokens on every matched request, this route refreshes again on\n // a 401, and a page load fires several of both at once. Each of those reads\n // the refresh token from its own request snapshot, so whichever rotation\n // lands second presents an already-revoked token through no fault of the\n // shopper. Clearing here would log them out mid-page.\n //\n // Leaving stale cookies in place is safe: the `(protected)` layout resolves\n // the session server-side on the next navigation and redirects to /login if\n // it really is gone, and signing in overwrites them.\n if (\n !refreshed.success ||\n !refreshed.data?.access_token ||\n !refreshed.data.refresh_token\n ) {\n return respond(result);\n }\n\n let retry: UpstreamResult;\n\n try {\n retry = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n refreshed.data.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n const response = respond(retry);\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: refreshed.data.access_token,\n refresh_token: refreshed.data.refresh_token,\n },\n authCookiePathFor(request,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,WAAW,OAAO,CAAC,OAAQ,QAAO,QAAQ,MAAM;AAG3D,QAAM,YAAY,MAAM;AAAA,IACtB;AAAA,IACA,aAAa,QAAQ,OAAO;AAAA,EAC9B,EAAE,QAAQ,OAAO,aAAa;AAe9B,MACE,CAAC,UAAU,WACX,CAAC,UAAU,MAAM,gBACjB,CAAC,UAAU,KAAK,eAChB;AACA,WAAO,QAAQ,MAAM;AAAA,EACvB;AAEA,MAAI;AAEJ,MAAI;AACF,YAAQ,MAAM;AAAA,MACZ;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ;AAAA,MACR,UAAU,KAAK;AAAA,IACjB;AAAA,EACF,QAAQ;AACN,WAAO,UAAU,KAAK,2BAA2B,sBAAsB;AAAA,EACzE;AAEA,QAAM,WAAW,QAAQ,KAAK;AAE9B;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,MACE,cAAc,UAAU,KAAK;AAAA,MAC7B,eAAe,UAAU,KAAK;AAAA,IAChC;AAAA,IACA,kBAAkB,SAAS,QAAQ;AAAA,EACrC;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,41 @@
1
+ import "server-only";
2
+ import { createEcomwebServerSdk } from "@ecomweb/sdk";
3
+ import { clientIpFrom } from "../auth/client-ip.js";
4
+ import { authHttpClient, storefrontSecretKey } from "../auth/sdk.js";
5
+ import { KIT_CLIENT_TOKEN } from "../client-info.js";
6
+ import { readStorePreviewToken } from "../stores/read-store-preview-token.js";
7
+ const SHOPPER_CALL_ON_SERVER = {
8
+ success: false,
9
+ error: {
10
+ statusCode: 401,
11
+ error: "SDK_SHOPPER_CALL_ON_SERVER",
12
+ message: "Shopper calls run in the browser: use createStoreSdk(storeRef)"
13
+ }
14
+ };
15
+ const shopperCallsRefused = {
16
+ get: async () => SHOPPER_CALL_ON_SERVER,
17
+ post: async () => SHOPPER_CALL_ON_SERVER,
18
+ put: async () => SHOPPER_CALL_ON_SERVER,
19
+ patch: async () => SHOPPER_CALL_ON_SERVER,
20
+ delete: async () => SHOPPER_CALL_ON_SERVER
21
+ };
22
+ function serverSdkFor(clientIp, previewToken) {
23
+ return createEcomwebServerSdk({
24
+ publicHttp: authHttpClient(clientIp, previewToken),
25
+ authHttp: shopperCallsRefused,
26
+ secretKey: storefrontSecretKey(),
27
+ clientInfo: KIT_CLIENT_TOKEN
28
+ });
29
+ }
30
+ async function getServerSdk() {
31
+ const { headers } = await import("next/headers");
32
+ return serverSdkFor(
33
+ clientIpFrom(await headers()),
34
+ await readStorePreviewToken()
35
+ );
36
+ }
37
+ export {
38
+ getServerSdk,
39
+ serverSdkFor
40
+ };
41
+ //# sourceMappingURL=server-sdk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/api/server-sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { createEcomwebServerSdk } from \"@ecomweb/sdk\";\nimport type { ApiResponse, EcomwebServerSdk, IHttpClient } from \"@ecomweb/sdk\";\nimport { clientIpFrom } from \"../auth/client-ip\";\nimport { authHttpClient, storefrontSecretKey } from \"../auth/sdk\";\nimport { KIT_CLIENT_TOKEN } from \"../client-info\";\nimport { readStorePreviewToken } from \"../stores/read-store-preview-token\";\n\nconst SHOPPER_CALL_ON_SERVER: ApiResponse<never> = {\n success: false,\n error: {\n statusCode: 401,\n error: \"SDK_SHOPPER_CALL_ON_SERVER\",\n message:\n \"Shopper calls run in the browser: use createStoreSdk(storeRef)\",\n },\n};\n\n/** Answers every shopper-side call with the same 401: a server has no shopper session. */\nconst shopperCallsRefused: IHttpClient = {\n get: async () => SHOPPER_CALL_ON_SERVER,\n post: async () => SHOPPER_CALL_ON_SERVER,\n put: async () => SHOPPER_CALL_ON_SERVER,\n patch: async () => SHOPPER_CALL_ON_SERVER,\n delete: async () => SHOPPER_CALL_ON_SERVER,\n};\n\n/** Internal: builds the server SDK for one request's shopper IP and preview token. */\nexport function serverSdkFor(\n clientIp?: string,\n previewToken?: string | null\n): EcomwebServerSdk {\n return createEcomwebServerSdk({\n publicHttp: authHttpClient(clientIp, previewToken),\n authHttp: shopperCallsRefused,\n secretKey: storefrontSecretKey(),\n clientInfo: KIT_CLIENT_TOKEN,\n });\n}\n\n/**\n * The server SDK for the current request, signed with the storefront secret\n * key, for private reads in server components and route handlers (for example\n * a review invitation by token). The shopper's IP and the store preview token\n * are taken from the request.\n *\n * Shopper-side methods (cart, orders, addresses and the like) do not work\n * here: a server has no shopper session, so they reject with\n * `SDK_SHOPPER_CALL_ON_SERVER`. Use `createStoreSdk(storeRef)` in the browser.\n *\n * @example\n * ```ts\n * import { getServerSdk } from \"@ecomweb/storefront-kit/server\";\n *\n * const sdk = await getServerSdk();\n * const invitation = await sdk.reviews.getReviewInvitation(storeRef, token);\n * ```\n *\n * @returns The server SDK for this request\n * @throws Error when the storefront secret key is not set\n */\nexport async function getServerSdk(): Promise<EcomwebServerSdk> {\n const { headers } = await import(\"next/headers\");\n return serverSdkFor(\n clientIpFrom(await headers()),\n await readStorePreviewToken()\n );\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,2BAA2B;AACpD,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AAEtC,MAAM,yBAA6C;AAAA,EACjD,SAAS;AAAA,EACT,OAAO;AAAA,IACL,YAAY;AAAA,IACZ,OAAO;AAAA,IACP,SACE;AAAA,EACJ;AACF;AAGA,MAAM,sBAAmC;AAAA,EACvC,KAAK,YAAY;AAAA,EACjB,MAAM,YAAY;AAAA,EAClB,KAAK,YAAY;AAAA,EACjB,OAAO,YAAY;AAAA,EACnB,QAAQ,YAAY;AACtB;AAGO,SAAS,aACd,UACA,cACkB;AAClB,SAAO,uBAAuB;AAAA,IAC5B,YAAY,eAAe,UAAU,YAAY;AAAA,IACjD,UAAU;AAAA,IACV,WAAW,oBAAoB;AAAA,IAC/B,YAAY;AAAA,EACd,CAAC;AACH;AAuBA,eAAsB,eAA0C;AAC9D,QAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,cAAc;AAC/C,SAAO;AAAA,IACL,aAAa,MAAM,QAAQ,CAAC;AAAA,IAC5B,MAAM,sBAAsB;AAAA,EAC9B;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/store-preview-header.ts"],"sourcesContent":["import { storePreviewTokenFrom } from \"../stores/store-preview-cookie\";\n\n/**\n * The browser's store preview token, which the layout hands over through\n * `StorefrontKitProvider` (see `storePreviewToken` there). Module-level: one\n * browser tab is one store. It stays set after the store opens until the\n * next layout render passes null (a reload); accepted: an open store needs\n * no token, so the API's answers do not change, only the kit's preview\n * cues lag in a tab left open across the opening.\n */\nlet browserToken: string | null = null;\n\n/**\n * Sets the token the browser's kit clients send as `X-Store-Preview`. Does\n * nothing on the server: a server module is shared by every request, so a\n * value set there would reach other shoppers.\n */\nexport function setBrowserStorePreviewToken(token: string | null): void {\n if (typeof window === \"undefined\") return;\n browserToken = token;\n}\n\n/**\n * True in the browser while a store preview token is set: the shopper is a\n * previewer, and the API refuses every write. The cart and checkout check\n * this to refuse a write without sending it.\n */\nexport function isBrowserStorePreview(): boolean {\n return typeof window !== \"undefined\" && browserToken !== null;\n}\n\n/**\n * Fetches a fresh preview token, set by `StorefrontKitProvider` only on a\n * theme preview host, whose token lasts 1 h (the app re-renders the layout,\n * which hands the new token over). A link preview's 24 h cookie has none.\n */\nlet renewer: (() => void) | null = null;\nlet lastRenewalAt: number | null = null;\n\n/** The shortest gap between two renewals a 403 asks for. */\nconst RENEWAL_THROTTLE_MS = 60_000;\n\n/** Sets or clears the renewer; a new one may renew at once. */\nexport function setStorePreviewRenewer(renew: (() => void) | null): void {\n renewer = renew;\n lastRenewalAt = null;\n}\n\n/**\n * Asks for a fresh preview token after a read was refused with\n * `STORE_COMING_SOON`. False when there is no renewer: the preview is over.\n * Otherwise true, and the renewer runs at most once per minute, so a page\n * whose reads all fail together renews once.\n */\nexport function requestStorePreviewRenewal(): boolean {\n if (!renewer) return false;\n const now = Date.now();\n if (lastRenewalAt === null || now - lastRenewalAt >= RENEWAL_THROTTLE_MS) {\n lastRenewalAt = now;\n renewer();\n }\n return true;\n}\n\n/**\n * The token this call should send as `X-Store-Preview`, or null. In the\n * browser, the one the layout handed over. On the server, the request's own\n * (`storePreviewTokenFrom`: a preview host's stamped token, else the store\n * preview cookie, else the theme preview cookie). Outside a request scope\n * (build time), `next/headers` throws and this is null.\n *\n * In the middleware it does not throw: Next 16 runs the middleware inside a\n * request store, so `next/headers` is the middleware's own incoming\n * request, before any sanitising, and this returns whatever token the\n * client sent, a forged `STORE_PREVIEW_TOKEN_HEADER` included. So every SDK\n * call the middleware makes must pass `SKIP_STORE_PREVIEW` or an explicit\n * `X-Store-Preview` header (as getStoreByHost, lookupRedirect and\n * getStoreSubdomain do).\n */\nexport async function currentStorePreviewToken(): Promise<string | null> {\n if (typeof window !== \"undefined\") return browserToken;\n try {\n // Imported lazily: this module is in the browser bundle too (as in\n // api/server-client.ts).\n const { cookies, headers } = await import(\"next/headers\");\n return storePreviewTokenFrom(await cookies(), { headers: await headers() });\n } catch {\n return null;\n }\n}\n"],"mappings":"AAAA,SAAS,6BAA6B;AAUtC,IAAI,eAA8B;AAO3B,SAAS,4BAA4B,OAA4B;AACtE,MAAI,OAAO,WAAW,YAAa;AACnC,iBAAe;AACjB;AAOO,SAAS,wBAAiC;AAC/C,SAAO,OAAO,WAAW,eAAe,iBAAiB;AAC3D;AAOA,IAAI,UAA+B;AACnC,IAAI,gBAA+B;AAGnC,MAAM,sBAAsB;AAGrB,SAAS,uBAAuB,OAAkC;AACvE,YAAU;AACV,kBAAgB;AAClB;AAQO,SAAS,6BAAsC;AACpD,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,kBAAkB,QAAQ,MAAM,iBAAiB,qBAAqB;AACxE,oBAAgB;AAChB,YAAQ;AAAA,EACV;AACA,SAAO;AACT;AAiBA,eAAsB,2BAAmD;AACvE,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI;AAGF,UAAM,EAAE,SAAS,QAAQ,IAAI,MAAM,OAAO,cAAc;AACxD,WAAO,sBAAsB,MAAM,QAAQ,GAAG,EAAE,SAAS,MAAM,QAAQ,EAAE,CAAC;AAAA,EAC5E,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/api/store-preview-header.ts"],"sourcesContent":["import { storePreviewTokenFrom } from \"../stores/store-preview-cookie\";\n\n/**\n * The browser's store preview token, which the layout hands over through\n * `StorefrontKitProvider` (see `storePreviewToken` there). Module-level: one\n * browser tab is one store. It stays set after the store opens until the\n * next layout render passes null (a reload); accepted: an open store needs\n * no token, so the API's answers do not change, only the kit's preview\n * cues lag in a tab left open across the opening.\n */\nlet browserToken: string | null = null;\n\n/**\n * Sets the token the browser's kit clients send as `X-Store-Preview`. Does\n * nothing on the server: a server module is shared by every request, so a\n * value set there would reach other shoppers.\n */\nexport function setBrowserStorePreviewToken(token: string | null): void {\n if (typeof window === \"undefined\") return;\n browserToken = token;\n}\n\n/**\n * True in the browser while a store preview token is set: the shopper is a\n * previewer, and the API refuses every write. The cart and checkout check\n * this to refuse a write without sending it.\n */\nexport function isBrowserStorePreview(): boolean {\n return typeof window !== \"undefined\" && browserToken !== null;\n}\n\n/**\n * Fetches a fresh preview token, set by `StorefrontKitProvider` only on a\n * theme preview host, whose token lasts 1 h (the app re-renders the layout,\n * which hands the new token over). A link preview's 24 h cookie has none.\n */\nlet renewer: (() => void) | null = null;\nlet lastRenewalAt: number | null = null;\n\n/** The shortest gap between two renewals a 403 asks for. */\nconst RENEWAL_THROTTLE_MS = 60_000;\n\n/** Sets or clears the renewer; a new one may renew at once. */\nexport function setStorePreviewRenewer(renew: (() => void) | null): void {\n renewer = renew;\n lastRenewalAt = null;\n}\n\n/**\n * Asks for a fresh preview token after a read was refused with\n * `STORE_COMING_SOON`. False when there is no renewer: the preview is over.\n * Otherwise true, and the renewer runs at most once per minute, so a page\n * whose reads all fail together renews once.\n */\nexport function requestStorePreviewRenewal(): boolean {\n if (!renewer) return false;\n const now = Date.now();\n if (lastRenewalAt === null || now - lastRenewalAt >= RENEWAL_THROTTLE_MS) {\n lastRenewalAt = now;\n renewer();\n }\n return true;\n}\n\n/**\n * The token this call should send as `X-Store-Preview`, or null. In the\n * browser, the one the layout handed over. On the server, the request's own\n * (`storePreviewTokenFrom`: a preview host's stamped token, else the store\n * preview cookie, else the theme preview cookie). Outside a request scope\n * (build time), `next/headers` throws and this is null.\n *\n * In the middleware it does not throw: Next 16 runs the middleware inside a\n * request store, so `next/headers` is the middleware's own incoming\n * request, before any sanitising, and this returns whatever token the\n * client sent, a forged `STORE_PREVIEW_TOKEN_HEADER` included. So every SDK\n * call the middleware makes must pass `SKIP_STORE_PREVIEW` or an explicit\n * `X-Store-Preview` header (as getStoreByHost, lookupRedirect and\n * getStoreSubdomain do).\n */\nexport async function currentStorePreviewToken(): Promise<string | null> {\n if (typeof window !== \"undefined\") return browserToken;\n try {\n // Imported lazily: this module is in the browser bundle too (as in\n // api/server-sdk.ts).\n const { cookies, headers } = await import(\"next/headers\");\n return storePreviewTokenFrom(await cookies(), { headers: await headers() });\n } catch {\n return null;\n }\n}\n"],"mappings":"AAAA,SAAS,6BAA6B;AAUtC,IAAI,eAA8B;AAO3B,SAAS,4BAA4B,OAA4B;AACtE,MAAI,OAAO,WAAW,YAAa;AACnC,iBAAe;AACjB;AAOO,SAAS,wBAAiC;AAC/C,SAAO,OAAO,WAAW,eAAe,iBAAiB;AAC3D;AAOA,IAAI,UAA+B;AACnC,IAAI,gBAA+B;AAGnC,MAAM,sBAAsB;AAGrB,SAAS,uBAAuB,OAAkC;AACvE,YAAU;AACV,kBAAgB;AAClB;AAQO,SAAS,6BAAsC;AACpD,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,kBAAkB,QAAQ,MAAM,iBAAiB,qBAAqB;AACxE,oBAAgB;AAChB,YAAQ;AAAA,EACV;AACA,SAAO;AACT;AAiBA,eAAsB,2BAAmD;AACvE,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI;AAGF,UAAM,EAAE,SAAS,QAAQ,IAAI,MAAM,OAAO,cAAc;AACxD,WAAO,sBAAsB,MAAM,QAAQ,GAAG,EAAE,SAAS,MAAM,QAAQ,EAAE,CAAC;AAAA,EAC5E,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
package/dist/auth/sdk.js CHANGED
@@ -8,16 +8,26 @@ import { STORE_PREVIEW_HEADER } from "../stores/store-preview-cookie.js";
8
8
  function backendBaseUrl() {
9
9
  return publicConfig().apiUrl;
10
10
  }
11
- function storefrontApiKey() {
12
- return serverConfig().platformApiKey;
11
+ function storefrontSecretKey() {
12
+ const key = serverConfig().secretKey;
13
+ if (!key) {
14
+ throw new Error(
15
+ "The storefront secret key is not set (PLATFORM_SECRET_KEY or ECOMWEB_SECRET_KEY)"
16
+ );
17
+ }
18
+ return key;
19
+ }
20
+ function backendUrl(path) {
21
+ const base = backendBaseUrl().replace(/\/+$/, "");
22
+ return `${base}${path.startsWith("/") ? path : `/${path}`}`;
13
23
  }
14
24
  async function send(method, url, data, options, clientIp, previewToken) {
15
25
  try {
16
- const response = await fetch(`${backendBaseUrl()}${url}`, {
26
+ const response = await fetch(backendUrl(url), {
17
27
  method,
18
28
  headers: {
19
29
  "Content-Type": "application/json",
20
- "x-storefront-api-key": storefrontApiKey(),
30
+ "x-storefront-api-key": storefrontSecretKey(),
21
31
  // A store preview opens a coming soon store for reads only, so the
22
32
  // token rides on GETs (auth config, me) and never on writes.
23
33
  ...previewToken && method === "GET" ? { [STORE_PREVIEW_HEADER]: previewToken } : {},
@@ -49,7 +59,12 @@ async function send(method, url, data, options, clientIp, previewToken) {
49
59
  }
50
60
  };
51
61
  }
52
- return { success: true, data: body };
62
+ return {
63
+ success: true,
64
+ data: body,
65
+ // fetch's Headers yields lowercase names.
66
+ headers: Object.fromEntries(response.headers.entries())
67
+ };
53
68
  } catch (error) {
54
69
  return {
55
70
  success: false,
@@ -79,6 +94,6 @@ export {
79
94
  authHttpClient,
80
95
  backendBaseUrl,
81
96
  createAuthApi,
82
- storefrontApiKey
97
+ storefrontSecretKey
83
98
  };
84
99
  //# sourceMappingURL=sdk.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi, withClientHeader } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { KIT_CLIENT_TOKEN } from \"../client-info\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\nimport { STORE_PREVIEW_HEADER } from \"../stores/store-preview-cookie\";\n\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * StorefrontApiKeyGuard fronts every customer-auth route and also resolves\n * :storeRef into request.storeId, so a missing key fails before auth runs.\n *\n * Only NEXT_PUBLIC_PLATFORM_API_KEY exists in this repo today (see .env /\n * .env.example, lib/api/client.ts, lib/api/server-client.ts). PLATFORM_API_KEY\n * is checked first so a server-only key can be introduced later without\n * another code change.\n */\nexport function storefrontApiKey(): string {\n return serverConfig().platformApiKey;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string,\n previewToken?: string | null\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(`${backendBaseUrl()}${url}`, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontApiKey(),\n // A store preview opens a coming soon store for reads only, so the\n // token rides on GETs (auth config, me) and never on writes.\n ...(previewToken && method === \"GET\"\n ? { [STORE_PREVIEW_HEADER]: previewToken }\n : {}),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return { success: true, data: body as T };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(\n clientIp?: string,\n previewToken?: string | null\n): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp, previewToken),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n * @param previewToken the request's store preview token\n * (`storePreviewTokenFrom`), sent as `X-Store-Preview` on GETs so a\n * previewer of a coming soon store still gets the auth config and `me`.\n */\nexport function createAuthApi(\n storeRef: string,\n clientIp?: string,\n previewToken?: string | null\n): AuthApi {\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WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO;AAAA,QACL,SAAS,iBAAiB,QAAQ,MAAM,UAAU;AAAA,QAClD,YAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,eACd,UACA,cACa;AACb,SAAO;AAAA,IACL,KAAK,CAAI,KAAa,YACpB,KAAQ,OAAO,KAAK,QAAW,SAAS,UAAU,YAAY;AAAA,IAChE,MAAM,CAAI,KAAa,MAAgB,YACrC,KAAQ,QAAQ,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC9C,KAAK,CAAI,KAAa,MAAgB,YACpC,KAAQ,OAAO,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC7C,OAAO,CAAI,KAAa,MAAgB,YACtC,KAAQ,SAAS,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC/C,QAAQ,CAAI,KAAa,YACvB,KAAQ,UAAU,KAAK,QAAW,SAAS,QAAQ;AAAA,EACvD;AACF;AASO,SAAS,cACd,UACA,UACA,cACS;AACT,SAAO,IAAI;AAAA,IACT,iBAAiB,eAAe,UAAU,YAAY,GAAG,gBAAgB;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi, withClientHeader } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { KIT_CLIENT_TOKEN } from \"../client-info\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\nimport { STORE_PREVIEW_HEADER } from \"../stores/store-preview-cookie\";\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * The key the server signs every backend call with (`x-storefront-api-key`):\n * PLATFORM_SECRET_KEY in the shared app, ECOMWEB_SECRET_KEY in a single-store\n * site. Builds hold none, so an empty one throws here, at use.\n */\nexport function storefrontSecretKey(): string {\n const key = serverConfig().secretKey;\n if (!key) {\n throw new Error(\n \"The storefront secret key is not set (PLATFORM_SECRET_KEY or ECOMWEB_SECRET_KEY)\"\n );\n }\n return key;\n}\n\n/**\n * Joins the backend origin and an SDK path with exactly one slash. Plain\n * string concatenation (unlike axios's baseURL join) turns a path without a\n * leading slash into `.../api/v1public/...`.\n */\nfunction backendUrl(path: string): string {\n const base = backendBaseUrl().replace(/\\/+$/, \"\");\n return `${base}${path.startsWith(\"/\") ? path : `/${path}`}`;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string,\n previewToken?: string | null\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(backendUrl(url), {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontSecretKey(),\n // A store preview opens a coming soon store for reads only, so the\n // token rides on GETs (auth config, me) and never on writes.\n ...(previewToken && method === \"GET\"\n ? { [STORE_PREVIEW_HEADER]: previewToken }\n : {}),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return {\n success: true,\n data: body as T,\n // fetch's Headers yields lowercase names.\n headers: Object.fromEntries(response.headers.entries()),\n };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(\n clientIp?: string,\n previewToken?: string | null\n): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp, previewToken),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n * @param previewToken the request's store preview token\n * (`storePreviewTokenFrom`), sent as `X-Store-Preview` on GETs so a\n * previewer of a coming soon store still gets the auth config and `me`.\n */\nexport function createAuthApi(\n storeRef: string,\n clientIp?: string,\n previewToken?: string | null\n): AuthApi {\n return new AuthApi(\n withClientHeader(authHttpClient(clientIp, previewToken), KIT_CLIENT_TOKEN),\n storeRef\n );\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,SAAS,wBAAwB;AAE1C,SAAS,yBAAyB;AAClC,SAAS,wBAAwB;AACjC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AAO9B,SAAS,iBAAyB;AACvC,SAAO,aAAa,EAAE;AACxB;AAOO,SAAS,sBAA8B;AAC5C,QAAM,MAAM,aAAa,EAAE;AAC3B,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAOA,SAAS,WAAW,MAAsB;AACxC,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AAS,eACd,UACA,cACa;AACb,SAAO;AAAA,IACL,KAAK,CAAI,KAAa,YACpB,KAAQ,OAAO,KAAK,QAAW,SAAS,UAAU,YAAY;AAAA,IAChE,MAAM,CAAI,KAAa,MAAgB,YACrC,KAAQ,QAAQ,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC9C,KAAK,CAAI,KAAa,MAAgB,YACpC,KAAQ,OAAO,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC7C,OAAO,CAAI,KAAa,MAAgB,YACtC,KAAQ,SAAS,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC/C,QAAQ,CAAI,KAAa,YACvB,KAAQ,UAAU,KAAK,QAAW,SAAS,QAAQ;AAAA,EACvD;AACF;AASO,SAAS,cACd,UACA,UACA,cACS;AACT,SAAO,IAAI;AAAA,IACT,iBAAiB,eAAe,UAAU,YAAY,GAAG,gBAAgB;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
@@ -6,8 +6,9 @@ import {
6
6
  } from "./cookies.js";
7
7
  import { forwardedForHeader } from "./client-ip.js";
8
8
  import { publicConfig } from "../config/public.js";
9
- import { serverConfig } from "../config/server.js";
9
+ import { storefrontSecretKey } from "./sdk.js";
10
10
  import { THEME_PREVIEW_HOST_HEADER } from "../theme/preview-host.js";
11
+ import { SERVED_STORE_HEADER } from "../request/served-store.js";
11
12
  import { STORE_PREVIEW_TOKEN_HEADER } from "../stores/store-preview-cookie.js";
12
13
  const REFRESH_WINDOW_SECONDS = 120;
13
14
  const REFRESH_FETCH_TIMEOUT_MS = 2500;
@@ -31,12 +32,12 @@ async function refreshIfNearExpiry(req, storeRef, cookiePath) {
31
32
  if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;
32
33
  try {
33
34
  const res = await fetch(
34
- `${publicConfig().apiUrl}/public/stores/${encodeURIComponent(storeRef)}/auth/refresh`,
35
+ `${publicConfig().apiUrl}/storefront/stores/${encodeURIComponent(storeRef)}/auth/refresh`,
35
36
  {
36
37
  method: "POST",
37
38
  headers: {
38
39
  "Content-Type": "application/json",
39
- "x-storefront-api-key": serverConfig().platformApiKey,
40
+ "x-storefront-api-key": storefrontSecretKey(),
40
41
  // The backend throttles per `storeId:clientIp`; without this (the
41
42
  // shopper IP plus the forwarder secret that makes the backend
42
43
  // believe it) every shopper's refresh lands in one store-wide bucket.
@@ -64,11 +65,13 @@ async function refreshIfNearExpiry(req, storeRef, cookiePath) {
64
65
  }
65
66
  return null;
66
67
  }
67
- function downstreamRequestHeaders(req, hostMapped, storeRef, rotated) {
68
+ function downstreamRequestHeaders(req, hostMapped, storeRef, rotated, servedStoreRef = null) {
68
69
  const headers = new Headers(req.headers);
69
70
  headers.set(HOST_MAPPED_HEADER, hostMapped ? "1" : "0");
70
71
  headers.delete(THEME_PREVIEW_HOST_HEADER);
71
72
  headers.delete(STORE_PREVIEW_TOKEN_HEADER);
73
+ headers.delete(SERVED_STORE_HEADER);
74
+ if (servedStoreRef) headers.set(SERVED_STORE_HEADER, servedStoreRef);
72
75
  if (rotated && storeRef) {
73
76
  const jar = new Map(req.cookies.getAll().map((c) => [c.name, c.value]));
74
77
  const path = authCookiePath(storeRef, hostMapped);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/session-refresh.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\nimport {\n accessCookieName,\n authCookiePath,\n refreshCookieName,\n HOST_MAPPED_HEADER,\n} from \"./cookies\";\nimport { forwardedForHeader } from \"./client-ip\";\nimport { publicConfig } from \"../config/public\";\nimport { serverConfig } from \"../config/server\";\nimport { THEME_PREVIEW_HOST_HEADER } from \"../theme/preview-host\";\nimport { STORE_PREVIEW_TOKEN_HEADER } from \"../stores/store-preview-cookie\";\n\n/**\n * Session upkeep shared by both middleware modes (createStorefrontMiddleware):\n * refresh a near-expiry access token, and pass the downstream render the\n * rotated tokens plus the host-mapped stamp.\n */\n\nconst REFRESH_WINDOW_SECONDS = 120;\nconst REFRESH_FETCH_TIMEOUT_MS = 2500;\n\nexport interface RotatedTokens {\n access_token: string;\n refresh_token: string;\n}\n\n/**\n * Reads `exp` without verifying the signature — the API verifies. This only\n * decides whether to refresh early, so a forged token gains nothing: it still\n * fails at the API.\n */\nexport function expiresWithin(token: string, seconds: number): boolean {\n try {\n const payload = JSON.parse(\n Buffer.from(token.split(\".\")[1], \"base64\").toString(\"utf8\")\n );\n if (typeof payload.exp !== \"number\") return false;\n return payload.exp - Math.floor(Date.now() / 1000) < seconds;\n } catch {\n return false;\n }\n}\n\n/**\n * Proactively refresh a near-expiry access token so requests don't hit a 401\n * on it. Returns the rotated pair, or null if there was nothing to do or the\n * attempt failed — a failed refresh is non-fatal and the request proceeds on\n * the old token, letting the 401 paths handle it.\n *\n * This runs for **every** request the matcher admits, not just host-mapped\n * ones: the server-rendered pages read the session straight off the cookie\n * (`lib/auth/session.ts`) and have no other way to renew it. Part A's backend\n * proxy refreshes on a 401, but that only covers browser-initiated calls.\n * `cookiePath` is the session cookies' path (authCookiePath).\n */\nexport async function refreshIfNearExpiry(\n req: NextRequest,\n storeRef: string,\n cookiePath: string\n): Promise<RotatedTokens | null> {\n const access = req.cookies.get(accessCookieName(storeRef, cookiePath))?.value;\n const refresh = req.cookies.get(\n refreshCookieName(storeRef, cookiePath)\n )?.value;\n\n if (!access || !refresh) return null;\n if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;\n\n try {\n const res = await fetch(\n `${publicConfig().apiUrl}/public/stores/${encodeURIComponent(storeRef)}/auth/refresh`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": serverConfig().platformApiKey,\n // The backend throttles per `storeId:clientIp`; without this (the\n // shopper IP plus the forwarder secret that makes the backend\n // believe it) every shopper's refresh lands in one store-wide bucket.\n ...forwardedForHeader(req.headers),\n },\n body: JSON.stringify({ refresh_token: refresh }),\n // This is a latency budget added to a page load the user did not\n // ask for, not an API call worth waiting out — bound it so a slow\n // (not down) API can't turn a fast page load into a stall. An\n // abort rejects `fetch`, which the surrounding catch below\n // treats the same as any other network failure: non-fatal,\n // the request proceeds on the old token.\n signal: AbortSignal.timeout(REFRESH_FETCH_TIMEOUT_MS),\n }\n );\n\n if (!res.ok) return null;\n\n const data = await res.json();\n if (data?.access_token && data?.refresh_token) {\n return {\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n };\n }\n } catch {\n // Non-fatal: proceed on the old token, the normal 401 path handles it.\n }\n\n return null;\n}\n\n/**\n * The request headers every downstream render and route handler sees.\n *\n * Two jobs:\n *\n * 1. `HOST_MAPPED_HEADER` records whether the **Host** named the store. This\n * middleware is the only place that resolves Host → store, and the auth\n * route handler needs the answer to choose the cookie `path` and to know\n * where the store's own root is — it cannot tell the deployments apart from\n * the request path, which is `/store/<ref>/api/…` on both. Always set, so a\n * browser-supplied value can never survive.\n * 2. When a token was rotated, the new pair replaces the old one in the cookie\n * header, so the render *this* request triggers already sees the new\n * session. Without it a shopper returning after their access token expired\n * would be bounced to `/login` on the very request that renewed it.\n */\nexport function downstreamRequestHeaders(\n req: NextRequest,\n hostMapped: boolean,\n storeRef: string | null,\n rotated: RotatedTokens | null\n): Headers {\n const headers = new Headers(req.headers);\n headers.set(HOST_MAPPED_HEADER, hostMapped ? \"1\" : \"0\");\n // Only the middleware names a preview host's theme (theme/preview-host).\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n // Only the middleware hands on a preview host's store preview token; a\n // copy the client sent never survives (stores/store-preview-cookie).\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n\n if (rotated && storeRef) {\n const jar = new Map(req.cookies.getAll().map(c => [c.name, c.value]));\n const path = authCookiePath(storeRef, hostMapped);\n jar.set(accessCookieName(storeRef, path), rotated.access_token);\n jar.set(refreshCookieName(storeRef, path), rotated.refresh_token);\n headers.set(\n \"cookie\",\n [...jar].map(([name, value]) => `${name}=${value}`).join(\"; \")\n );\n }\n\n return headers;\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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EpB,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,QAAI,MAAM,gBAAgB,MAAM,eAAe;AAC7C,aAAO;AAAA,QACL,cAAc,KAAK;AAAA,QACnB,eAAe,KAAK;AAAA,MACtB;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO;AACT;AAkBO,SAAS,yBACd,KACA,YACA,UACA,SACS;AACT,QAAM,UAAU,IAAI,QAAQ,IAAI,OAAO;AACvC,UAAQ,IAAI,oBAAoB,aAAa,MAAM,GAAG;AAEtD,UAAQ,OAAO,yBAAyB;AAGxC,UAAQ,OAAO,0BAA0B;AAEzC,MAAI,WAAW,UAAU;AACvB,UAAM,MAAM,IAAI,IAAI,IAAI,QAAQ,OAAO,EAAE,IAAI,OAAK,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AACpE,UAAM,OAAO,eAAe,UAAU,UAAU;AAChD,QAAI,IAAI,iBAAiB,UAAU,IAAI,GAAG,QAAQ,YAAY;AAC9D,QAAI,IAAI,kBAAkB,UAAU,IAAI,GAAG,QAAQ,aAAa;AAChE,YAAQ;AAAA,MACN;AAAA,MACA,CAAC,GAAG,GAAG,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,KAAK,EAAE,EAAE,KAAK,IAAI;AAAA,IAC/D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/session-refresh.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\nimport {\n accessCookieName,\n authCookiePath,\n refreshCookieName,\n HOST_MAPPED_HEADER,\n} from \"./cookies\";\nimport { forwardedForHeader } from \"./client-ip\";\nimport { publicConfig } from \"../config/public\";\nimport { storefrontSecretKey } from \"./sdk\";\nimport { THEME_PREVIEW_HOST_HEADER } from \"../theme/preview-host\";\nimport { SERVED_STORE_HEADER } from \"../request/served-store\";\nimport { STORE_PREVIEW_TOKEN_HEADER } from \"../stores/store-preview-cookie\";\n\n/**\n * Session upkeep shared by both middleware modes (createStorefrontMiddleware):\n * refresh a near-expiry access token, and pass the downstream render the\n * rotated tokens plus the host-mapped stamp.\n */\n\nconst REFRESH_WINDOW_SECONDS = 120;\nconst REFRESH_FETCH_TIMEOUT_MS = 2500;\n\nexport interface RotatedTokens {\n access_token: string;\n refresh_token: string;\n}\n\n/**\n * Reads `exp` without verifying the signature — the API verifies. This only\n * decides whether to refresh early, so a forged token gains nothing: it still\n * fails at the API.\n */\nexport function expiresWithin(token: string, seconds: number): boolean {\n try {\n const payload = JSON.parse(\n Buffer.from(token.split(\".\")[1], \"base64\").toString(\"utf8\")\n );\n if (typeof payload.exp !== \"number\") return false;\n return payload.exp - Math.floor(Date.now() / 1000) < seconds;\n } catch {\n return false;\n }\n}\n\n/**\n * Proactively refresh a near-expiry access token so requests don't hit a 401\n * on it. Returns the rotated pair, or null if there was nothing to do or the\n * attempt failed — a failed refresh is non-fatal and the request proceeds on\n * the old token, letting the 401 paths handle it.\n *\n * This runs for **every** request the matcher admits, not just host-mapped\n * ones: the server-rendered pages read the session straight off the cookie\n * (`lib/auth/session.ts`) and have no other way to renew it. Part A's backend\n * proxy refreshes on a 401, but that only covers browser-initiated calls.\n * `cookiePath` is the session cookies' path (authCookiePath).\n */\nexport async function refreshIfNearExpiry(\n req: NextRequest,\n storeRef: string,\n cookiePath: string\n): Promise<RotatedTokens | null> {\n const access = req.cookies.get(accessCookieName(storeRef, cookiePath))?.value;\n const refresh = req.cookies.get(\n refreshCookieName(storeRef, cookiePath)\n )?.value;\n\n if (!access || !refresh) return null;\n if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;\n\n try {\n const res = await fetch(\n `${publicConfig().apiUrl}/storefront/stores/${encodeURIComponent(storeRef)}/auth/refresh`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontSecretKey(),\n // The backend throttles per `storeId:clientIp`; without this (the\n // shopper IP plus the forwarder secret that makes the backend\n // believe it) every shopper's refresh lands in one store-wide bucket.\n ...forwardedForHeader(req.headers),\n },\n body: JSON.stringify({ refresh_token: refresh }),\n // This is a latency budget added to a page load the user did not\n // ask for, not an API call worth waiting out — bound it so a slow\n // (not down) API can't turn a fast page load into a stall. An\n // abort rejects `fetch`, which the surrounding catch below\n // treats the same as any other network failure: non-fatal,\n // the request proceeds on the old token.\n signal: AbortSignal.timeout(REFRESH_FETCH_TIMEOUT_MS),\n }\n );\n\n if (!res.ok) return null;\n\n const data = await res.json();\n if (data?.access_token && data?.refresh_token) {\n return {\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n };\n }\n } catch {\n // Non-fatal: proceed on the old token, the normal 401 path handles it.\n }\n\n return null;\n}\n\n/**\n * The request headers every downstream render and route handler sees.\n *\n * Two jobs:\n *\n * 1. `HOST_MAPPED_HEADER` records whether the **Host** named the store. This\n * middleware is the only place that resolves Host → store, and the auth\n * route handler needs the answer to choose the cookie `path` and to know\n * where the store's own root is — it cannot tell the deployments apart from\n * the request path, which is `/store/<ref>/api/…` on both. Always set, so a\n * browser-supplied value can never survive.\n * 2. `SERVED_STORE_HEADER` names the store this request serves (null: none).\n * 3. When a token was rotated, the new pair replaces the old one in the cookie\n * header, so the render *this* request triggers already sees the new\n * session. Without it a shopper returning after their access token expired\n * would be bounced to `/login` on the very request that renewed it.\n */\nexport function downstreamRequestHeaders(\n req: NextRequest,\n hostMapped: boolean,\n storeRef: string | null,\n rotated: RotatedTokens | null,\n servedStoreRef: string | null = null\n): Headers {\n const headers = new Headers(req.headers);\n headers.set(HOST_MAPPED_HEADER, hostMapped ? \"1\" : \"0\");\n // Only the middleware names a preview host's theme (theme/preview-host).\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n // Only the middleware hands on a preview host's store preview token; a\n // copy the client sent never survives (stores/store-preview-cookie).\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n // Only the middleware names the store this request serves; a client copy\n // never survives (request/served-store).\n headers.delete(SERVED_STORE_HEADER);\n if (servedStoreRef) headers.set(SERVED_STORE_HEADER, servedStoreRef);\n\n if (rotated && storeRef) {\n const jar = new Map(req.cookies.getAll().map(c => [c.name, c.value]));\n const path = authCookiePath(storeRef, hostMapped);\n jar.set(accessCookieName(storeRef, path), rotated.access_token);\n jar.set(refreshCookieName(storeRef, path), rotated.refresh_token);\n headers.set(\n \"cookie\",\n [...jar].map(([name, value]) => `${name}=${value}`).join(\"; \")\n );\n }\n\n return headers;\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,iCAAiC;AAC1C,SAAS,2BAA2B;AACpC,SAAS,kCAAkC;AAQ3C,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AAY1B,SAAS,cAAc,OAAe,SAA0B;AACrE,MAAI;AACF,UAAM,UAAU,KAAK;AAAA,MACnB,OAAO,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,QAAQ,EAAE,SAAS,MAAM;AAAA,IAC5D;AACA,QAAI,OAAO,QAAQ,QAAQ,SAAU,QAAO;AAC5C,WAAO,QAAQ,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAcA,eAAsB,oBACpB,KACA,UACA,YAC+B;AAC/B,QAAM,SAAS,IAAI,QAAQ,IAAI,iBAAiB,UAAU,UAAU,CAAC,GAAG;AACxE,QAAM,UAAU,IAAI,QAAQ;AAAA,IAC1B,kBAAkB,UAAU,UAAU;AAAA,EACxC,GAAG;AAEH,MAAI,CAAC,UAAU,CAAC,QAAS,QAAO;AAChC,MAAI,CAAC,cAAc,QAAQ,sBAAsB,EAAG,QAAO;AAE3D,MAAI;AACF,UAAM,MAAM,MAAM;AAAA,MAChB,GAAG,aAAa,EAAE,MAAM,sBAAsB,mBAAmB,QAAQ,C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AAI,IAAI,KAAK,EAAE,EAAE,KAAK,IAAI;AAAA,IAC/D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cart/api.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\n\nexport type {\n CartApiItem,\n CartApiResponse,\n AddToCartRequest,\n UpdateCartItemRequest,\n} from \"@ecomweb/sdk\";\n\nexport interface MergeCartsRequest {\n // No body needed, user_id comes from header\n}\n\n/**\n * Plain module, not a component, so it cannot read React context or an\n * httpOnly cookie. `storeRef` and `isAuth` are therefore explicit parameters\n * supplied by `CartProvider`. When `isAuth` is true the SDK takes the\n * JWT-guarded `/stores/:ref/cart` branch, which reaches the backend through the\n * same-origin proxy (`lib/api/proxy.ts`) — that is what attaches the bearer\n * token server-side.\n */\nclass CartApiService {\n private getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n\n let sessionId = localStorage.getItem(\"cart_session_id\");\n if (!sessionId) {\n sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n localStorage.setItem(\"cart_session_id\", sessionId);\n }\n return sessionId;\n }\n\n async getCart(storeRef: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.getCart(\n storeRef,\n this.getSessionId(),\n isAuth\n );\n }\n\n async addToCart(\n storeRef: string,\n data: Parameters<ReturnType<typeof createStoreSdk>[\"cart\"][\"addItem\"]>[1],\n isAuth: boolean\n ) {\n return createStoreSdk(storeRef).cart.addItem(\n storeRef,\n data,\n this.getSessionId(),\n isAuth\n );\n }\n\n async updateCartItem(\n storeRef: string,\n itemId: string,\n data: Parameters<\n ReturnType<typeof createStoreSdk>[\"cart\"][\"updateItem\"]\n >[2],\n isAuth: boolean\n ) {\n return createStoreSdk(storeRef).cart.updateItem(\n storeRef,\n itemId,\n data,\n this.getSessionId(),\n isAuth\n );\n }\n\n async removeFromCart(storeRef: string, itemId: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.removeItem(\n storeRef,\n itemId,\n this.getSessionId(),\n isAuth\n );\n }\n\n async clearCart(storeRef: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.clear(\n storeRef,\n this.getSessionId(),\n isAuth\n );\n }\n\n /** Always authenticated: merging a guest cart needs an identity to merge into. */\n async mergeCarts(storeRef: string) {\n return createStoreSdk(storeRef).cart.merge(storeRef, this.getSessionId());\n }\n}\n\nexport const cartApiService = new CartApiService();\n"],"mappings":"AAAA,SAAS,sBAAsB;AAqB/B,MAAM,eAAe;AAAA,EACX,eAAuB;AAC7B,QAAI,OAAO,WAAW,YAAa,QAAO;AAE1C,QAAI,YAAY,aAAa,QAAQ,iBAAiB;AACtD,QAAI,CAAC,WAAW;AACd,kBAAY,WAAW,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,GAAG,CAAC,CAAC;AAC5E,mBAAa,QAAQ,mBAAmB,SAAS;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,QAAQ,UAAkB,QAAiB;AAC/C,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,UACJ,UACA,MACA,QACA;AACA,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,eACJ,UACA,QACA,MAGA,QACA;AACA,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,eAAe,UAAkB,QAAgB,QAAiB;AACtE,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,UAAU,UAAkB,QAAiB;AACjD,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAAW,UAAkB;AACjC,WAAO,eAAe,QAAQ,EAAE,KAAK,MAAM,UAAU,KAAK,aAAa,CAAC;AAAA,EAC1E;AACF;AAEO,MAAM,iBAAiB,IAAI,eAAe;","names":[]}
1
+ {"version":3,"sources":["../../src/cart/api.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\n\nexport type {\n CartApiItem,\n CartApiResponse,\n AddToCartRequest,\n UpdateCartItemRequest,\n} from \"@ecomweb/sdk\";\n\nexport interface MergeCartsRequest {\n // No body needed, user_id comes from header\n}\n\n/**\n * Plain module, not a component, so it cannot read React context or an\n * httpOnly cookie. `storeRef` and `isAuth` are therefore explicit parameters\n * supplied by `CartProvider`. When `isAuth` is true the SDK takes the\n * JWT-guarded `/storefront/stores/:ref/customers/cart` branch, which reaches the backend through the\n * same-origin proxy (`lib/api/proxy.ts`) — that is what attaches the bearer\n * token server-side.\n */\nclass CartApiService {\n private getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n\n let sessionId = localStorage.getItem(\"cart_session_id\");\n if (!sessionId) {\n sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n localStorage.setItem(\"cart_session_id\", sessionId);\n }\n return sessionId;\n }\n\n async getCart(storeRef: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.getCart(\n storeRef,\n this.getSessionId(),\n isAuth\n );\n }\n\n async addToCart(\n storeRef: string,\n data: Parameters<ReturnType<typeof createStoreSdk>[\"cart\"][\"addItem\"]>[1],\n isAuth: boolean\n ) {\n return createStoreSdk(storeRef).cart.addItem(\n storeRef,\n data,\n this.getSessionId(),\n isAuth\n );\n }\n\n async updateCartItem(\n storeRef: string,\n itemId: string,\n data: Parameters<\n ReturnType<typeof createStoreSdk>[\"cart\"][\"updateItem\"]\n >[2],\n isAuth: boolean\n ) {\n return createStoreSdk(storeRef).cart.updateItem(\n storeRef,\n itemId,\n data,\n this.getSessionId(),\n isAuth\n );\n }\n\n async removeFromCart(storeRef: string, itemId: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.removeItem(\n storeRef,\n itemId,\n this.getSessionId(),\n isAuth\n );\n }\n\n async clearCart(storeRef: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.clear(\n storeRef,\n this.getSessionId(),\n isAuth\n );\n }\n\n /** Always authenticated: merging a guest cart needs an identity to merge into. */\n async mergeCarts(storeRef: string) {\n return createStoreSdk(storeRef).cart.merge(storeRef, this.getSessionId());\n }\n}\n\nexport const cartApiService = new CartApiService();\n"],"mappings":"AAAA,SAAS,sBAAsB;AAqB/B,MAAM,eAAe;AAAA,EACX,eAAuB;AAC7B,QAAI,OAAO,WAAW,YAAa,QAAO;AAE1C,QAAI,YAAY,aAAa,QAAQ,iBAAiB;AACtD,QAAI,CAAC,WAAW;AACd,kBAAY,WAAW,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,GAAG,CAAC,CAAC;AAC5E,mBAAa,QAAQ,mBAAmB,SAAS;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,QAAQ,UAAkB,QAAiB;AAC/C,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,UACJ,UACA,MACA,QACA;AACA,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,eACJ,UACA,QACA,MAGA,QACA;AACA,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,eAAe,UAAkB,QAAgB,QAAiB;AACtE,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,UAAU,UAAkB,QAAiB;AACjD,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAAW,UAAkB;AACjC,WAAO,eAAe,QAAQ,EAAE,KAAK,MAAM,UAAU,KAAK,aAAa,CAAC;AAAA,EAC1E;AACF;AAEO,MAAM,iBAAiB,IAAI,eAAe;","names":[]}
@@ -1,13 +1,9 @@
1
- import { publicApiClient } from "../api/client.js";
2
- import { unwrap } from "../api/response.js";
1
+ import { createStoreSdk } from "../sdk.js";
3
2
  async function getPaymentState(storeRef, order_code) {
4
- const res = await publicApiClient.get(
5
- // `order_code` carries a `#` prefix by default in this system — left
6
- // unencoded, it truncates the URL (everything from `#` on is treated
7
- // as a fragment) and the request silently hits a different route.
8
- `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`
3
+ return createStoreSdk(storeRef).payments.getPaymentState(
4
+ storeRef,
5
+ order_code
9
6
  );
10
- return unwrap(res);
11
7
  }
12
8
  export {
13
9
  getPaymentState
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/get-payment-state.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport type { PaymentStateResult } from \"./payment-state-poll\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.getPaymentState`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * — see `lib/checkout/initiate-gateway-payment.ts` for the full story\n * (same pinned commit, same missing module). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.getPaymentState()`'s request/response\n * shape exactly (same path, same result shape) so that once the SDK bump\n * lands, the fix is: delete this file, delete this import in\n * `payment-state-poll`'s caller, and call\n * `sdk.payments.getPaymentState(...)` instead — the call site already reads\n * as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.getPaymentState`.\n */\nexport async function getPaymentState(\n storeRef: string,\n order_code: string\n): Promise<PaymentStateResult> {\n const res = await publicApiClient.get<PaymentStateResult>(\n // `order_code` carries a `#` prefix by default in this system — left\n // unencoded, it truncates the URL (everything from `#` on is treated\n // as a fragment) and the request silently hits a different route.\n `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AAyBvB,eAAsB,gBACpB,UACA,YAC6B;AAC7B,QAAM,MAAM,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA,IAIhC,kBAAkB,mBAAmB,QAAQ,CAAC,WAAW,mBAAmB,UAAU,CAAC;AAAA,EACzF;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/get-payment-state.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\nimport type { PaymentStateResult } from \"./payment-state-poll\";\n\n/**\n * Reads where a payment stands for an order, from the browser, through the\n * store's backend proxy (`createStoreSdk`), which adds the secret key. Browser\n * only: the proxied SDK uses a relative URL. On a server use `getServerSdk()`.\n *\n * @param storeRef - the store's ref\n * @param order_code - the order's code\n * @returns the payment state of the order\n */\nexport async function getPaymentState(\n storeRef: string,\n order_code: string\n): Promise<PaymentStateResult> {\n return createStoreSdk(storeRef).payments.getPaymentState(\n storeRef,\n order_code\n );\n}\n"],"mappings":"AAAA,SAAS,sBAAsB;AAY/B,eAAsB,gBACpB,UACA,YAC6B;AAC7B,SAAO,eAAe,QAAQ,EAAE,SAAS;AAAA,IACvC;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -1,11 +1,9 @@
1
- import { publicApiClient } from "../api/client.js";
2
- import { unwrap } from "../api/response.js";
1
+ import { createStoreSdk } from "../sdk.js";
3
2
  async function initiateGatewayPayment(storeRef, input) {
4
- const res = await publicApiClient.post(
5
- `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,
6
- { order_code: input.order_code, provider_code: input.provider_code }
7
- );
8
- return unwrap(res);
3
+ return createStoreSdk(storeRef).payments.initiate(storeRef, {
4
+ order_code: input.order_code,
5
+ provider_code: input.provider_code
6
+ });
9
7
  }
10
8
  export {
11
9
  initiateGatewayPayment
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/initiate-gateway-payment.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.initiate`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * (confirmed: nothing under `node_modules/@ecomweb/sdk/src` references\n * `payments`, `provider_code`, or `redirect_url`). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.initiate()`'s request/response shape\n * exactly (same path, same body keys, same result shape) so that once the\n * SDK bump lands, the fix is: delete this file, delete this import in\n * `checkout-page-client.tsx`, and call `sdk.payments.initiate(...)` instead\n * — the call site already reads as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.initiate`.\n */\nexport interface InitiatePaymentResult {\n payment_id: number;\n redirect_url: string;\n}\n\nexport async function initiateGatewayPayment(\n storeRef: string,\n input: { order_code: string; provider_code: string }\n): Promise<InitiatePaymentResult> {\n const res = await publicApiClient.post<InitiatePaymentResult>(\n `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,\n { order_code: input.order_code, provider_code: input.provider_code }\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AA4BvB,eAAsB,uBACpB,UACA,OACgC;AAChC,QAAM,MAAM,MAAM,gBAAgB;AAAA,IAChC,kBAAkB,mBAAmB,QAAQ,CAAC;AAAA,IAC9C,EAAE,YAAY,MAAM,YAAY,eAAe,MAAM,cAAc;AAAA,EACrE;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/initiate-gateway-payment.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\n\nexport interface InitiatePaymentResult {\n payment_id: number;\n redirect_url: string;\n}\n\nexport async function initiateGatewayPayment(\n storeRef: string,\n input: { order_code: string; provider_code: string }\n): Promise<InitiatePaymentResult> {\n return createStoreSdk(storeRef).payments.initiate(storeRef, {\n order_code: input.order_code,\n provider_code: input.provider_code,\n });\n}\n"],"mappings":"AAAA,SAAS,sBAAsB;AAO/B,eAAsB,uBACpB,UACA,OACgC;AAChC,SAAO,eAAe,QAAQ,EAAE,SAAS,SAAS,UAAU;AAAA,IAC1D,YAAY,MAAM;AAAA,IAClB,eAAe,MAAM;AAAA,EACvB,CAAC;AACH;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/order-handoff.ts"],"sourcesContent":["/**\n * Carries what the success screen needs from the checkout page that placed\n * the order.\n *\n * Why this exists: gateway methods reach `/order-success` through the\n * provider and the API's return endpoint, so that page knows only the order\n * code. Offline methods (cod, bank_transfer) now navigate there directly, and\n * the screen has to know which method was used and how much to ask for.\n *\n * Why not read it from the API: the obvious candidate,\n * `GET /public/stores/:ref/orders/:code/payment-state`, deliberately\n * allow-lists its response down to two status fields, because it sits behind\n * only the public storefront key and order codes are sequential. Putting an\n * amount there would let anyone enumerate a store's order values. This data\n * never leaves the shopper's own browser instead.\n *\n * Replaces the older \"recent-order\" key, which nothing had written for a long\n * time while the success page still read it, so `orderInfo` there was always\n * null.\n */\nconst HANDOFF_KEY = \"ecw:order-handoff\";\n\n/** Older handoffs are ignored rather than shown against a newer order. */\nconst MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\n/**\n * What the thank-you page shows of the order (contact, address, methods,\n * lines, money), built by the storefront when it places the order. Like the\n * rest of the handoff it stays in the shopper's own browser.\n */\nexport interface OrderHandoffSummary {\n customer_name: string;\n phone: string;\n email: string | null;\n /** The delivery address as one display line. */\n address: string;\n shipping_method: string | null;\n shipping_fee: number | null;\n payment_label: string;\n items: {\n name: string;\n variant: string | null;\n quantity: number;\n /** Unit price. */\n price: number;\n image: string | null;\n }[];\n subtotal: number;\n discount: number;\n}\n\nexport interface OrderHandoff {\n order_code: string;\n /** `cod`, `bank_transfer`, or a gateway code. */\n payment_method: string;\n /** Non-null only for gateway-backed methods. */\n provider_code: string | null;\n total: number;\n currency_code: string;\n /** Absent for gateway returns and older handoffs. */\n summary?: OrderHandoffSummary | null;\n written_at: number;\n}\n\nfunction isSummary(value: unknown): value is OrderHandoffSummary {\n if (!value || typeof value !== \"object\") return false;\n const s = value as Record<string, unknown>;\n return (\n typeof s.customer_name === \"string\" &&\n typeof s.address === \"string\" &&\n typeof s.payment_label === \"string\" &&\n typeof s.subtotal === \"number\" &&\n Array.isArray(s.items) &&\n s.items.every(\n item =>\n !!item &&\n typeof item === \"object\" &&\n typeof (item as Record<string, unknown>).name === \"string\" &&\n typeof (item as Record<string, unknown>).quantity === \"number\" &&\n typeof (item as Record<string, unknown>).price === \"number\"\n )\n );\n}\n\nexport function writeOrderHandoff(\n handoff: Omit<OrderHandoff, \"written_at\">\n): void {\n try {\n window.localStorage.setItem(\n HANDOFF_KEY,\n JSON.stringify({ ...handoff, written_at: Date.now() })\n );\n } catch {\n // Private mode, quota, or storage disabled. The success screen falls back\n // to its order-code-only rendering, so losing this is a degradation and\n // never a failure.\n }\n}\n\n/**\n * Returns the handoff only if it is present, well-formed, fresh, and for the\n * order being shown. Any mismatch yields null: showing one order's amount on\n * another order's screen would be worse than showing no amount at all.\n */\nexport function readOrderHandoff(\n order_code: string | null\n): OrderHandoff | null {\n if (!order_code) return null;\n let raw: string | null = null;\n try {\n raw = window.localStorage.getItem(HANDOFF_KEY);\n } catch {\n return null;\n }\n if (!raw) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n return matchHandoff(parsed, order_code, Date.now());\n}\n\n/**\n * The validation half of readOrderHandoff, split out so it can be tested\n * without a DOM or a clock. Exported for that reason only.\n */\nexport function matchHandoff(\n parsed: unknown,\n order_code: string,\n now: number\n): OrderHandoff | null {\n if (!parsed || typeof parsed !== \"object\") return null;\n const h = parsed as Record<string, unknown>;\n\n if (typeof h.order_code !== \"string\" || h.order_code !== order_code)\n return null;\n if (typeof h.payment_method !== \"string\" || h.payment_method.length === 0) {\n return null;\n }\n if (typeof h.total !== \"number\" || !Number.isFinite(h.total)) return null;\n if (typeof h.written_at !== \"number\" || now - h.written_at > MAX_AGE_MS) {\n return null;\n }\n\n return {\n order_code: h.order_code,\n payment_method: h.payment_method,\n provider_code:\n typeof h.provider_code === \"string\" && h.provider_code.length > 0\n ? h.provider_code\n : null,\n total: h.total,\n currency_code:\n typeof h.currency_code === \"string\" && h.currency_code.length > 0\n ? h.currency_code\n : \"VND\",\n summary: isSummary(h.summary) ? h.summary : null,\n written_at: h.written_at,\n };\n}\n\nexport function clearOrderHandoff(): void {\n try {\n window.localStorage.removeItem(HANDOFF_KEY);\n } catch {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AAG;AACzE,WAAO;AAAA,EACT;AACA,MAAI,OAAO,EAAE,UAAU,YAAY,CAAC,OAAO,SAAS,EAAE,KAAK,EAAG,QAAO;AACrE,MAAI,OAAO,EAAE,eAAe,YAAY,MAAM,EAAE,aAAa,YAAY;AACvE,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,YAAY,EAAE;AAAA,IACd,gBAAgB,EAAE;AAAA,IAClB,eACE,OAAO,EAAE,kBAAkB,YAAY,EAAE,cAAc,SAAS,IAC5D,EAAE,gBACF;AAAA,IACN,OAAO,EAAE;AAAA,IACT,eACE,OAAO,EAAE,kBAAkB,YAAY,EAAE,cAAc,SAAS,IAC5D,EAAE,gBACF;AAAA,IACN,SAAS,UAAU,EAAE,OAAO,IAAI,EAAE,UAAU;AAAA,IAC5C,YAAY,EAAE;AAAA,EAChB;AACF;AAEO,SAAS,oBAA0B;AACxC,MAAI;AACF,WAAO,aAAa,WAAW,WAAW;AAAA,EAC5C,QAAQ;AAAA,EAER;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/order-handoff.ts"],"sourcesContent":["/**\n * Carries what the success screen needs from the checkout page that placed\n * the order.\n *\n * Why this exists: gateway methods reach `/order-success` through the\n * provider and the API's return endpoint, so that page knows only the order\n * code. Offline methods (cod, bank_transfer) now navigate there directly, and\n * the screen has to know which method was used and how much to ask for.\n *\n * Why not read it from the API: the obvious candidate,\n * `GET /storefront/stores/:ref/orders/:code/payment-state`, deliberately\n * allow-lists its response down to two status fields, because it sits behind\n * only the public storefront key and order codes are sequential. Putting an\n * amount there would let anyone enumerate a store's order values. This data\n * never leaves the shopper's own browser instead.\n *\n * Replaces the older \"recent-order\" key, which nothing had written for a long\n * time while the success page still read it, so `orderInfo` there was always\n * null.\n */\nconst HANDOFF_KEY = \"ecw:order-handoff\";\n\n/** Older handoffs are ignored rather than shown against a newer order. */\nconst MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\n/**\n * What the thank-you page shows of the order (contact, address, methods,\n * lines, money), built by the storefront when it places the order. Like the\n * rest of the handoff it stays in the shopper's own browser.\n */\nexport interface OrderHandoffSummary {\n customer_name: string;\n phone: string;\n email: string | null;\n /** The delivery address as one display line. */\n address: string;\n shipping_method: string | null;\n shipping_fee: number | null;\n payment_label: string;\n items: {\n name: string;\n variant: string | null;\n quantity: number;\n /** Unit price. */\n price: number;\n image: string | null;\n }[];\n subtotal: number;\n discount: number;\n}\n\nexport interface OrderHandoff {\n order_code: string;\n /** `cod`, `bank_transfer`, or a gateway code. */\n payment_method: string;\n /** Non-null only for gateway-backed methods. */\n provider_code: string | null;\n total: number;\n currency_code: string;\n /** Absent for gateway returns and older handoffs. */\n summary?: OrderHandoffSummary | null;\n written_at: number;\n}\n\nfunction isSummary(value: unknown): value is OrderHandoffSummary {\n if (!value || typeof value !== \"object\") return false;\n const s = value as Record<string, unknown>;\n return (\n typeof s.customer_name === \"string\" &&\n typeof s.address === \"string\" &&\n typeof s.payment_label === \"string\" &&\n typeof s.subtotal === \"number\" &&\n Array.isArray(s.items) &&\n s.items.every(\n item =>\n !!item &&\n typeof item === \"object\" &&\n typeof (item as Record<string, unknown>).name === \"string\" &&\n typeof (item as Record<string, unknown>).quantity === \"number\" &&\n typeof (item as Record<string, unknown>).price === \"number\"\n )\n );\n}\n\nexport function writeOrderHandoff(\n handoff: Omit<OrderHandoff, \"written_at\">\n): void {\n try {\n window.localStorage.setItem(\n HANDOFF_KEY,\n JSON.stringify({ ...handoff, written_at: Date.now() })\n );\n } catch {\n // Private mode, quota, or storage disabled. The success screen falls back\n // to its order-code-only rendering, so losing this is a degradation and\n // never a failure.\n }\n}\n\n/**\n * Returns the handoff only if it is present, well-formed, fresh, and for the\n * order being shown. Any mismatch yields null: showing one order's amount on\n * another order's screen would be worse than showing no amount at all.\n */\nexport function readOrderHandoff(\n order_code: string | null\n): OrderHandoff | null {\n if (!order_code) return null;\n let raw: string | null = null;\n try {\n raw = window.localStorage.getItem(HANDOFF_KEY);\n } catch {\n return null;\n }\n if (!raw) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n return matchHandoff(parsed, order_code, Date.now());\n}\n\n/**\n * The validation half of readOrderHandoff, split out so it can be tested\n * without a DOM or a clock. Exported for that reason only.\n */\nexport function matchHandoff(\n parsed: unknown,\n order_code: string,\n now: number\n): OrderHandoff | null {\n if (!parsed || typeof parsed !== \"object\") return null;\n const h = parsed as Record<string, unknown>;\n\n if (typeof h.order_code !== \"string\" || h.order_code !== order_code)\n return null;\n if (typeof h.payment_method !== \"string\" || h.payment_method.length === 0) {\n return null;\n }\n if (typeof h.total !== \"number\" || !Number.isFinite(h.total)) return null;\n if (typeof h.written_at !== \"number\" || now - h.written_at > MAX_AGE_MS) {\n return null;\n }\n\n return {\n order_code: h.order_code,\n payment_method: h.payment_method,\n provider_code:\n typeof h.provider_code === \"string\" && h.provider_code.length > 0\n ? h.provider_code\n : null,\n total: h.total,\n currency_code:\n typeof h.currency_code === \"string\" && h.currency_code.length > 0\n ? h.currency_code\n : \"VND\",\n summary: isSummary(h.summary) ? h.summary : null,\n written_at: h.written_at,\n };\n}\n\nexport function clearOrderHandoff(): void {\n try {\n window.localStorage.removeItem(HANDOFF_KEY);\n } catch {\n // Nothing to do; a stale entry expires on its own.\n }\n}\n"],"mappings":"AAoBA,MAAM,cAAc;AAGpB,MAAM,aAAa,KAAK,KAAK,KAAK;AAyClC,SAAS,UAAU,OAA8C;AAC/D,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,IAAI;AACV,SACE,OAAO,EAAE,kBAAkB,YAC3B,OAAO,EAAE,YAAY,YACrB,OAAO,EAAE,kBAAkB,YAC3B,OAAO,EAAE,aAAa,YACtB,MAAM,QAAQ,EAAE,KAAK,KACrB,EAAE,MAAM;AAAA,IACN,UACE,CAAC,CAAC,QACF,OAAO,SAAS,YAChB,OAAQ,KAAiC,SAAS,YAClD,OAAQ,KAAiC,aAAa,YACtD,OAAQ,KA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,IAAI,EAAE,UAAU;AAAA,IAC5C,YAAY,EAAE;AAAA,EAChB;AACF;AAEO,SAAS,oBAA0B;AACxC,MAAI;AACF,WAAO,aAAa,WAAW,WAAW;AAAA,EAC5C,QAAQ;AAAA,EAER;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/payment-redirect.ts"],"sourcesContent":["/**\n * Decides whether a just-placed checkout should send the shopper to a\n * payment gateway, or leave today's inline \"order placed\" success flow\n * untouched.\n *\n * Deliberately pure: no network call, no `window` access. The page\n * component (`checkout-page-client.tsx`) performs the actual redirect once\n * this function tells it to.\n */\n\n/**\n * The pinned `@ecomweb/sdk` version's `StorePaymentMethod` type does not yet\n * declare `provider_code` (see `lib/checkout/initiate-gateway-payment.ts` for\n * the full story — the SDK PR that adds it is not merged, and this repo's\n * lockfile pins an older commit). The backend already returns the field on\n * `GET /public/stores/:storeRef/payment-methods` today, so this function is\n * typed against only the one field it actually needs rather than the SDK's\n * (currently stale) full type, and the call site casts to this shape.\n */\nexport interface PaymentMethodWithProviderCode {\n provider_code?: string | null;\n}\n\nexport interface PaymentRedirectIntent {\n readonly provider_code: string;\n readonly order_code: string;\n}\n\n/**\n * A payment method with a non-null `provider_code` is gateway-backed\n * (OnePay, MoMo, ...) and the shopper must be sent to the provider to pay.\n * A method without one (`cod`, `bank_transfer`) is settled offline — the\n * existing inline success screen is correct for it and this returns `null`.\n *\n * The returned intent carries `order_code`, never an order id: the\n * `payments/initiate` endpoint is keyed on it deliberately, because the\n * storefront API key authenticates the store rather than the shopper and a\n * raw sequential id would let a caller enumerate a store's orders.\n */\nexport function getPaymentRedirectIntent(\n method: PaymentMethodWithProviderCode | null | undefined,\n order_code: string\n): PaymentRedirectIntent | null {\n const provider_code = method?.provider_code;\n if (!provider_code) {\n return null;\n }\n\n return { provider_code, order_code };\n}\n"],"mappings":"AAuCO,SAAS,yBACd,QACA,YAC8B;AAC9B,QAAM,gBAAgB,QAAQ;AAC9B,MAAI,CAAC,eAAe;AAClB,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,eAAe,WAAW;AACrC;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/payment-redirect.ts"],"sourcesContent":["/**\n * Decides whether a just-placed checkout should send the shopper to a\n * payment gateway, or leave today's inline \"order placed\" success flow\n * untouched.\n *\n * Deliberately pure: no network call, no `window` access. The page\n * component (`checkout-page-client.tsx`) performs the actual redirect once\n * this function tells it to.\n */\n\n/**\n * The pinned `@ecomweb/sdk` version's `StorePaymentMethod` type does not yet\n * declare `provider_code` (see `lib/checkout/initiate-gateway-payment.ts` for\n * the full story — the SDK PR that adds it is not merged, and this repo's\n * lockfile pins an older commit). The backend already returns the field on\n * `GET /storefront/stores/:storeRef/payment-methods` today, so this function is\n * typed against only the one field it actually needs rather than the SDK's\n * (currently stale) full type, and the call site casts to this shape.\n */\nexport interface PaymentMethodWithProviderCode {\n provider_code?: string | null;\n}\n\nexport interface PaymentRedirectIntent {\n readonly provider_code: string;\n readonly order_code: string;\n}\n\n/**\n * A payment method with a non-null `provider_code` is gateway-backed\n * (OnePay, MoMo, ...) and the shopper must be sent to the provider to pay.\n * A method without one (`cod`, `bank_transfer`) is settled offline — the\n * existing inline success screen is correct for it and this returns `null`.\n *\n * The returned intent carries `order_code`, never an order id: the\n * `payments/initiate` endpoint is keyed on it deliberately, because the\n * storefront API key authenticates the store rather than the shopper and a\n * raw sequential id would let a caller enumerate a store's orders.\n */\nexport function getPaymentRedirectIntent(\n method: PaymentMethodWithProviderCode | null | undefined,\n order_code: string\n): PaymentRedirectIntent | null {\n const provider_code = method?.provider_code;\n if (!provider_code) {\n return null;\n }\n\n return { provider_code, order_code };\n}\n"],"mappings":"AAuCO,SAAS,yBACd,QACA,YAC8B;AAC9B,QAAM,gBAAgB,QAAQ;AAC9B,MAAI,CAAC,eAAe;AAClB,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,eAAe,WAAW;AACrC;","names":[]}
@@ -1,4 +1,4 @@
1
- const KIT_VERSION = true ? "0.14.1" : "dev";
1
+ const KIT_VERSION = true ? "0.16.0" : "dev";
2
2
  const KIT_CLIENT_TOKEN = `@ecomweb/storefront-kit/${KIT_VERSION}`;
3
3
  export {
4
4
  KIT_CLIENT_TOKEN,
@@ -1,4 +1,5 @@
1
1
  import { resolveMode } from "./mode.js";
2
+ import { assertNoSecretInPublicEnv } from "./secret-guard.js";
2
3
  import {
3
4
  envValue,
4
5
  logLevelOf,
@@ -84,6 +85,7 @@ function parseSingle(env) {
84
85
  );
85
86
  }
86
87
  function parsePublicConfig(env) {
88
+ assertNoSecretInPublicEnv(env);
87
89
  return resolveMode(env) === "multi" ? parseMulti(env) : parseSingle(env);
88
90
  }
89
91
  let cached;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/public.ts"],"sourcesContent":["import { resolveMode } from \"./mode\";\nimport {\n envValue,\n logLevelOf,\n parseOrThrow,\n publicConfigSchema,\n sampleRateOf,\n type EnvSource,\n type PublicConfig,\n} from \"./schema\";\n\nconst MULTI_ENV_NAME_OF: Record<string, string> = {\n apiUrl: \"NEXT_PUBLIC_API_URL\",\n storefrontApiKey: \"NEXT_PUBLIC_PLATFORM_API_KEY\",\n appUrl: \"NEXT_PUBLIC_APP_URL\",\n platformDomainSuffix: \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\",\n primaryMenuRef: \"NEXT_PUBLIC_PRIMARY_MENU_REF\",\n};\n\n/** next.config.mjs derives these NEXT_PUBLIC_ names from ECOMWEB_* / SITE_URL. */\nconst SINGLE_ENV_NAME_OF: Record<string, string> = {\n storeRef: \"ECOMWEB_STORE_REF\",\n storefrontApiKey: \"ECOMWEB_PUBLISHABLE_KEY\",\n apiUrl: \"ECOMWEB_API_URL\",\n appUrl: \"SITE_URL\",\n};\n\n// Production serves the API under /api/v1 (Kong strips the prefix) and stored\n// assets at the origin's /storage/v1.\nconst DEFAULT_SINGLE_API_URL = \"https://apibase.ecomweb.app/api/v1\";\n\n/** Stored assets live at the API host's /storage/v1, whatever path the API has. */\nfunction originOf(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return url; // the schema reports the invalid API URL\n }\n}\n\nfunction parseMulti(env: EnvSource): PublicConfig {\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"multi\",\n storeRef: null,\n apiUrl: envValue(env, \"NEXT_PUBLIC_API_URL\")?.replace(/\\/$/, \"\"),\n assetBaseUrl: (envValue(env, \"NEXT_PUBLIC_ASSET_BASE_URL\") ?? \"\").replace(\n /\\/$/,\n \"\"\n ),\n appUrl: envValue(env, \"NEXT_PUBLIC_APP_URL\") ?? \"https://ecomweb.app\",\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_PLATFORM_API_KEY\"),\n platformDomainSuffix:\n envValue(env, \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\") ?? \"ecomsite.app\",\n appBaseUrlFlag: envValue(env, \"NEXT_PUBLIC_APP_BASE_URL\"),\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef:\n envValue(env, \"NEXT_PUBLIC_PRIMARY_MENU_REF\") ?? \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n MULTI_ENV_NAME_OF\n );\n}\n\nfunction parseSingle(env: EnvSource): PublicConfig {\n const apiUrl = (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_API_URL\") ?? DEFAULT_SINGLE_API_URL\n ).replace(/\\/$/, \"\");\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"single\",\n storeRef: envValue(env, \"NEXT_PUBLIC_ECOMWEB_STORE_REF\"),\n apiUrl,\n assetBaseUrl: (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_ASSET_URL\") ?? originOf(apiUrl)\n ).replace(/\\/$/, \"\"),\n appUrl: envValue(env, \"NEXT_PUBLIC_SITE_URL\")?.replace(/\\/$/, \"\"),\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY\"),\n platformDomainSuffix: null,\n appBaseUrlFlag: undefined,\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef: \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n SINGLE_ENV_NAME_OF\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parsePublicConfig(env: EnvSource): PublicConfig {\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: PublicConfig | undefined;\n\n/** Specs that stub env per test call this in beforeEach. */\nexport function resetPublicConfigForTests(): void {\n cached = undefined;\n}\n\n/**\n * Every NEXT_PUBLIC_ var is spelled out literally: Next inlines only literal\n * `process.env.NEXT_PUBLIC_X` reads into client bundles.\n */\nexport function publicConfig(): PublicConfig {\n return (cached ??= parsePublicConfig({\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n ECOMWEB_MODE:\n typeof window === \"undefined\" ? process.env.ECOMWEB_MODE : undefined,\n // multi\n NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,\n NEXT_PUBLIC_ASSET_BASE_URL: process.env.NEXT_PUBLIC_ASSET_BASE_URL,\n NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,\n NEXT_PUBLIC_PLATFORM_API_KEY: process.env.NEXT_PUBLIC_PLATFORM_API_KEY,\n NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX:\n process.env.NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX,\n NEXT_PUBLIC_APP_BASE_URL: process.env.NEXT_PUBLIC_APP_BASE_URL,\n NEXT_PUBLIC_PRIMARY_MENU_REF: process.env.NEXT_PUBLIC_PRIMARY_MENU_REF,\n // single\n NEXT_PUBLIC_ECOMWEB_STORE_REF: process.env.NEXT_PUBLIC_ECOMWEB_STORE_REF,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n NEXT_PUBLIC_ECOMWEB_API_URL: process.env.NEXT_PUBLIC_ECOMWEB_API_URL,\n NEXT_PUBLIC_ECOMWEB_ASSET_URL: process.env.NEXT_PUBLIC_ECOMWEB_ASSET_URL,\n NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,\n // both\n NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS:\n process.env.NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS,\n NEXT_PUBLIC_LOG_LEVEL: process.env.NEXT_PUBLIC_LOG_LEVEL,\n NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE:\n process.env.NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE,\n }));\n}\n"],"mappings":"AAAA,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,MAAM,oBAA4C;AAAA,EAChD,QAAQ;AAAA,EACR,kBAAkB;AAAA,EAClB,QAAQ;AAAA,EACR,sBAAsB;AAAA,EACtB,gBAAgB;AAClB;AAGA,MAAM,qBAA6C;AAAA,EACjD,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,QAAQ;AAAA,EACR,QAAQ;AACV;AAIA,MAAM,yBAAyB;AAG/B,SAAS,SAAS,KAAqB;AACrC,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WA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uB,CAAC;AAAA,MAC3D,qBAAqB;AAAA,QACnB,SAAS,KAAK,oCAAoC;AAAA,QAClD;AAAA,MACF;AAAA,IACF;AAAA,IACA;AAAA,EACF;AACF;AAGO,SAAS,kBAAkB,KAA8B;AAC9D,SAAO,YAAY,GAAG,MAAM,UAAU,WAAW,GAAG,IAAI,YAAY,GAAG;AACzE;AAEA,IAAI;AAGG,SAAS,4BAAkC;AAChD,WAAS;AACX;AAMO,SAAS,eAA6B;AAC3C,SAAQ,WAAW,kBAAkB;AAAA,IACnC,0BAA0B,QAAQ,IAAI;AAAA,IACtC,cACE,OAAO,WAAW,cAAc,QAAQ,IAAI,eAAe;AAAA;AAAA,IAE7D,qBAAqB,QAAQ,IAAI;AAAA,IACjC,4BAA4B,QAAQ,IAAI;AAAA,IACxC,qBAAqB,QAAQ,IAAI;AAAA,IACjC,8BAA8B,QAAQ,IAAI;AAAA,IAC1C,oCACE,QAAQ,IAAI;AAAA,IACd,0BAA0B,QAAQ,IAAI;AAAA,IACtC,8BAA8B,QAAQ,IAAI;AAAA;AAAA,IAE1C,+BAA+B,QAAQ,IAAI;AAAA,IAC3C,qCACE,QAAQ,IAAI;AAAA,IACd,6BAA6B,QAAQ,IAAI;AAAA,IACzC,+BAA+B,QAAQ,IAAI;AAAA,IAC3C,sBAAsB,QAAQ,IAAI;AAAA;AAAA,IAElC,0CACE,QAAQ,IAAI;AAAA,IACd,uBAAuB,QAAQ,IAAI;AAAA,IACnC,oCACE,QAAQ,IAAI;AAAA,EAChB,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/config/public.ts"],"sourcesContent":["import { resolveMode } from \"./mode\";\nimport { assertNoSecretInPublicEnv } from \"./secret-guard\";\nimport {\n envValue,\n logLevelOf,\n parseOrThrow,\n publicConfigSchema,\n sampleRateOf,\n type EnvSource,\n type PublicConfig,\n} from \"./schema\";\n\nconst MULTI_ENV_NAME_OF: Record<string, string> = {\n apiUrl: \"NEXT_PUBLIC_API_URL\",\n storefrontApiKey: \"NEXT_PUBLIC_PLATFORM_API_KEY\",\n appUrl: \"NEXT_PUBLIC_APP_URL\",\n platformDomainSuffix: \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\",\n primaryMenuRef: \"NEXT_PUBLIC_PRIMARY_MENU_REF\",\n};\n\n/** next.config.mjs derives these NEXT_PUBLIC_ names from ECOMWEB_* / SITE_URL. */\nconst SINGLE_ENV_NAME_OF: Record<string, string> = {\n storeRef: \"ECOMWEB_STORE_REF\",\n storefrontApiKey: \"ECOMWEB_PUBLISHABLE_KEY\",\n apiUrl: \"ECOMWEB_API_URL\",\n appUrl: \"SITE_URL\",\n};\n\n// Production serves the API under /api/v1 (Kong strips the prefix) and stored\n// assets at the origin's /storage/v1.\nconst DEFAULT_SINGLE_API_URL = \"https://apibase.ecomweb.app/api/v1\";\n\n/** Stored assets live at the API host's /storage/v1, whatever path the API has. */\nfunction originOf(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return url; // the schema reports the invalid API URL\n }\n}\n\nfunction parseMulti(env: EnvSource): PublicConfig {\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"multi\",\n storeRef: null,\n apiUrl: envValue(env, \"NEXT_PUBLIC_API_URL\")?.replace(/\\/$/, \"\"),\n assetBaseUrl: (envValue(env, \"NEXT_PUBLIC_ASSET_BASE_URL\") ?? \"\").replace(\n /\\/$/,\n \"\"\n ),\n appUrl: envValue(env, \"NEXT_PUBLIC_APP_URL\") ?? \"https://ecomweb.app\",\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_PLATFORM_API_KEY\"),\n platformDomainSuffix:\n envValue(env, \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\") ?? \"ecomsite.app\",\n appBaseUrlFlag: envValue(env, \"NEXT_PUBLIC_APP_BASE_URL\"),\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef:\n envValue(env, \"NEXT_PUBLIC_PRIMARY_MENU_REF\") ?? \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n MULTI_ENV_NAME_OF\n );\n}\n\nfunction parseSingle(env: EnvSource): PublicConfig {\n const apiUrl = (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_API_URL\") ?? DEFAULT_SINGLE_API_URL\n ).replace(/\\/$/, \"\");\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"single\",\n storeRef: envValue(env, \"NEXT_PUBLIC_ECOMWEB_STORE_REF\"),\n apiUrl,\n assetBaseUrl: (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_ASSET_URL\") ?? originOf(apiUrl)\n ).replace(/\\/$/, \"\"),\n appUrl: envValue(env, \"NEXT_PUBLIC_SITE_URL\")?.replace(/\\/$/, \"\"),\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY\"),\n platformDomainSuffix: null,\n appBaseUrlFlag: undefined,\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef: \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n SINGLE_ENV_NAME_OF\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parsePublicConfig(env: EnvSource): PublicConfig {\n assertNoSecretInPublicEnv(env);\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: PublicConfig | undefined;\n\n/** Specs that stub env per test call this in beforeEach. */\nexport function resetPublicConfigForTests(): void {\n cached = undefined;\n}\n\n/**\n * Every NEXT_PUBLIC_ var is spelled out literally: Next inlines only literal\n * `process.env.NEXT_PUBLIC_X` reads into client bundles.\n */\nexport function publicConfig(): PublicConfig {\n return (cached ??= parsePublicConfig({\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n ECOMWEB_MODE:\n typeof window === \"undefined\" ? process.env.ECOMWEB_MODE : undefined,\n // multi\n NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,\n NEXT_PUBLIC_ASSET_BASE_URL: process.env.NEXT_PUBLIC_ASSET_BASE_URL,\n NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,\n NEXT_PUBLIC_PLATFORM_API_KEY: process.env.NEXT_PUBLIC_PLATFORM_API_KEY,\n NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX:\n process.env.NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX,\n NEXT_PUBLIC_APP_BASE_URL: process.env.NEXT_PUBLIC_APP_BASE_URL,\n NEXT_PUBLIC_PRIMARY_MENU_REF: process.env.NEXT_PUBLIC_PRIMARY_MENU_REF,\n // single\n NEXT_PUBLIC_ECOMWEB_STORE_REF: process.env.NEXT_PUBLIC_ECOMWEB_STORE_REF,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n NEXT_PUBLIC_ECOMWEB_API_URL: process.env.NEXT_PUBLIC_ECOMWEB_API_URL,\n NEXT_PUBLIC_ECOMWEB_ASSET_URL: process.env.NEXT_PUBLIC_ECOMWEB_ASSET_URL,\n NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,\n // both\n NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS:\n process.env.NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS,\n NEXT_PUBLIC_LOG_LEVEL: process.env.NEXT_PUBLIC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BAA8B,QAAQ,IAAI;AAAA;AAAA,IAE1C,+BAA+B,QAAQ,IAAI;AAAA,IAC3C,qCACE,QAAQ,IAAI;AAAA,IACd,6BAA6B,QAAQ,IAAI;AAAA,IACzC,+BAA+B,QAAQ,IAAI;AAAA,IAC3C,sBAAsB,QAAQ,IAAI;AAAA;AAAA,IAElC,0CACE,QAAQ,IAAI;AAAA,IACd,uBAAuB,QAAQ,IAAI;AAAA,IACnC,oCACE,QAAQ,IAAI;AAAA,EAChB,CAAC;AACH;","names":[]}
@@ -7,6 +7,7 @@ function envValue(env, key) {
7
7
  function logLevelOf(v) {
8
8
  return LOG_LEVELS.includes(v ?? "") ? v : void 0;
9
9
  }
10
+ const SECRET_IN_PUBLIC_MESSAGE = "holds a secret key; secret keys go in server-only variables (ECOMWEB_SECRET_KEY, PLATFORM_SECRET_KEY)";
10
11
  const httpUrl = z.url({ protocol: /^https?$/ });
11
12
  const publicConfigSchema = z.object({
12
13
  mode: z.enum(["multi", "single"]),
@@ -14,7 +15,9 @@ const publicConfigSchema = z.object({
14
15
  apiUrl: httpUrl,
15
16
  assetBaseUrl: z.string(),
16
17
  appUrl: httpUrl,
17
- storefrontApiKey: z.string().min(1),
18
+ storefrontApiKey: z.string().min(1).refine((v) => !v.trim().startsWith("sk_"), {
19
+ message: SECRET_IN_PUBLIC_MESSAGE
20
+ }),
18
21
  platformDomainSuffix: z.string().min(1).nullable(),
19
22
  appBaseUrlFlag: z.string().optional(),
20
23
  imageTransformationsFlag: z.string().optional(),
@@ -23,7 +26,14 @@ const publicConfigSchema = z.object({
23
26
  webVitalsSampleRate: z.number().min(0).max(1)
24
27
  });
25
28
  const serverConfigSchema = z.object({
26
- platformApiKey: z.string().min(1),
29
+ /**
30
+ * Signs every server-side call. Empty only while `next build` runs (builds
31
+ * get no secret); read it through `storefrontSecretKey()`, which throws on
32
+ * an empty one.
33
+ */
34
+ secretKey: z.string({ error: "is required" }).refine((v) => !v.trim().startsWith("pk_"), {
35
+ message: "is a publishable key; this variable takes the secret key (sk_...)"
36
+ }),
27
37
  clientIpForwarderSecret: z.string().min(1).optional(),
28
38
  appBaseUrl: z.string().min(1),
29
39
  appEnv: z.string().min(1),
@@ -48,12 +58,13 @@ class ConfigError extends Error {
48
58
  this.name = "ConfigError";
49
59
  }
50
60
  }
51
- function parseOrThrow(schema, candidate, envNameOf) {
61
+ function parseOrThrow(schema, candidate, envNameOf, notes = {}) {
52
62
  const result = schema.safeParse(candidate);
53
63
  if (result.success) return result.data;
54
64
  const lines = result.error.issues.map((issue) => {
55
65
  const field = String(issue.path[0] ?? "");
56
- return ` - ${envNameOf[field] ?? field}: ${issue.message}`;
66
+ const note = notes[field] ? ` ${notes[field]}` : "";
67
+ return ` - ${envNameOf[field] ?? field}: ${issue.message}${note}`;
57
68
  });
58
69
  throw new ConfigError(
59
70
  `Invalid storefront configuration:
@@ -70,6 +81,7 @@ function sampleRateOf(v, fallback) {
70
81
  }
71
82
  export {
72
83
  ConfigError,
84
+ SECRET_IN_PUBLIC_MESSAGE,
73
85
  countOf,
74
86
  envValue,
75
87
  logLevelOf,