@ecomweb/storefront-kit 0.6.0 → 0.9.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 (64) hide show
  1. package/dist/api/proxy.js +5 -1
  2. package/dist/api/proxy.js.map +1 -1
  3. package/dist/api/server-client.js +7 -4
  4. package/dist/api/server-client.js.map +1 -1
  5. package/dist/auth/cookies.js +51 -33
  6. package/dist/auth/cookies.js.map +1 -1
  7. package/dist/auth/error-copy.js +2 -1
  8. package/dist/auth/error-copy.js.map +1 -1
  9. package/dist/auth/route-handlers.js +2 -2
  10. package/dist/auth/route-handlers.js.map +1 -1
  11. package/dist/auth/session-refresh.js +11 -5
  12. package/dist/auth/session-refresh.js.map +1 -1
  13. package/dist/auth/session.js +8 -4
  14. package/dist/auth/session.js.map +1 -1
  15. package/dist/checkout/get-payment-state.js.map +1 -1
  16. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  17. package/dist/checkout/order-handoff.js +10 -1
  18. package/dist/checkout/order-handoff.js.map +1 -1
  19. package/dist/checkout/use-checkout.js +8 -2
  20. package/dist/checkout/use-checkout.js.map +1 -1
  21. package/dist/config/schema.js +12 -1
  22. package/dist/config/schema.js.map +1 -1
  23. package/dist/config/server.js +9 -2
  24. package/dist/config/server.js.map +1 -1
  25. package/dist/config.d.ts +3 -3
  26. package/dist/index.d.ts +84 -24
  27. package/dist/index.js +12 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/middleware/create-storefront-middleware.js +62 -26
  30. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  31. package/dist/middleware.d.ts +2 -2
  32. package/dist/{mode-YNx2aOtQ.d.ts → mode-Lm9t4qzX.d.ts} +1 -1
  33. package/dist/promotions/use-promotion-validation.js +19 -16
  34. package/dist/promotions/use-promotion-validation.js.map +1 -1
  35. package/dist/{schema-Tc0qRs-Q.d.ts → schema-Dg0ZflMW.d.ts} +1 -0
  36. package/dist/server.d.ts +8 -2
  37. package/dist/server.js +2 -0
  38. package/dist/server.js.map +1 -1
  39. package/dist/shipping/shipping-calculation-reducer.js +7 -4
  40. package/dist/shipping/shipping-calculation-reducer.js.map +1 -1
  41. package/dist/stores/get-store-by-host.js +41 -6
  42. package/dist/stores/get-store-by-host.js.map +1 -1
  43. package/dist/stores/store-subdomain.js +25 -0
  44. package/dist/stores/store-subdomain.js.map +1 -0
  45. package/dist/stores/store-traffic.js +50 -0
  46. package/dist/stores/store-traffic.js.map +1 -0
  47. package/dist/stores/ttl-cache.js +34 -0
  48. package/dist/stores/ttl-cache.js.map +1 -0
  49. package/dist/theme/define.js.map +1 -1
  50. package/dist/theme/index.js.map +1 -1
  51. package/dist/theme/preview-bridge.js +33 -0
  52. package/dist/theme/preview-bridge.js.map +1 -0
  53. package/dist/theme/preview-cookie.js +13 -6
  54. package/dist/theme/preview-cookie.js.map +1 -1
  55. package/dist/theme/preview-host.js +7 -0
  56. package/dist/theme/preview-host.js.map +1 -0
  57. package/dist/theme/read-preview-host.js +10 -0
  58. package/dist/theme/read-preview-host.js.map +1 -0
  59. package/dist/theme/read-preview-token.js +5 -3
  60. package/dist/theme/read-preview-token.js.map +1 -1
  61. package/dist/theme/settings-context.js +14 -1
  62. package/dist/theme/settings-context.js.map +1 -1
  63. package/dist/theme.d.ts +65 -5
  64. package/package.json +2 -2
package/dist/api/proxy.js CHANGED
@@ -96,7 +96,11 @@ async function handleBackendProxy(request, storeRef, segments) {
96
96
  return jsonError(400, "Invalid proxy path", "PROXY_INVALID_PATH");
97
97
  }
98
98
  const body = METHODS_WITH_BODY.has(request.method) ? await request.text() : void 0;
99
- const tokens = readAuthCookies(request.cookies, storeRef);
99
+ const tokens = readAuthCookies(
100
+ request.cookies,
101
+ storeRef,
102
+ authCookiePathFor(request, storeRef)
103
+ );
100
104
  let result;
101
105
  try {
102
106
  result = await callUpstream(
@@ -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\";\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 */\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]);\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\nfunction forwardedHeaders(request: NextRequest, accessToken?: string) {\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 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 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, 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(request.cookies, storeRef);\n\n let result: UpstreamResult;\n\n try {\n result = await callUpstream(\n request,\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 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;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,eAAe,wBAAwB;AAqChE,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,MAAM,oBAAoB,oBAAI,IAAI,CAAC,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAEpE,SAAS,UAAU,QAAgB,SAAiB,MAAc;AAChE,SAAO,aAAa,KAAK,EAAE,MAAM,QAAQ,GAAG,EAAE,OAAO,CAAC;AACxD;AAQA,SAAS,cAAc,UAAoB,QAA4B;AACrE,MAAI,SAAS,WAAW,EAAG,QAAO;AAElC,aAAW,WAAW,UAAU;AAC9B,QACE,YAAY,MACZ,YAAY,OACZ,YAAY,QACZ,QAAQ,SAAS,GAAG,KACpB,QAAQ,S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;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, storefrontApiKey } from \"../auth/sdk\";\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 */\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]);\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\nfunction forwardedHeaders(request: NextRequest, accessToken?: string) {\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 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 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, 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 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 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;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,eAAe,wBAAwB;AAqChE,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,MAAM,oBAAoB,oBAAI,IAAI,CAAC,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAEpE,SAAS,UAAU,QAAgB,SAAiB,MAAc;AAChE,SAAO,aAAa,KAAK,EAAE,M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ACF,YAAQ,MAAM;AAAA,MACZ;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":[]}
@@ -1,4 +1,4 @@
1
- import { readAuthCookies } from "../auth/cookies.js";
1
+ import { authCookiePathFor, readAuthCookies } from "../auth/cookies.js";
2
2
  import { publicConfig } from "../config.js";
3
3
  const DEFAULT_TIMEOUT = 1e4;
4
4
  class ServerApiClient {
@@ -19,9 +19,12 @@ class ServerApiClient {
19
19
  "ServerApiClient: storeRef is required for authenticated requests"
20
20
  );
21
21
  }
22
- const { cookies } = await import("next/headers");
23
- const jar = await cookies();
24
- const tokens = readAuthCookies(jar, storeRef);
22
+ const { cookies, headers } = await import("next/headers");
23
+ const tokens = readAuthCookies(
24
+ await cookies(),
25
+ storeRef,
26
+ authCookiePathFor({ headers: await headers() }, storeRef)
27
+ );
25
28
  if (!tokens) {
26
29
  throw new Error("User not authenticated");
27
30
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/server-client.ts"],"sourcesContent":["import { ApiResponse, AuthenticatedApiClient } from \"../interfaces\";\nimport { readAuthCookies } from \"../auth/cookies\";\nimport { publicConfig } from \"../config\";\n\nconst DEFAULT_TIMEOUT = 10000; // 10 seconds\n\ninterface FetchConfig {\n headers?: Record<string, string>;\n signal?: AbortSignal;\n /**\n * Auth cookies are store-scoped (see lib/auth/cookies.ts), so a\n * `requireAuth` request needs to know which store's cookie to read. There\n * is no store context at the module level (serverApiClient is a shared\n * singleton), so callers thread it through here instead.\n */\n storeRef?: string;\n [key: string]: any;\n}\n\nclass ServerApiClient implements AuthenticatedApiClient {\n private baseUrl: string;\n private timeout: number;\n private requireAuth: boolean;\n\n constructor(\n baseUrl: string = publicConfig().apiUrl,\n options?: { requireAuth?: boolean }\n ) {\n this.requireAuth =\n options?.requireAuth !== undefined ? options.requireAuth : true;\n this.baseUrl = baseUrl.replace(/\\/$/, \"\"); // Remove trailing slash\n this.timeout = DEFAULT_TIMEOUT;\n }\n\n private async getAuthToken(storeRef?: string): Promise<string | null> {\n if (!this.requireAuth) {\n return null;\n }\n\n if (!storeRef) {\n // Auth cookies are store-scoped; without a storeRef there is no\n // cookie to read. Fail loudly rather than silently going anonymous.\n throw new Error(\n \"ServerApiClient: storeRef is required for authenticated requests\"\n );\n }\n\n // Dynamically import next/headers only when auth is needed — this\n // prevents Edge Runtime errors for non-auth requests.\n const { cookies } = await import(\"next/headers\");\n const jar = await cookies();\n const tokens = readAuthCookies(jar, storeRef);\n\n if (!tokens) {\n throw new Error(\"User not authenticated\");\n }\n\n return tokens.access_token;\n }\n\n private async makeRequest<T>(\n url: string,\n options: RequestInit = {},\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n try {\n // Set up timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Prepare headers\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...config?.headers,\n };\n\n // Add platform API key for authentication\n const platformApiKey = publicConfig().storefrontApiKey;\n if (platformApiKey) {\n headers[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n // Add auth token if required\n if (this.requireAuth) {\n const token = await this.getAuthToken(config?.storeRef);\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n }\n }\n\n // Make the fetch request\n const response = await fetch(`${this.baseUrl}${url}`, {\n ...options,\n headers,\n signal: config?.signal || controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n let data: T;\n const contentType = response.headers.get(\"content-type\");\n if (contentType && contentType.includes(\"application/json\")) {\n data = await response.json();\n } else {\n data = (await response.text()) as any;\n }\n\n // Handle non-OK responses\n if (!response.ok) {\n return {\n success: false,\n error: {\n message:\n (data as any)?.message ||\n `Request failed with status ${response.status}`,\n statusCode: response.status,\n error: (data as any)?.error || response.statusText,\n details: (data as any)?.details,\n },\n };\n }\n\n return {\n success: true,\n data,\n };\n } catch (error: any) {\n // Handle timeout\n if (error.name === \"AbortError\") {\n return {\n success: false,\n error: {\n message: \"Request timeout - please try again\",\n statusCode: 0,\n error: \"TIMEOUT\",\n },\n };\n }\n\n // Handle network errors\n if (error instanceof TypeError) {\n return {\n success: false,\n error: {\n message: \"Network error - check your connection\",\n statusCode: 0,\n error: \"NETWORK_ERROR\",\n },\n };\n }\n\n // Handle other errors\n return {\n success: false,\n error: {\n message:\n error instanceof Error ? error.message : \"Unknown error occurred\",\n statusCode: 0,\n },\n };\n }\n }\n\n async get<T>(url: string, config?: FetchConfig): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(url, { method: \"GET\" }, config);\n }\n\n async post<T>(\n url: string,\n data?: any,\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(\n url,\n {\n method: \"POST\",\n body: data ? JSON.stringify(data) : undefined,\n },\n config\n );\n }\n\n async put<T>(\n url: string,\n data?: any,\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(\n url,\n {\n method: \"PUT\",\n body: data ? JSON.stringify(data) : undefined,\n },\n config\n );\n }\n\n async patch<T>(\n url: string,\n data?: any,\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(\n url,\n {\n method: \"PATCH\",\n body: data ? JSON.stringify(data) : undefined,\n },\n config\n );\n }\n\n async delete<T>(url: string, config?: FetchConfig): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(url, { method: \"DELETE\" }, config);\n }\n\n // Additional utility methods for server-side use\n setBaseURL(baseUrl: string): void {\n this.baseUrl = baseUrl.replace(/\\/$/, \"\");\n }\n\n setTimeout(timeout: number): void {\n this.timeout = timeout;\n }\n}\n\n// Create a default instance for server-side use\nexport const serverApiClient = new ServerApiClient();\n\n// Create a server-side public (no-auth) instance\nexport const serverPublicApiClient = new ServerApiClient(publicConfig().apiUrl, {\n requireAuth: false,\n});\n\n// Export the class for custom instances\nexport { ServerApiClient };\n"],"mappings":"AACA,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAE7B,MAAM,kBAAkB;AAexB,MAAM,gBAAkD;AAAA,EAC9C;AAAA,EACA;AAAA,EACA;AAAA,EAER,YACE,UAAkB,aAAa,EAAE,QACjC,SACA;AACA,SAAK,cACH,SAAS,gBAAgB,SAAY,QAAQ,cAAc;AAC7D,SAAK,UAAU,QAAQ,QAAQ,OAAO,EAAE;AACxC,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAc,aAAa,UAA2C;AACpE,QAAI,CAAC,KAAK,aAAa;AACrB,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,UAAU;AAGb,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAIA,UAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,cAAc;AAC/C,UAAM,MAAM,MAAM,QAAQ;AAC1B,UAAM,SAAS,gBAAgB,KAAK,QAAQ;AAE5C,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC1C;AAEA,WAAO,OAAO;AAAA,EAChB;AAAA,EAEA,MAAc,YACZ,KACA,UAAuB,CAAC,GACxB,QACyB;AACzB,QAAI;AAEF,YAAM,aAAa,IAAI,gBAAgB;AACvC,YAAM,YAAY,WAAW,MAAM,WAAW,MAAM,GAAG,KAAK,OAAO;AAGnE,YAAM,UAAkC;AAAA,QACtC,gBAAgB;AAAA,QAChB,GAAG,QAAQ;AAAA,MACb;AAGA,YAAM,iBAAiB,aAAa,EAAE;AACtC,UAAI,gBAAgB;AAClB,gBAAQ,sBAAsB,IAAI;AAAA,MACpC;AAGA,UAAI,KAAK,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3C,YAAY;AAAA,QACd;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,IAAO,KAAa,QAA+C;AACvE,WAAO,KAAK,YAAe,KAAK,EAAE,QAAQ,MAAM,GAAG,MAAM;AAAA,EAC3D;AAAA,EAEA,MAAM,KACJ,KACA,MACA,QACyB;AACzB,WAAO,KAAK;AAAA,MACV;AAAA,MACA;AAAA,QACE,QAAQ;AAAA,QACR,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;AAAA,MACtC;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,IACJ,KACA,MACA,QACyB;AACzB,WAAO,KAAK;AAAA,MACV;AAAA,MACA;AAAA,QACE,QAAQ;AAAA,QACR,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;AAAA,MACtC;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,MACJ,KACA,MACA,QACyB;AACzB,WAAO,KAAK;AAAA,MACV;AAAA,MACA;AAAA,QACE,QAAQ;AAAA,QACR,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;AAAA,MACtC;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,OAAU,KAAa,QAA+C;AAC1E,WAAO,KAAK,YAAe,KAAK,EAAE,QAAQ,SAAS,GAAG,MAAM;AAAA,EAC9D;AAAA;AAAA,EAGA,WAAW,SAAuB;AAChC,SAAK,UAAU,QAAQ,QAAQ,OAAO,EAAE;AAAA,EAC1C;AAAA,EAEA,WAAW,SAAuB;AAChC,SAAK,UAAU;AAAA,EACjB;AACF;AAGO,MAAM,kBAAkB,IAAI,gBAAgB;AAG5C,MAAM,wBAAwB,IAAI,gBAAgB,aAAa,EAAE,QAAQ;AAAA,EAC9E,aAAa;AACf,CAAC;","names":[]}
1
+ {"version":3,"sources":["../../src/api/server-client.ts"],"sourcesContent":["import { ApiResponse, AuthenticatedApiClient } from \"../interfaces\";\nimport { authCookiePathFor, readAuthCookies } from \"../auth/cookies\";\nimport { publicConfig } from \"../config\";\n\nconst DEFAULT_TIMEOUT = 10000; // 10 seconds\n\ninterface FetchConfig {\n headers?: Record<string, string>;\n signal?: AbortSignal;\n /**\n * Auth cookies are store-scoped (see lib/auth/cookies.ts), so a\n * `requireAuth` request needs to know which store's cookie to read. There\n * is no store context at the module level (serverApiClient is a shared\n * singleton), so callers thread it through here instead.\n */\n storeRef?: string;\n [key: string]: any;\n}\n\nclass ServerApiClient implements AuthenticatedApiClient {\n private baseUrl: string;\n private timeout: number;\n private requireAuth: boolean;\n\n constructor(\n baseUrl: string = publicConfig().apiUrl,\n options?: { requireAuth?: boolean }\n ) {\n this.requireAuth =\n options?.requireAuth !== undefined ? options.requireAuth : true;\n this.baseUrl = baseUrl.replace(/\\/$/, \"\"); // Remove trailing slash\n this.timeout = DEFAULT_TIMEOUT;\n }\n\n private async getAuthToken(storeRef?: string): Promise<string | null> {\n if (!this.requireAuth) {\n return null;\n }\n\n if (!storeRef) {\n // Auth cookies are store-scoped; without a storeRef there is no\n // cookie to read. Fail loudly rather than silently going anonymous.\n throw new Error(\n \"ServerApiClient: storeRef is required for authenticated requests\"\n );\n }\n\n // Dynamically import next/headers only when auth is needed — this\n // prevents Edge Runtime errors for non-auth requests.\n const { cookies, headers } = await import(\"next/headers\");\n const tokens = readAuthCookies(\n await cookies(),\n storeRef,\n authCookiePathFor({ headers: await headers() }, storeRef)\n );\n\n if (!tokens) {\n throw new Error(\"User not authenticated\");\n }\n\n return tokens.access_token;\n }\n\n private async makeRequest<T>(\n url: string,\n options: RequestInit = {},\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n try {\n // Set up timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Prepare headers\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...config?.headers,\n };\n\n // Add platform API key for authentication\n const platformApiKey = publicConfig().storefrontApiKey;\n if (platformApiKey) {\n headers[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n // Add auth token if required\n if (this.requireAuth) {\n const token = await this.getAuthToken(config?.storeRef);\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n }\n }\n\n // Make the fetch request\n const response = await fetch(`${this.baseUrl}${url}`, {\n ...options,\n headers,\n signal: config?.signal || controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n let data: T;\n const contentType = response.headers.get(\"content-type\");\n if (contentType && contentType.includes(\"application/json\")) {\n data = await response.json();\n } else {\n data = (await response.text()) as any;\n }\n\n // Handle non-OK responses\n if (!response.ok) {\n return {\n success: false,\n error: {\n message:\n (data as any)?.message ||\n `Request failed with status ${response.status}`,\n statusCode: response.status,\n error: (data as any)?.error || response.statusText,\n details: (data as any)?.details,\n },\n };\n }\n\n return {\n success: true,\n data,\n };\n } catch (error: any) {\n // Handle timeout\n if (error.name === \"AbortError\") {\n return {\n success: false,\n error: {\n message: \"Request timeout - please try again\",\n statusCode: 0,\n error: \"TIMEOUT\",\n },\n };\n }\n\n // Handle network errors\n if (error instanceof TypeError) {\n return {\n success: false,\n error: {\n message: \"Network error - check your connection\",\n statusCode: 0,\n error: \"NETWORK_ERROR\",\n },\n };\n }\n\n // Handle other errors\n return {\n success: false,\n error: {\n message:\n error instanceof Error ? error.message : \"Unknown error occurred\",\n statusCode: 0,\n },\n };\n }\n }\n\n async get<T>(url: string, config?: FetchConfig): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(url, { method: \"GET\" }, config);\n }\n\n async post<T>(\n url: string,\n data?: any,\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(\n url,\n {\n method: \"POST\",\n body: data ? JSON.stringify(data) : undefined,\n },\n config\n );\n }\n\n async put<T>(\n url: string,\n data?: any,\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(\n url,\n {\n method: \"PUT\",\n body: data ? JSON.stringify(data) : undefined,\n },\n config\n );\n }\n\n async patch<T>(\n url: string,\n data?: any,\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(\n url,\n {\n method: \"PATCH\",\n body: data ? JSON.stringify(data) : undefined,\n },\n config\n );\n }\n\n async delete<T>(url: string, config?: FetchConfig): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(url, { method: \"DELETE\" }, config);\n }\n\n // Additional utility methods for server-side use\n setBaseURL(baseUrl: string): void {\n this.baseUrl = baseUrl.replace(/\\/$/, \"\");\n }\n\n setTimeout(timeout: number): void {\n this.timeout = timeout;\n }\n}\n\n// Create a default instance for server-side use\nexport const serverApiClient = new ServerApiClient();\n\n// Create a server-side public (no-auth) instance\nexport const serverPublicApiClient = new ServerApiClient(publicConfig().apiUrl, {\n requireAuth: false,\n});\n\n// Export the class for custom instances\nexport { ServerApiClient };\n"],"mappings":"AACA,SAAS,mBAAmB,uBAAuB;AACnD,SAAS,oBAAoB;AAE7B,MAAM,kBAAkB;AAexB,MAAM,gBAAkD;AAAA,EAC9C;AAAA,EACA;AAAA,EACA;AAAA,EAER,YACE,UAAkB,aAAa,EAAE,QACjC,SACA;AACA,SAAK,cACH,SAAS,gBAAgB,SAAY,QAAQ,cAAc;AAC7D,SAAK,UAAU,QAAQ,QAAQ,OAAO,EAAE;AACxC,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAc,aAAa,UAA2C;AACpE,QAAI,CAAC,KAAK,aAAa;AACrB,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,UAAU;AAGb,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAIA,UAAM,EAAE,SAAS,QAAQ,IAAI,MAAM,OAAO,cAAc;AACxD,UAAM,SAAS;AAAA,MACb,MAAM,QAAQ;AAAA,MACd;AAAA,MACA,kBAAkB,EAAE,SAAS,MAAM,QAAQ,EAAE,GAAG,QAAQ;AAAA,IAC1D;AAEA,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC1C;AAEA,WAAO,OAA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AAuB;AAChC,SAAK,UAAU,QAAQ,QAAQ,OAAO,EAAE;AAAA,EAC1C;AAAA,EAEA,WAAW,SAAuB;AAChC,SAAK,UAAU;AAAA,EACjB;AACF;AAGO,MAAM,kBAAkB,IAAI,gBAAgB;AAG5C,MAAM,wBAAwB,IAAI,gBAAgB,aAAa,EAAE,QAAQ;AAAA,EAC9E,aAAa;AACf,CAAC;","names":[]}
@@ -1,13 +1,19 @@
1
- function accessCookieName(storeRef) {
2
- return `ecomweb_sf_${storeRef}_at`;
1
+ function secureCookies() {
2
+ return process.env.NODE_ENV === "production";
3
3
  }
4
- function refreshCookieName(storeRef) {
5
- return `ecomweb_sf_${storeRef}_rt`;
4
+ function hostOnlyCookieName(name, path, secure = secureCookies()) {
5
+ return secure && path === "/" ? `__Host-${name}` : name;
6
+ }
7
+ function accessCookieName(storeRef, path) {
8
+ return hostOnlyCookieName(`ecomweb_sf_${storeRef}_at`, path);
9
+ }
10
+ function refreshCookieName(storeRef, path) {
11
+ return hostOnlyCookieName(`ecomweb_sf_${storeRef}_rt`, path);
6
12
  }
7
13
  const HOST_MAPPED_HEADER = "x-ecomweb-host-mapped";
8
- function readAuthCookies(jar, storeRef) {
9
- const access_token = jar.get(accessCookieName(storeRef))?.value;
10
- const refresh_token = jar.get(refreshCookieName(storeRef))?.value;
14
+ function readAuthCookies(jar, storeRef, path) {
15
+ const access_token = jar.get(accessCookieName(storeRef, path))?.value;
16
+ const refresh_token = jar.get(refreshCookieName(storeRef, path))?.value;
11
17
  if (!access_token || !refresh_token) return null;
12
18
  return { access_token, refresh_token };
13
19
  }
@@ -24,58 +30,68 @@ function authCookiePathFor(request, storeRef) {
24
30
  function storeBasePathFor(request, storeRef) {
25
31
  return isHostMappedRequest(request) ? "" : `/store/${encodeURIComponent(storeRef)}`;
26
32
  }
27
- const BASE_OPTIONS = {
28
- httpOnly: true,
29
- secure: process.env.NODE_ENV === "production",
30
- sameSite: "lax"
31
- };
32
- function oauthNonceCookieName(storeRef) {
33
- return `ecomweb_sf_${storeRef}_oauth`;
33
+ function baseOptions() {
34
+ return { httpOnly: true, secure: secureCookies(), sameSite: "lax" };
35
+ }
36
+ function oauthNonceCookieName(storeRef, path) {
37
+ return hostOnlyCookieName(`ecomweb_sf_${storeRef}_oauth`, path);
34
38
  }
35
39
  const OAUTH_NONCE_MAX_AGE_SECONDS = 600;
36
40
  function writeOAuthNonceCookie(response, storeRef, nonce, path) {
37
- response.cookies.set(oauthNonceCookieName(storeRef), nonce, {
38
- ...BASE_OPTIONS,
41
+ response.cookies.set(oauthNonceCookieName(storeRef, path), nonce, {
42
+ ...baseOptions(),
39
43
  path,
40
44
  maxAge: OAUTH_NONCE_MAX_AGE_SECONDS
41
45
  });
42
46
  }
43
47
  function clearOAuthNonceCookie(response, storeRef, path) {
44
- response.cookies.set(oauthNonceCookieName(storeRef), "", {
45
- ...BASE_OPTIONS,
48
+ response.cookies.set(oauthNonceCookieName(storeRef, path), "", {
49
+ ...baseOptions(),
46
50
  path,
47
51
  maxAge: 0
48
52
  });
49
53
  }
50
54
  function writeAuthCookies(response, storeRef, tokens, path) {
51
- response.cookies.set(accessCookieName(storeRef), tokens.access_token, {
52
- ...BASE_OPTIONS,
53
- path
54
- });
55
- response.cookies.set(refreshCookieName(storeRef), tokens.refresh_token, {
56
- ...BASE_OPTIONS,
55
+ response.cookies.set(accessCookieName(storeRef, path), tokens.access_token, {
56
+ ...baseOptions(),
57
57
  path
58
58
  });
59
+ response.cookies.set(
60
+ refreshCookieName(storeRef, path),
61
+ tokens.refresh_token,
62
+ {
63
+ ...baseOptions(),
64
+ path
65
+ }
66
+ );
59
67
  }
60
68
  function clearAuthCookies(response, storeRef, path) {
61
- response.cookies.set(accessCookieName(storeRef), "", {
62
- ...BASE_OPTIONS,
69
+ response.cookies.set(accessCookieName(storeRef, path), "", {
70
+ ...baseOptions(),
63
71
  path,
64
72
  maxAge: 0
65
73
  });
66
- response.cookies.set(refreshCookieName(storeRef), "", {
67
- ...BASE_OPTIONS,
74
+ response.cookies.set(refreshCookieName(storeRef, path), "", {
75
+ ...baseOptions(),
68
76
  path,
69
77
  maxAge: 0
70
78
  });
71
79
  const otherPath = path === LEGACY_PATH ? authCookiePath(storeRef, false) : LEGACY_PATH;
72
- for (const name of [
73
- accessCookieName(storeRef),
74
- refreshCookieName(storeRef)
75
- ]) {
80
+ const stale = [
81
+ [accessCookieName(storeRef, otherPath), otherPath],
82
+ [refreshCookieName(storeRef, otherPath), otherPath]
83
+ ];
84
+ if (secureCookies()) {
85
+ stale.push(
86
+ [`ecomweb_sf_${storeRef}_at`, LEGACY_PATH],
87
+ [`ecomweb_sf_${storeRef}_rt`, LEGACY_PATH]
88
+ );
89
+ }
90
+ const secure = secureCookies() ? "; Secure" : "";
91
+ for (const [name, stalePath] of stale) {
76
92
  response.headers.append(
77
93
  "set-cookie",
78
- `${name}=; Path=${otherPath}; Max-Age=0; HttpOnly; SameSite=Lax${BASE_OPTIONS.secure ? "; Secure" : ""}`
94
+ `${name}=; Path=${stalePath}; Max-Age=0; HttpOnly; SameSite=Lax${secure}`
79
95
  );
80
96
  }
81
97
  }
@@ -86,10 +102,12 @@ export {
86
102
  authCookiePathFor,
87
103
  clearAuthCookies,
88
104
  clearOAuthNonceCookie,
105
+ hostOnlyCookieName,
89
106
  isHostMappedRequest,
90
107
  oauthNonceCookieName,
91
108
  readAuthCookies,
92
109
  refreshCookieName,
110
+ secureCookies,
93
111
  storeBasePathFor,
94
112
  writeAuthCookies,
95
113
  writeOAuthNonceCookie
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/cookies.ts"],"sourcesContent":["import type { NextResponse } from \"next/server\";\nimport type { AuthTokens } from \"@ecomweb/sdk\";\n\n/**\n * Cookie names are store-scoped because the platform serves many stores from\n * one origin (`/store/<storeRef>`). A shared name lets store B read store A's\n * session on the same domain.\n */\nexport function accessCookieName(storeRef: string): string {\n return `ecomweb_sf_${storeRef}_at`;\n}\n\nexport function refreshCookieName(storeRef: string): string {\n return `ecomweb_sf_${storeRef}_rt`;\n}\n\n/**\n * Request header the middleware (`proxy.ts`) stamps on every request it sees,\n * recording whether the **Host** identified the store — i.e. whether this is a\n * custom domain / subdomain deployment (one store per origin) or the shared\n * path-based host (`<origin>/store/<ref>/…`).\n *\n * It exists because the cookie `path` has to match the URL space the *browser*\n * is in, and the auth route handler cannot tell the two apart on its own: the\n * client calls `/store/<ref>/api/auth/*` in both cases (`lib/auth/context.tsx`).\n * The middleware is the only place that resolves Host → store.\n *\n * Always overwritten by the middleware, so a browser-supplied value cannot\n * survive on any path the middleware matches. On the paths it does not match\n * (root `/api/*`, which is reachable only on a custom domain) the value is\n * absent and the fallback is the unscoped path — the pre-existing behaviour.\n */\nexport const HOST_MAPPED_HEADER = \"x-ecomweb-host-mapped\";\n\n/** Minimal shape shared by `cookies()` and `request.cookies`. */\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** Minimal shape shared by `NextRequest` and a plain `Request`. */\ninterface HeaderReader {\n headers: { get(name: string): string | null };\n}\n\nexport function readAuthCookies(\n jar: CookieReader,\n storeRef: string\n): AuthTokens | null {\n const access_token = jar.get(accessCookieName(storeRef))?.value;\n const refresh_token = jar.get(refreshCookieName(storeRef))?.value;\n\n if (!access_token || !refresh_token) return null;\n\n return { access_token, refresh_token };\n}\n\n/**\n * The unscoped path every auth cookie used to be written with, and still is\n * on a custom domain. Also the path the migration has to clear: sessions\n * created before this change live here.\n */\nconst LEGACY_PATH = \"/\";\n\n/**\n * The `path` for this store's auth cookies.\n *\n * On the shared path-based host every store lives under `/store/<ref>/…`, so\n * scoping the cookie there keeps store B's server code from ever receiving\n * store A's token. On a custom domain the shopper's URLs are rooted at `/`\n * and the cookie must stay unscoped, or the browser would withhold it from\n * every page and the shopper would look signed out.\n */\nexport function authCookiePath(storeRef: string, hostMapped: boolean): string {\n return hostMapped ? LEGACY_PATH : `/store/${encodeURIComponent(storeRef)}`;\n}\n\n/**\n * Whether the Host identified the store for this request, per the middleware.\n *\n * Absent header → treated as host-mapped, i.e. exactly what this code did\n * before the scoping existed. Never guess \"shared host\" without evidence:\n * guessing wrong in that direction scopes the cookie to a path the shopper's\n * pages are not under, and hides their session from them.\n */\nexport function isHostMappedRequest(request: HeaderReader): boolean {\n return request.headers.get(HOST_MAPPED_HEADER) !== \"0\";\n}\n\n/** `authCookiePath` for an incoming request, using the middleware's stamp. */\nexport function authCookiePathFor(\n request: HeaderReader,\n storeRef: string\n): string {\n return authCookiePath(storeRef, isHostMappedRequest(request));\n}\n\n/**\n * The store's own root as the *browser* sees it: `\"\"` on a custom domain or\n * subdomain (the store is the origin), `/store/<ref>` on the shared\n * path-based host. Derived from the same signal as the cookie path so the two\n * can never disagree — and not from the request path, which is\n * `/store/<ref>/api/…` on both deployments.\n */\nexport function storeBasePathFor(\n request: HeaderReader,\n storeRef: string\n): string {\n return isHostMappedRequest(request)\n ? \"\"\n : `/store/${encodeURIComponent(storeRef)}`;\n}\n\nconst BASE_OPTIONS = {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\" as const,\n};\n\n/**\n * Binds an OAuth round trip to the browser that started it.\n *\n * `google/complete` has to accept GET — Google's redirect chain lands there —\n * and `sameSite: \"lax\"` sends cookies on a cross-site top-level navigation, so\n * without this a link on any site could feed a victim's browser a one-time\n * code the attacker minted from their OWN Google account and plant the\n * attacker's session in it. The signed `state` cannot help: the backend\n * consumes it before the storefront is ever reached.\n *\n * `lax` (not `strict`) is required here for the same reason it is on the\n * session cookies: the browser arrives from Google's origin.\n */\nexport function oauthNonceCookieName(storeRef: string): string {\n return `ecomweb_sf_${storeRef}_oauth`;\n}\n\n/** Long enough for a human to finish Google's consent screen, no longer. */\nconst OAUTH_NONCE_MAX_AGE_SECONDS = 600;\n\nexport function writeOAuthNonceCookie(\n response: NextResponse,\n storeRef: string,\n nonce: string,\n path: string\n): void {\n response.cookies.set(oauthNonceCookieName(storeRef), nonce, {\n ...BASE_OPTIONS,\n path,\n maxAge: OAUTH_NONCE_MAX_AGE_SECONDS,\n });\n}\n\nexport function clearOAuthNonceCookie(\n response: NextResponse,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(oauthNonceCookieName(storeRef), \"\", {\n ...BASE_OPTIONS,\n path,\n maxAge: 0,\n });\n}\n\nexport function writeAuthCookies(\n response: NextResponse,\n storeRef: string,\n tokens: AuthTokens,\n path: string\n): void {\n response.cookies.set(accessCookieName(storeRef), tokens.access_token, {\n ...BASE_OPTIONS,\n path,\n });\n response.cookies.set(refreshCookieName(storeRef), tokens.refresh_token, {\n ...BASE_OPTIONS,\n path,\n });\n}\n\n/**\n * Clearing has to name the identical path the cookie was written with — a\n * `Set-Cookie` with a different path creates a second, empty cookie and leaves\n * the real one in place. So logout clears BOTH paths, always.\n *\n * Not belt and braces: a cookie can genuinely exist at the other path. Every\n * session that predates the scoping lives at `Path=/`, and a request whose\n * Host lookup failed transiently writes the scoped path on a deployment that\n * otherwise uses the unscoped one. Either survivor would be handed straight\n * back by `readAuthCookies` — a live session the shopper believes they ended.\n */\nexport function clearAuthCookies(\n response: NextResponse,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(accessCookieName(storeRef), \"\", {\n ...BASE_OPTIONS,\n path,\n maxAge: 0,\n });\n response.cookies.set(refreshCookieName(storeRef), \"\", {\n ...BASE_OPTIONS,\n path,\n maxAge: 0,\n });\n\n const otherPath =\n path === LEGACY_PATH ? authCookiePath(storeRef, false) : LEGACY_PATH;\n\n // `response.cookies` is keyed by name alone and rewrites the whole\n // Set-Cookie list on every `set()`, so a second cookie of the same name\n // cannot go through it and must be appended afterwards, never before.\n for (const name of [\n accessCookieName(storeRef),\n refreshCookieName(storeRef),\n ]) {\n response.headers.append(\n \"set-cookie\",\n `${name}=; Path=${otherPath}; Max-Age=0; HttpOnly; SameSite=Lax${\n BASE_OPTIONS.secure ? \"; Secure\" : \"\"\n }`\n );\n }\n}\n"],"mappings":"AAQO,SAAS,iBAAiB,UAA0B;AACzD,SAAO,cAAc,QAAQ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AS,QAAQ,IAAI,iBAAiB,QAAQ,GAAG,OAAO,cAAc;AAAA,IACpE,GAAG;AAAA,IACH;AAAA,EACF,CAAC;AACD,WAAS,QAAQ,IAAI,kBAAkB,QAAQ,GAAG,OAAO,eAAe;AAAA,IACtE,GAAG;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAaO,SAAS,iBACd,UACA,UACA,MACM;AACN,WAAS,QAAQ,IAAI,iBAAiB,QAAQ,GAAG,IAAI;AAAA,IACnD,GAAG;AAAA,IACH;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AACD,WAAS,QAAQ,IAAI,kBAAkB,QAAQ,GAAG,IAAI;AAAA,IACpD,GAAG;AAAA,IACH;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AAED,QAAM,YACJ,SAAS,cAAc,eAAe,UAAU,KAAK,IAAI;AAK3D,aAAW,QAAQ;AAAA,IACjB,iBAAiB,QAAQ;AAAA,IACzB,kBAAkB,QAAQ;AAAA,EAC5B,GAAG;AACD,aAAS,QAAQ;AAAA,MACf;AAAA,MACA,GAAG,IAAI,WAAW,SAAS,sCACzB,aAAa,SAAS,aAAa,EACrC;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/cookies.ts"],"sourcesContent":["import type { NextResponse } from \"next/server\";\nimport type { AuthTokens } from \"@ecomweb/sdk\";\n\n/** Whether cookies are written `Secure` (everywhere but local dev over http). */\nexport function secureCookies(): boolean {\n return process.env.NODE_ENV === \"production\";\n}\n\n/**\n * `name` with the `__Host-` prefix whenever the cookie can carry it: `Secure`\n * and `Path=/` (the browser rejects a `__Host-` cookie that is not both).\n *\n * Store subdomains are siblings under the platform domain, so a merchant\n * script on one store can set a cookie with `Domain=<platform domain>` that\n * every other store receives: a planted session or OAuth nonce (cookie\n * tossing). Browsers also reject a `__Host-` cookie that names a Domain, so\n * one read under this name was set by this host and no other.\n *\n * Readers must look up the same name the writer used and never fall back to\n * the bare one, which any sibling store can set. Path-scoped cookies (the\n * shared `/store/<ref>` host) cannot take the prefix and keep the bare name.\n */\nexport function hostOnlyCookieName(\n name: string,\n path: string,\n secure = secureCookies()\n): string {\n return secure && path === \"/\" ? `__Host-${name}` : name;\n}\n\n/**\n * Cookie names are store-scoped because the platform serves many stores from\n * one origin (`/store/<storeRef>`). A shared name lets store B read store A's\n * session on the same domain. `path` is the cookie's (see authCookiePath).\n */\nexport function accessCookieName(storeRef: string, path: string): string {\n return hostOnlyCookieName(`ecomweb_sf_${storeRef}_at`, path);\n}\n\nexport function refreshCookieName(storeRef: string, path: string): string {\n return hostOnlyCookieName(`ecomweb_sf_${storeRef}_rt`, path);\n}\n\n/**\n * Request header the middleware (`proxy.ts`) stamps on every request it sees,\n * recording whether the **Host** identified the store — i.e. whether this is a\n * custom domain / subdomain deployment (one store per origin) or the shared\n * path-based host (`<origin>/store/<ref>/…`).\n *\n * It exists because the cookie `path` has to match the URL space the *browser*\n * is in, and the auth route handler cannot tell the two apart on its own: the\n * client calls `/store/<ref>/api/auth/*` in both cases (`lib/auth/context.tsx`).\n * The middleware is the only place that resolves Host → store.\n *\n * Always overwritten by the middleware, so a browser-supplied value cannot\n * survive on any path the middleware matches. On the paths it does not match\n * (root `/api/*`, which is reachable only on a custom domain) the value is\n * absent and the fallback is the unscoped path — the pre-existing behaviour.\n */\nexport const HOST_MAPPED_HEADER = \"x-ecomweb-host-mapped\";\n\n/** Minimal shape shared by `cookies()` and `request.cookies`. */\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** Minimal shape shared by `NextRequest` and a plain `Request`. */\ninterface HeaderReader {\n headers: { get(name: string): string | null };\n}\n\n/** The session pair stored at `path` (see authCookiePath), if both are set. */\nexport function readAuthCookies(\n jar: CookieReader,\n storeRef: string,\n path: string\n): AuthTokens | null {\n const access_token = jar.get(accessCookieName(storeRef, path))?.value;\n const refresh_token = jar.get(refreshCookieName(storeRef, path))?.value;\n\n if (!access_token || !refresh_token) return null;\n\n return { access_token, refresh_token };\n}\n\n/**\n * The unscoped path every auth cookie used to be written with, and still is\n * on a custom domain. Also the path the migration has to clear: sessions\n * created before this change live here.\n */\nconst LEGACY_PATH = \"/\";\n\n/**\n * The `path` for this store's auth cookies.\n *\n * On the shared path-based host every store lives under `/store/<ref>/…`, so\n * scoping the cookie there keeps store B's server code from ever receiving\n * store A's token. On a custom domain the shopper's URLs are rooted at `/`\n * and the cookie must stay unscoped, or the browser would withhold it from\n * every page and the shopper would look signed out.\n */\nexport function authCookiePath(storeRef: string, hostMapped: boolean): string {\n return hostMapped ? LEGACY_PATH : `/store/${encodeURIComponent(storeRef)}`;\n}\n\n/**\n * Whether the Host identified the store for this request, per the middleware.\n *\n * Absent header → treated as host-mapped, i.e. exactly what this code did\n * before the scoping existed. Never guess \"shared host\" without evidence:\n * guessing wrong in that direction scopes the cookie to a path the shopper's\n * pages are not under, and hides their session from them.\n */\nexport function isHostMappedRequest(request: HeaderReader): boolean {\n return request.headers.get(HOST_MAPPED_HEADER) !== \"0\";\n}\n\n/** `authCookiePath` for an incoming request, using the middleware's stamp. */\nexport function authCookiePathFor(\n request: HeaderReader,\n storeRef: string\n): string {\n return authCookiePath(storeRef, isHostMappedRequest(request));\n}\n\n/**\n * The store's own root as the *browser* sees it: `\"\"` on a custom domain or\n * subdomain (the store is the origin), `/store/<ref>` on the shared\n * path-based host. Derived from the same signal as the cookie path so the two\n * can never disagree — and not from the request path, which is\n * `/store/<ref>/api/…` on both deployments.\n */\nexport function storeBasePathFor(\n request: HeaderReader,\n storeRef: string\n): string {\n return isHostMappedRequest(request)\n ? \"\"\n : `/store/${encodeURIComponent(storeRef)}`;\n}\n\nfunction baseOptions() {\n return { httpOnly: true, secure: secureCookies(), sameSite: \"lax\" as const };\n}\n\n/**\n * Binds an OAuth round trip to the browser that started it.\n *\n * `google/complete` has to accept GET — Google's redirect chain lands there —\n * and `sameSite: \"lax\"` sends cookies on a cross-site top-level navigation, so\n * without this a link on any site could feed a victim's browser a one-time\n * code the attacker minted from their OWN Google account and plant the\n * attacker's session in it. The signed `state` cannot help: the backend\n * consumes it before the storefront is ever reached.\n *\n * `lax` (not `strict`) is required here for the same reason it is on the\n * session cookies: the browser arrives from Google's origin.\n */\nexport function oauthNonceCookieName(storeRef: string, path: string): string {\n return hostOnlyCookieName(`ecomweb_sf_${storeRef}_oauth`, path);\n}\n\n/** Long enough for a human to finish Google's consent screen, no longer. */\nconst OAUTH_NONCE_MAX_AGE_SECONDS = 600;\n\nexport function writeOAuthNonceCookie(\n response: NextResponse,\n storeRef: string,\n nonce: string,\n path: string\n): void {\n response.cookies.set(oauthNonceCookieName(storeRef, path), nonce, {\n ...baseOptions(),\n path,\n maxAge: OAUTH_NONCE_MAX_AGE_SECONDS,\n });\n}\n\nexport function clearOAuthNonceCookie(\n response: NextResponse,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(oauthNonceCookieName(storeRef, path), \"\", {\n ...baseOptions(),\n path,\n maxAge: 0,\n });\n}\n\nexport function writeAuthCookies(\n response: NextResponse,\n storeRef: string,\n tokens: AuthTokens,\n path: string\n): void {\n response.cookies.set(accessCookieName(storeRef, path), tokens.access_token, {\n ...baseOptions(),\n path,\n });\n response.cookies.set(\n refreshCookieName(storeRef, path),\n tokens.refresh_token,\n {\n ...baseOptions(),\n path,\n }\n );\n}\n\n/**\n * Clearing has to name the identical path the cookie was written with — a\n * `Set-Cookie` with a different path creates a second, empty cookie and leaves\n * the real one in place. So logout clears BOTH paths, always.\n *\n * Not belt and braces: a cookie can genuinely exist at the other path. Every\n * session that predates the scoping lives at `Path=/`, and a request whose\n * Host lookup failed transiently writes the scoped path on a deployment that\n * otherwise uses the unscoped one. Either survivor would be handed straight\n * back by `readAuthCookies` — a live session the shopper believes they ended.\n */\nexport function clearAuthCookies(\n response: NextResponse,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(accessCookieName(storeRef, path), \"\", {\n ...baseOptions(),\n path,\n maxAge: 0,\n });\n response.cookies.set(refreshCookieName(storeRef, path), \"\", {\n ...baseOptions(),\n path,\n maxAge: 0,\n });\n\n // The same session wherever else it can be stored: at the other path, and\n // in production under the bare names at `/` every session used before the\n // `__Host-` names (still sent to the scoped path, so still readable there).\n const otherPath =\n path === LEGACY_PATH ? authCookiePath(storeRef, false) : LEGACY_PATH;\n const stale: Array<[name: string, path: string]> = [\n [accessCookieName(storeRef, otherPath), otherPath],\n [refreshCookieName(storeRef, otherPath), otherPath],\n ];\n if (secureCookies()) {\n stale.push(\n [`ecomweb_sf_${storeRef}_at`, LEGACY_PATH],\n [`ecomweb_sf_${storeRef}_rt`, LEGACY_PATH]\n );\n }\n\n // `response.cookies` is keyed by name alone and rewrites the whole\n // Set-Cookie list on every `set()`, so a second cookie of the same name\n // cannot go through it and must be appended afterwards, never before.\n const secure = secureCookies() ? \"; Secure\" : \"\";\n for (const [name, stalePath] of stale) {\n response.headers.append(\n \"set-cookie\",\n `${name}=; Path=${stalePath}; Max-Age=0; HttpOnly; SameSite=Lax${secure}`\n );\n }\n}\n"],"mappings":"AAIO,SAAS,gBAAyB;AACvC,SAAO,QAAQ,IAAI,aAAa;AAClC;AAgBO,SAAS,mBACd,MACA,MACA,SAAS,cAAc,GACf;AACR,SAAO,UAAU,SAAS,MAAM,UAAU,IAAI,KAAK;AACrD;AAOO,SAAS,iBAAiB,UAAkB,MAAsB;AACvE,SAAO,mBAAmB,cAAc,QAAQ,OAAO,IAAI;AAC7D;AAEO,SAAS,kBAAkB,UAAkB,MAAsB;AACxE,SAAO,mBAAmB,cAAc,QAAQ,OAAO,IAAI;AAC7D;AAkBO,MAAM,qBAAqB;AAa3B,SAAS,gBACd,KACA,UACA,MACmB;AACnB,QAAM,eAAe,IAAI,IAAI,iBAAiB,UAAU,IAAI,CAAC,GAAG;AAChE,QAAM,gBAAgB,IAAI,IAAI,kBAAkB,UAAU,IAAI,CAAC,GAAG;AAElE,MAAI,CAAC,gBAAgB,CAAC,cAAe,QAAO;AAE5C,SAAO,EAAE,cAAc,cAAc;AACvC;AAOA,MA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,IAAI,iBAAiB,UAAU,IAAI,GAAG,IAAI;AAAA,IACzD,GAAG,YAAY;AAAA,IACf;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AACD,WAAS,QAAQ,IAAI,kBAAkB,UAAU,IAAI,GAAG,IAAI;AAAA,IAC1D,GAAG,YAAY;AAAA,IACf;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AAKD,QAAM,YACJ,SAAS,cAAc,eAAe,UAAU,KAAK,IAAI;AAC3D,QAAM,QAA6C;AAAA,IACjD,CAAC,iBAAiB,UAAU,SAAS,GAAG,SAAS;AAAA,IACjD,CAAC,kBAAkB,UAAU,SAAS,GAAG,SAAS;AAAA,EACpD;AACA,MAAI,cAAc,GAAG;AACnB,UAAM;AAAA,MACJ,CAAC,cAAc,QAAQ,OAAO,WAAW;AAAA,MACzC,CAAC,cAAc,QAAQ,OAAO,WAAW;AAAA,IAC3C;AAAA,EACF;AAKA,QAAM,SAAS,cAAc,IAAI,aAAa;AAC9C,aAAW,CAAC,MAAM,SAAS,KAAK,OAAO;AACrC,aAAS,QAAQ;AAAA,MACf;AAAA,MACA,GAAG,IAAI,WAAW,SAAS,sCAAsC,MAAM;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
@@ -16,7 +16,8 @@ const ERROR_COPY = {
16
16
  ADDRESS_NOT_FOUND: "Kh\xF4ng t\xECm th\u1EA5y \u0111\u1ECBa ch\u1EC9 n\xE0y.",
17
17
  ORDER_NOT_FOUND: "Kh\xF4ng t\xECm th\u1EA5y \u0111\u01A1n h\xE0ng n\xE0y.",
18
18
  ORDER_NOT_CANCELLABLE: "\u0110\u01A1n h\xE0ng n\xE0y kh\xF4ng th\u1EC3 hu\u1EF7 \u0111\u01B0\u1EE3c n\u1EEFa.",
19
- INSUFFICIENT_INVENTORY: "M\u1ED9t s\u1ED1 s\u1EA3n ph\u1EA9m kh\xF4ng \u0111\u1EE7 h\xE0ng."
19
+ INSUFFICIENT_INVENTORY: "M\u1ED9t s\u1ED1 s\u1EA3n ph\u1EA9m kh\xF4ng \u0111\u1EE7 h\xE0ng.",
20
+ ORDER_PROMOTION_NOT_APPLICABLE: "M\xE3 gi\u1EA3m gi\xE1 kh\xF4ng c\xF2n d\xF9ng \u0111\u01B0\u1EE3c cho \u0111\u01A1n n\xE0y n\xEAn \u0111\xE3 \u0111\u01B0\u1EE3c g\u1EE1. Vui l\xF2ng ki\u1EC3m tra l\u1EA1i t\u1ED5ng ti\u1EC1n r\u1ED3i \u0111\u1EB7t h\xE0ng."
20
21
  };
21
22
  const STATUS_COPY = {
22
23
  0: "Kh\xF4ng th\u1EC3 k\u1EBFt n\u1ED1i m\xE1y ch\u1EE7. Vui l\xF2ng ki\u1EC3m tra k\u1EBFt n\u1ED1i m\u1EA1ng.",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/error-copy.ts"],"sourcesContent":["/**\n * Shopper-facing copy for backend errors.\n *\n * Project rule: backend exception messages are written in English and are\n * never shown to a shopper. The backend serialises every business error as\n * `{ code, message, details, timestamp }` (see `src/common/exceptions/` in the\n * api repo) and `code` is the stable identifier — this module is the single\n * place that turns one into Vietnamese.\n *\n * The fallback is always a generic Vietnamese sentence. Never fall back to the\n * backend's `message`.\n */\n\nexport const GENERIC_ERROR_COPY = \"Đã xảy ra lỗi. Vui lòng thử lại.\";\n\n/**\n * Keyed by the backend's stable `code`. Sources, read directly rather than\n * guessed:\n * - `AUTH_*` — `src/modules/customer-auth/domain/constants/auth.constants.ts`\n * (`AUTH_ERROR`).\n * - `ACCESS_DENIED` — `AuthorizationException.accessDenied()`, thrown by\n * `customer-addresses.controller.ts` on an address the caller does not own.\n * - `<RESOURCE>_NOT_FOUND` — `ResourceNotFoundException`, whose code is\n * `${resource.toUpperCase()}_NOT_FOUND`. `Address` and `Order` are the two\n * resources the storefront's authenticated routes can produce.\n * - `VALIDATION_FAILED` — `ValidationException`.\n * - `ORDER_NOT_CANCELLABLE` — `ORDER_ERROR.NOT_CANCELLABLE`\n * (`src/modules/orders/domain/constants/order-error.constants.ts`),\n * thrown by `OrderCancelCommandHandler` when a customer tries to cancel\n * an order outside pending/confirmed/processing.\n * - `INSUFFICIENT_INVENTORY`: `InsufficientInventoryException`\n * (`src/modules/inventory/domain/exceptions/`), thrown when an order asks\n * for more of a deny-policy variant than is available.\n */\nconst ERROR_COPY: Record<string, string> = {\n AUTH_INVALID_CREDENTIALS: \"Email hoặc mật khẩu không đúng.\",\n AUTH_ACCOUNT_LOCKED: \"Quá nhiều lần thử. Vui lòng thử lại sau 15 phút.\",\n AUTH_EMAIL_NOT_VERIFIED: \"Vui lòng xác thực email của bạn trước.\",\n AUTH_METHOD_DISABLED:\n \"Phương thức đăng nhập này không khả dụng cho cửa hàng này.\",\n AUTH_TOKEN_INVALID: \"Mã xác thực không hợp lệ hoặc đã được sử dụng.\",\n AUTH_TOKEN_EXPIRED: \"Mã xác thực đã hết hạn. Vui lòng yêu cầu mã mới.\",\n AUTH_SESSION_EXPIRED: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n AUTH_WEAK_PASSWORD: \"Mật khẩu chưa đáp ứng yêu cầu của cửa hàng.\",\n AUTH_RATE_LIMITED: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n AUTH_STORE_MISMATCH:\n \"Phiên đăng nhập không thuộc cửa hàng này. Vui lòng đăng nhập lại.\",\n AUTH_EMAIL_TAKEN: \"Email này đã được sử dụng.\",\n\n ACCESS_DENIED: \"Bạn không có quyền thực hiện thao tác này.\",\n VALIDATION_FAILED: \"Thông tin chưa hợp lệ. Vui lòng kiểm tra lại.\",\n ADDRESS_NOT_FOUND: \"Không tìm thấy địa chỉ này.\",\n ORDER_NOT_FOUND: \"Không tìm thấy đơn hàng này.\",\n ORDER_NOT_CANCELLABLE: \"Đơn hàng này không thể huỷ được nữa.\",\n INSUFFICIENT_INVENTORY: \"Một số sản phẩm không đủ hàng.\",\n};\n\n/**\n * Nest's built-in `UnauthorizedException` / `ForbiddenException` (thrown by\n * `TenantUserAuthGuard`, `StorefrontApiKeyGuard` and the `@CurrentCustomer`\n * decorator) carry no `code` at all — only a status and English prose. Status\n * is the only stable signal there.\n */\nconst STATUS_COPY: Record<number, string> = {\n 0: \"Không thể kết nối máy chủ. Vui lòng kiểm tra kết nối mạng.\",\n 401: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n 403: \"Bạn không có quyền thực hiện thao tác này.\",\n 404: \"Không tìm thấy dữ liệu yêu cầu.\",\n 429: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n 500: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 502: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 503: \"Máy chủ đang bận. Vui lòng thử lại sau.\",\n 504: \"Máy chủ phản hồi quá lâu. Vui lòng thử lại.\",\n};\n\n/** Maps a backend error code to Vietnamese copy. */\nexport function errorCopy(\n code: string | null | undefined,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n return (code && ERROR_COPY[code]) || fallback;\n}\n\n/**\n * The same mapping for a caught throwable. `ApiClientError` (thrown by the\n * SDK's `unwrap`) carries `code` and `statusCode`; `lib/auth/context.tsx`\n * surfaces `{ message, code }`. Anything else falls through to `fallback`.\n *\n * The caught value's own `message` is deliberately never used: it is either\n * the backend's English prose or an axios internal string.\n */\nexport function errorCopyFor(\n error: unknown,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n if (!error || typeof error !== \"object\") return fallback;\n\n const { code, statusCode } = error as {\n code?: unknown;\n statusCode?: unknown;\n };\n\n if (typeof code === \"string\" && ERROR_COPY[code]) return ERROR_COPY[code];\n if (typeof statusCode === \"number\" && STATUS_COPY[statusCode]) {\n return STATUS_COPY[statusCode];\n }\n\n return fallback;\n}\n"],"mappings":"AAaO,MAAM,qBAAqB;AAqBlC,MAAM,aAAqC;AAAA,EACzC,0BAA0B;AAAA,EAC1B,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EACzB,sBACE;AAAA,EACF,oBAAoB;AAAA,EACpB,oBAAoB;AAAA,EACpB,sBAAsB;AAAA,EACtB,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,qBACE;AAAA,EACF,kBAAkB;AAAA,EAElB,eAAe;AAAA,EACf,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,uBAAuB;AAAA,EACvB,wBAAwB;AAC1B;AAQA,MAAM,cAAsC;AAAA,EAC1C,GAAG;AAAA,EACH,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAGO,SAAS,UACd,MACA,WAAmB,oBACX;AACR,SAAQ,QAAQ,WAAW,IAAI,KAAM;AACvC;AAUO,SAAS,aACd,OACA,WAAmB,oBACX;AACR,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,QAAM,EAAE,MAAM,WAAW,IAAI;AAK7B,MAAI,OAAO,SAAS,YAAY,WAAW,IAAI,EAAG,QAAO,WAAW,IAAI;AACxE,MAAI,OAAO,eAAe,YAAY,YAAY,UAAU,GAAG;AAC7D,WAAO,YAAY,UAAU;AAAA,EAC/B;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/error-copy.ts"],"sourcesContent":["/**\n * Shopper-facing copy for backend errors.\n *\n * Project rule: backend exception messages are written in English and are\n * never shown to a shopper. The backend serialises every business error as\n * `{ code, message, details, timestamp }` (see `src/common/exceptions/` in the\n * api repo) and `code` is the stable identifier — this module is the single\n * place that turns one into Vietnamese.\n *\n * The fallback is always a generic Vietnamese sentence. Never fall back to the\n * backend's `message`.\n */\n\nexport const GENERIC_ERROR_COPY = \"Đã xảy ra lỗi. Vui lòng thử lại.\";\n\n/**\n * Keyed by the backend's stable `code`. Sources, read directly rather than\n * guessed:\n * - `AUTH_*` — `src/modules/customer-auth/domain/constants/auth.constants.ts`\n * (`AUTH_ERROR`).\n * - `ACCESS_DENIED` — `AuthorizationException.accessDenied()`, thrown by\n * `customer-addresses.controller.ts` on an address the caller does not own.\n * - `<RESOURCE>_NOT_FOUND` — `ResourceNotFoundException`, whose code is\n * `${resource.toUpperCase()}_NOT_FOUND`. `Address` and `Order` are the two\n * resources the storefront's authenticated routes can produce.\n * - `VALIDATION_FAILED` — `ValidationException`.\n * - `ORDER_NOT_CANCELLABLE` — `ORDER_ERROR.NOT_CANCELLABLE`\n * (`src/modules/orders/domain/constants/order-error.constants.ts`),\n * thrown by `OrderCancelCommandHandler` when a customer tries to cancel\n * an order outside pending/confirmed/processing.\n * - `INSUFFICIENT_INVENTORY`: `InsufficientInventoryException`\n * (`src/modules/inventory/domain/exceptions/`), thrown when an order asks\n * for more of a deny-policy variant than is available.\n * - `ORDER_PROMOTION_NOT_APPLICABLE`: `ORDER_ERROR.PROMOTION_NOT_APPLICABLE`,\n * thrown by `OrderComputationService.applyPromotionCode` when the applied\n * code can no longer be redeemed at placement (expired, used up, the cart\n * changed). `useCheckout` drops the code when it sees this.\n */\nconst ERROR_COPY: Record<string, string> = {\n AUTH_INVALID_CREDENTIALS: \"Email hoặc mật khẩu không đúng.\",\n AUTH_ACCOUNT_LOCKED: \"Quá nhiều lần thử. Vui lòng thử lại sau 15 phút.\",\n AUTH_EMAIL_NOT_VERIFIED: \"Vui lòng xác thực email của bạn trước.\",\n AUTH_METHOD_DISABLED:\n \"Phương thức đăng nhập này không khả dụng cho cửa hàng này.\",\n AUTH_TOKEN_INVALID: \"Mã xác thực không hợp lệ hoặc đã được sử dụng.\",\n AUTH_TOKEN_EXPIRED: \"Mã xác thực đã hết hạn. Vui lòng yêu cầu mã mới.\",\n AUTH_SESSION_EXPIRED: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n AUTH_WEAK_PASSWORD: \"Mật khẩu chưa đáp ứng yêu cầu của cửa hàng.\",\n AUTH_RATE_LIMITED: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n AUTH_STORE_MISMATCH:\n \"Phiên đăng nhập không thuộc cửa hàng này. Vui lòng đăng nhập lại.\",\n AUTH_EMAIL_TAKEN: \"Email này đã được sử dụng.\",\n\n ACCESS_DENIED: \"Bạn không có quyền thực hiện thao tác này.\",\n VALIDATION_FAILED: \"Thông tin chưa hợp lệ. Vui lòng kiểm tra lại.\",\n ADDRESS_NOT_FOUND: \"Không tìm thấy địa chỉ này.\",\n ORDER_NOT_FOUND: \"Không tìm thấy đơn hàng này.\",\n ORDER_NOT_CANCELLABLE: \"Đơn hàng này không thể huỷ được nữa.\",\n INSUFFICIENT_INVENTORY: \"Một số sản phẩm không đủ hàng.\",\n ORDER_PROMOTION_NOT_APPLICABLE:\n \"Mã giảm giá không còn dùng được cho đơn này nên đã được gỡ. Vui lòng kiểm tra lại tổng tiền rồi đặt hàng.\",\n};\n\n/**\n * Nest's built-in `UnauthorizedException` / `ForbiddenException` (thrown by\n * `TenantUserAuthGuard`, `StorefrontApiKeyGuard` and the `@CurrentCustomer`\n * decorator) carry no `code` at all — only a status and English prose. Status\n * is the only stable signal there.\n */\nconst STATUS_COPY: Record<number, string> = {\n 0: \"Không thể kết nối máy chủ. Vui lòng kiểm tra kết nối mạng.\",\n 401: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n 403: \"Bạn không có quyền thực hiện thao tác này.\",\n 404: \"Không tìm thấy dữ liệu yêu cầu.\",\n 429: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n 500: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 502: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 503: \"Máy chủ đang bận. Vui lòng thử lại sau.\",\n 504: \"Máy chủ phản hồi quá lâu. Vui lòng thử lại.\",\n};\n\n/** Maps a backend error code to Vietnamese copy. */\nexport function errorCopy(\n code: string | null | undefined,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n return (code && ERROR_COPY[code]) || fallback;\n}\n\n/**\n * The same mapping for a caught throwable. `ApiClientError` (thrown by the\n * SDK's `unwrap`) carries `code` and `statusCode`; `lib/auth/context.tsx`\n * surfaces `{ message, code }`. Anything else falls through to `fallback`.\n *\n * The caught value's own `message` is deliberately never used: it is either\n * the backend's English prose or an axios internal string.\n */\nexport function errorCopyFor(\n error: unknown,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n if (!error || typeof error !== \"object\") return fallback;\n\n const { code, statusCode } = error as {\n code?: unknown;\n statusCode?: unknown;\n };\n\n if (typeof code === \"string\" && ERROR_COPY[code]) return ERROR_COPY[code];\n if (typeof statusCode === \"number\" && STATUS_COPY[statusCode]) {\n return STATUS_COPY[statusCode];\n }\n\n return fallback;\n}\n"],"mappings":"AAaO,MAAM,qBAAqB;AAyBlC,MAAM,aAAqC;AAAA,EACzC,0BAA0B;AAAA,EAC1B,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EACzB,sBACE;AAAA,EACF,oBAAoB;AAAA,EACpB,oBAAoB;AAAA,EACpB,sBAAsB;AAAA,EACtB,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,qBACE;AAAA,EACF,kBAAkB;AAAA,EAElB,eAAe;AAAA,EACf,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,uBAAuB;AAAA,EACvB,wBAAwB;AAAA,EACxB,gCACE;AACJ;AAQA,MAAM,cAAsC;AAAA,EAC1C,GAAG;AAAA,EACH,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAGO,SAAS,UACd,MACA,WAAmB,oBACX;AACR,SAAQ,QAAQ,WAAW,IAAI,KAAM;AACvC;AAUO,SAAS,aACd,OACA,WAAmB,oBACX;AACR,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,QAAM,EAAE,MAAM,WAAW,IAAI;AAK7B,MAAI,OAAO,SAAS,YAAY,WAAW,IAAI,EAAG,QAAO,WAAW,IAAI;AACxE,MAAI,OAAO,eAAe,YAAY,YAAY,UAAU,GAAG;AAC7D,WAAO,YAAY,UAAU;AAAA,EAC/B;AAEA,SAAO;AACT;","names":[]}
@@ -75,8 +75,8 @@ async function handleAuthRoute(request, storeRef, segments) {
75
75
  if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);
76
76
  const auth = createAuthApi(storeRef, clientIpFrom(request.headers));
77
77
  const hostMapped = isHostMappedRequest(request);
78
- const tokens = readAuthCookies(request.cookies, storeRef);
79
78
  const cookiePath = authCookiePath(storeRef, hostMapped);
79
+ const tokens = readAuthCookies(request.cookies, storeRef, cookiePath);
80
80
  const body = request.method === "POST" ? await request.json().catch(() => ({})) : {};
81
81
  switch (action) {
82
82
  case "config": {
@@ -294,7 +294,7 @@ async function handleAuthRoute(request, storeRef, segments) {
294
294
  const carrierParams = new URL(carrier, publicNextUrl(request).toString()).searchParams;
295
295
  const presentedNonce = carrierParams.get(OAUTH_NONCE_PARAM);
296
296
  const expectedNonce = request.cookies.get(
297
- oauthNonceCookieName(storeRef)
297
+ oauthNonceCookieName(storeRef, cookiePath)
298
298
  )?.value;
299
299
  const nonceMatches = !!presentedNonce && !!expectedNonce && presentedNonce === expectedNonce;
300
300
  if (!code || !nonceMatches) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/route-handlers.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { createAuthApi } from \"./sdk\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { safeRedirectPath } from \"./safe-redirect\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n authCookiePath,\n clearAuthCookies,\n clearOAuthNonceCookie,\n isHostMappedRequest,\n oauthNonceCookieName,\n readAuthCookies,\n writeAuthCookies,\n storeBasePathFor,\n writeOAuthNonceCookie,\n} from \"./cookies\";\nimport type {\n AuthResult,\n ChangeEmailPayload,\n ChangePasswordPayload,\n LoginPayload,\n RegisterPayload,\n ResetPasswordPayload,\n VerifyOtpPayload,\n} from \"@ecomweb/sdk\";\n\n/** Translates the SDK's ApiResponse into a JSON response, preserving the code. */\nfunction fail(status: number, message: string, code?: string) {\n return NextResponse.json(\n { error: { message, code } },\n { status: status || 500 }\n );\n}\n\n/**\n * The HTTP method each action answers on — one entry per action, no defaults.\n *\n * Every one of these used to answer GET as well as POST, and the session\n * cookies are `sameSite: \"lax\"`, which the browser DOES send on a cross-site\n * top-level navigation. A link on any page therefore reached `logout-all`, or\n * `google/complete` with a code of the attacker's choosing. The split is\n * enumerated rather than inferred so that adding an action forces a decision\n * here; an action missing from this map is a 404, not a silent GET.\n *\n * GET is limited to the two reads the client polls (`config`, `session`) and\n * the two halves of the OAuth hand-off: `google/url` is a read, and\n * `google/complete` is the browser's landing spot in a redirect chain, so it\n * cannot be anything else. It carries its own browser binding instead — see\n * the nonce cookie below.\n */\nconst AUTH_ACTION_METHOD = {\n config: \"GET\",\n session: \"GET\",\n \"google/url\": \"GET\",\n \"google/complete\": \"GET\",\n\n register: \"POST\",\n login: \"POST\",\n \"otp/request\": \"POST\",\n \"otp/verify\": \"POST\",\n anonymous: \"POST\",\n logout: \"POST\",\n \"logout-all\": \"POST\",\n \"verify-email\": \"POST\",\n \"resend-verification\": \"POST\",\n \"forgot-password\": \"POST\",\n \"reset-password\": \"POST\",\n \"change-password\": \"POST\",\n \"change-email\": \"POST\",\n \"change-email/confirm\": \"POST\",\n} as const satisfies Record<string, \"GET\" | \"POST\">;\n\ntype AuthAction = keyof typeof AUTH_ACTION_METHOD;\n\n/**\n * The query parameter carrying the OAuth nonce home.\n *\n * `redirect_to` is the only field that survives the round trip through the\n * signed `state` and back out as `next=`, and the backend requires it to be a\n * relative path, so the nonce travels inside it as a query parameter of a\n * path-only URL. The storefront is both the producer and the only consumer of\n * this shape.\n */\nconst OAUTH_NONCE_PARAM = \"sf_oauth\";\nconst OAUTH_NEXT_PARAM = \"next\";\n\n/** Tokens go into cookies and never into the response body. */\nfunction withSession(\n storeRef: string,\n cookiePath: string,\n result: AuthResult,\n body: Record<string, unknown> = {}\n) {\n const response = NextResponse.json({ identity: result.identity, ...body });\n\n if (result.access_token && result.refresh_token) {\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: result.access_token,\n refresh_token: result.refresh_token,\n },\n cookiePath\n );\n }\n\n return response;\n}\n\nfunction methodNotAllowed(allowed: \"GET\" | \"POST\") {\n return NextResponse.json(\n {\n error: {\n message: `This action requires ${allowed}`,\n code: \"METHOD_NOT_ALLOWED\",\n },\n },\n { status: 405, headers: { allow: allowed } }\n );\n}\n\nexport async function handleAuthRoute(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const action = segments.join(\"/\");\n const allowedMethod = AUTH_ACTION_METHOD[action as AuthAction];\n\n if (!allowedMethod) return fail(404, `Unknown auth action: ${action}`);\n if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);\n\n // The shopper's address, not this server's: the backend rate-limits per\n // `storeId:clientIp` and every one of these calls is made server-side.\n const auth = createAuthApi(storeRef, clientIpFrom(request.headers));\n const hostMapped = isHostMappedRequest(request);\n const tokens = readAuthCookies(request.cookies, storeRef);\n const cookiePath = authCookiePath(storeRef, hostMapped);\n\n const body: Record<string, any> =\n request.method === \"POST\" ? await request.json().catch(() => ({})) : {};\n\n switch (action) {\n case \"config\": {\n const res = await auth.getAuthConfig();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"register\": {\n // Never trust a browser-supplied `anonymous_identity_id`: the backend\n // only checks store_id / is_anonymous / !deleted_at, not ownership, so\n // forwarding it would let anyone who learns an anonymous UUID register\n // against it and inherit its cart and orders. Whatever the browser sent\n // is dropped and the id is derived from the httpOnly session instead.\n const payload: Record<string, any> = { ...body };\n delete payload.anonymous_identity_id;\n\n let anonymousIdentityId: string | undefined;\n\n if (tokens) {\n const current = await auth.me(tokens.access_token);\n if (current.success && current.data?.is_anonymous) {\n anonymousIdentityId = current.data.id;\n }\n }\n\n const res = await auth.register({\n ...payload,\n anonymous_identity_id: anonymousIdentityId,\n } as RegisterPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Register never returns tokens, by design.\n return NextResponse.json({ registered: true });\n }\n\n case \"login\": {\n const res = await auth.login(body as LoginPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"otp/request\": {\n const res = await auth.requestOtp(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"otp/verify\": {\n const res = await auth.verifyOtp(body as VerifyOtpPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"anonymous\": {\n const res = await auth.anonymous();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"session\": {\n if (!tokens) return NextResponse.json({ identity: null });\n const res = await auth.me(tokens.access_token);\n if (!res.success) return NextResponse.json({ identity: null });\n return NextResponse.json({ identity: res.data });\n }\n\n case \"logout\": {\n // Best-effort revoke: a failed call must still clear the browser's\n // cookies, or the shopper is stuck logged in against a dead session.\n if (tokens) {\n await auth\n .logout(tokens.access_token, tokens.refresh_token)\n .catch(() => undefined);\n }\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"logout-all\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.logoutAll(tokens.access_token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"verify-email\": {\n const res = await auth.verifyEmail(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"resend-verification\": {\n const res = await auth.resendVerification(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"forgot-password\": {\n const res = await auth.forgotPassword(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"reset-password\": {\n const res = await auth.resetPassword(body as ResetPasswordPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"change-password\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changePassword(\n tokens.access_token,\n body as ChangePasswordPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Changing a password revokes sessions server-side; drop the cookies too.\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"change-email\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changeEmail(\n tokens.access_token,\n body as ChangeEmailPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"change-email/confirm\": {\n const res = await auth.confirmEmailChange(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"google/url\": {\n // Proxied rather than called from the browser so the storefront API key\n // stays server-side.\n const base = storeBasePathFor(request, storeRef);\n const wanted = safeRedirectPath(\n request.nextUrl.searchParams.get(\"redirect_to\"),\n publicNextUrl(request).toString()\n );\n\n // The nonce is minted here, remembered in an httpOnly cookie, and rides\n // out inside `redirect_to`. `google/complete` refuses to issue a session\n // unless the two match, which is what makes that GET unforgeable.\n // `globalThis.crypto` rather than a node:crypto import: this module is\n // bundled for whichever runtime the route runs in.\n const nonce = globalThis.crypto.randomUUID();\n const carrier = new URLSearchParams({\n [OAUTH_NONCE_PARAM]: nonce,\n [OAUTH_NEXT_PARAM]: wanted,\n });\n\n const res = await auth.getGoogleUrl(`${base}/?${carrier.toString()}`);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n\n const response = NextResponse.json(res.data);\n writeOAuthNonceCookie(response, storeRef, nonce, cookiePath);\n return response;\n }\n\n case \"google/complete\": {\n // The backend redirects the BROWSER here with a one-time code. It is\n // redeemed server-side so no token ever reaches the URL bar, history,\n // or a Referer header.\n const base = storeBasePathFor(request, storeRef);\n const errorTarget = new URL(\n `${base}/auth/error?error=oauth_failed`,\n publicNextUrl(request).toString()\n );\n\n const code = request.nextUrl.searchParams.get(\"code\");\n\n // Whatever came back in `next` is the carrier this route wrote in\n // `google/url`: a relative path plus the nonce. Both halves are\n // re-validated — the path against the origin, the nonce against the\n // cookie — before anything is issued.\n const carrier = safeRedirectPath(\n request.nextUrl.searchParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const carrierParams = new URL(carrier, publicNextUrl(request).toString()).searchParams;\n const presentedNonce = carrierParams.get(OAUTH_NONCE_PARAM);\n const expectedNonce = request.cookies.get(\n oauthNonceCookieName(storeRef)\n )?.value;\n\n const nonceMatches =\n !!presentedNonce && !!expectedNonce && presentedNonce === expectedNonce;\n\n if (!code || !nonceMatches) {\n // A missing or mismatched nonce means this browser did not start the\n // flow: someone else's one-time code is being pushed into it. Refuse\n // before any token is exchanged, and burn the nonce either way.\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const res = await auth.exchangeGoogleCode(code);\n\n if (!res.success || !res.data?.access_token || !res.data.refresh_token) {\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const target = safeRedirectPath(\n carrierParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const response = NextResponse.redirect(\n new URL(target === \"/\" ? `${base}/` : target, publicNextUrl(request).toString())\n );\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: res.data.access_token,\n refresh_token: res.data.refresh_token,\n },\n cookiePath\n );\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n\n return response;\n }\n\n default:\n // Unreachable: AUTH_ACTION_METHOD is checked first, and every key it\n // holds has a case above. Kept so adding a key without a case is a\n // 404 rather than an undefined response.\n return fail(404, `Unknown auth action: ${action}`);\n }\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP,SAAS,KAAK,QAAgB,SAAiB,MAAe;AAC5D,SAAO,aAAa;AAAA,IAClB,EAAE,OAAO,EAAE,SAAS,KAAK,EAAE;AAAA,IAC3B,EAAE,QAAQ,UAAU,IAAI;AAAA,EAC1B;AACF;AAkBA,MAAM,qBAAqB;AAAA,EACzB,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,cAAc;AAAA,EACd,mBAAmB;AAAA,EAEnB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,eAAe;AAAA,EACf,cAAc;AAAA,EACd,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,uBAAuB;AAAA,EACvB,mBAAmB;AAAA,EACnB,kBAAkB;AAAA,EAClB,mBAAmB;AAAA,EACnB,gBAAgB;AAAA,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ACA;AAAA,QACA;AAAA,UACE,cAAc,IAAI,KAAK;AAAA,UACvB,eAAe,IAAI,KAAK;AAAA,QAC1B;AAAA,QACA;AAAA,MACF;AACA,4BAAsB,UAAU,UAAU,UAAU;AAEpD,aAAO;AAAA,IACT;AAAA,IAEA;AAIE,aAAO,KAAK,KAAK,wBAAwB,MAAM,EAAE;AAAA,EACrD;AACF;","names":["response"]}
1
+ {"version":3,"sources":["../../src/auth/route-handlers.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { createAuthApi } from \"./sdk\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { safeRedirectPath } from \"./safe-redirect\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n authCookiePath,\n clearAuthCookies,\n clearOAuthNonceCookie,\n isHostMappedRequest,\n oauthNonceCookieName,\n readAuthCookies,\n writeAuthCookies,\n storeBasePathFor,\n writeOAuthNonceCookie,\n} from \"./cookies\";\nimport type {\n AuthResult,\n ChangeEmailPayload,\n ChangePasswordPayload,\n LoginPayload,\n RegisterPayload,\n ResetPasswordPayload,\n VerifyOtpPayload,\n} from \"@ecomweb/sdk\";\n\n/** Translates the SDK's ApiResponse into a JSON response, preserving the code. */\nfunction fail(status: number, message: string, code?: string) {\n return NextResponse.json(\n { error: { message, code } },\n { status: status || 500 }\n );\n}\n\n/**\n * The HTTP method each action answers on — one entry per action, no defaults.\n *\n * Every one of these used to answer GET as well as POST, and the session\n * cookies are `sameSite: \"lax\"`, which the browser DOES send on a cross-site\n * top-level navigation. A link on any page therefore reached `logout-all`, or\n * `google/complete` with a code of the attacker's choosing. The split is\n * enumerated rather than inferred so that adding an action forces a decision\n * here; an action missing from this map is a 404, not a silent GET.\n *\n * GET is limited to the two reads the client polls (`config`, `session`) and\n * the two halves of the OAuth hand-off: `google/url` is a read, and\n * `google/complete` is the browser's landing spot in a redirect chain, so it\n * cannot be anything else. It carries its own browser binding instead — see\n * the nonce cookie below.\n */\nconst AUTH_ACTION_METHOD = {\n config: \"GET\",\n session: \"GET\",\n \"google/url\": \"GET\",\n \"google/complete\": \"GET\",\n\n register: \"POST\",\n login: \"POST\",\n \"otp/request\": \"POST\",\n \"otp/verify\": \"POST\",\n anonymous: \"POST\",\n logout: \"POST\",\n \"logout-all\": \"POST\",\n \"verify-email\": \"POST\",\n \"resend-verification\": \"POST\",\n \"forgot-password\": \"POST\",\n \"reset-password\": \"POST\",\n \"change-password\": \"POST\",\n \"change-email\": \"POST\",\n \"change-email/confirm\": \"POST\",\n} as const satisfies Record<string, \"GET\" | \"POST\">;\n\ntype AuthAction = keyof typeof AUTH_ACTION_METHOD;\n\n/**\n * The query parameter carrying the OAuth nonce home.\n *\n * `redirect_to` is the only field that survives the round trip through the\n * signed `state` and back out as `next=`, and the backend requires it to be a\n * relative path, so the nonce travels inside it as a query parameter of a\n * path-only URL. The storefront is both the producer and the only consumer of\n * this shape.\n */\nconst OAUTH_NONCE_PARAM = \"sf_oauth\";\nconst OAUTH_NEXT_PARAM = \"next\";\n\n/** Tokens go into cookies and never into the response body. */\nfunction withSession(\n storeRef: string,\n cookiePath: string,\n result: AuthResult,\n body: Record<string, unknown> = {}\n) {\n const response = NextResponse.json({ identity: result.identity, ...body });\n\n if (result.access_token && result.refresh_token) {\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: result.access_token,\n refresh_token: result.refresh_token,\n },\n cookiePath\n );\n }\n\n return response;\n}\n\nfunction methodNotAllowed(allowed: \"GET\" | \"POST\") {\n return NextResponse.json(\n {\n error: {\n message: `This action requires ${allowed}`,\n code: \"METHOD_NOT_ALLOWED\",\n },\n },\n { status: 405, headers: { allow: allowed } }\n );\n}\n\nexport async function handleAuthRoute(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const action = segments.join(\"/\");\n const allowedMethod = AUTH_ACTION_METHOD[action as AuthAction];\n\n if (!allowedMethod) return fail(404, `Unknown auth action: ${action}`);\n if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);\n\n // The shopper's address, not this server's: the backend rate-limits per\n // `storeId:clientIp` and every one of these calls is made server-side.\n const auth = createAuthApi(storeRef, clientIpFrom(request.headers));\n const hostMapped = isHostMappedRequest(request);\n const cookiePath = authCookiePath(storeRef, hostMapped);\n const tokens = readAuthCookies(request.cookies, storeRef, cookiePath);\n\n const body: Record<string, any> =\n request.method === \"POST\" ? await request.json().catch(() => ({})) : {};\n\n switch (action) {\n case \"config\": {\n const res = await auth.getAuthConfig();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"register\": {\n // Never trust a browser-supplied `anonymous_identity_id`: the backend\n // only checks store_id / is_anonymous / !deleted_at, not ownership, so\n // forwarding it would let anyone who learns an anonymous UUID register\n // against it and inherit its cart and orders. Whatever the browser sent\n // is dropped and the id is derived from the httpOnly session instead.\n const payload: Record<string, any> = { ...body };\n delete payload.anonymous_identity_id;\n\n let anonymousIdentityId: string | undefined;\n\n if (tokens) {\n const current = await auth.me(tokens.access_token);\n if (current.success && current.data?.is_anonymous) {\n anonymousIdentityId = current.data.id;\n }\n }\n\n const res = await auth.register({\n ...payload,\n anonymous_identity_id: anonymousIdentityId,\n } as RegisterPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Register never returns tokens, by design.\n return NextResponse.json({ registered: true });\n }\n\n case \"login\": {\n const res = await auth.login(body as LoginPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"otp/request\": {\n const res = await auth.requestOtp(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"otp/verify\": {\n const res = await auth.verifyOtp(body as VerifyOtpPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"anonymous\": {\n const res = await auth.anonymous();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"session\": {\n if (!tokens) return NextResponse.json({ identity: null });\n const res = await auth.me(tokens.access_token);\n if (!res.success) return NextResponse.json({ identity: null });\n return NextResponse.json({ identity: res.data });\n }\n\n case \"logout\": {\n // Best-effort revoke: a failed call must still clear the browser's\n // cookies, or the shopper is stuck logged in against a dead session.\n if (tokens) {\n await auth\n .logout(tokens.access_token, tokens.refresh_token)\n .catch(() => undefined);\n }\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"logout-all\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.logoutAll(tokens.access_token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"verify-email\": {\n const res = await auth.verifyEmail(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"resend-verification\": {\n const res = await auth.resendVerification(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"forgot-password\": {\n const res = await auth.forgotPassword(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"reset-password\": {\n const res = await auth.resetPassword(body as ResetPasswordPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"change-password\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changePassword(\n tokens.access_token,\n body as ChangePasswordPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Changing a password revokes sessions server-side; drop the cookies too.\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"change-email\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changeEmail(\n tokens.access_token,\n body as ChangeEmailPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"change-email/confirm\": {\n const res = await auth.confirmEmailChange(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"google/url\": {\n // Proxied rather than called from the browser so the storefront API key\n // stays server-side.\n const base = storeBasePathFor(request, storeRef);\n const wanted = safeRedirectPath(\n request.nextUrl.searchParams.get(\"redirect_to\"),\n publicNextUrl(request).toString()\n );\n\n // The nonce is minted here, remembered in an httpOnly cookie, and rides\n // out inside `redirect_to`. `google/complete` refuses to issue a session\n // unless the two match, which is what makes that GET unforgeable.\n // `globalThis.crypto` rather than a node:crypto import: this module is\n // bundled for whichever runtime the route runs in.\n const nonce = globalThis.crypto.randomUUID();\n const carrier = new URLSearchParams({\n [OAUTH_NONCE_PARAM]: nonce,\n [OAUTH_NEXT_PARAM]: wanted,\n });\n\n const res = await auth.getGoogleUrl(`${base}/?${carrier.toString()}`);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n\n const response = NextResponse.json(res.data);\n writeOAuthNonceCookie(response, storeRef, nonce, cookiePath);\n return response;\n }\n\n case \"google/complete\": {\n // The backend redirects the BROWSER here with a one-time code. It is\n // redeemed server-side so no token ever reaches the URL bar, history,\n // or a Referer header.\n const base = storeBasePathFor(request, storeRef);\n const errorTarget = new URL(\n `${base}/auth/error?error=oauth_failed`,\n publicNextUrl(request).toString()\n );\n\n const code = request.nextUrl.searchParams.get(\"code\");\n\n // Whatever came back in `next` is the carrier this route wrote in\n // `google/url`: a relative path plus the nonce. Both halves are\n // re-validated — the path against the origin, the nonce against the\n // cookie — before anything is issued.\n const carrier = safeRedirectPath(\n request.nextUrl.searchParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const carrierParams = new URL(carrier, publicNextUrl(request).toString()).searchParams;\n const presentedNonce = carrierParams.get(OAUTH_NONCE_PARAM);\n const expectedNonce = request.cookies.get(\n oauthNonceCookieName(storeRef, cookiePath)\n )?.value;\n\n const nonceMatches =\n !!presentedNonce && !!expectedNonce && presentedNonce === expectedNonce;\n\n if (!code || !nonceMatches) {\n // A missing or mismatched nonce means this browser did not start the\n // flow: someone else's one-time code is being pushed into it. Refuse\n // before any token is exchanged, and burn the nonce either way.\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const res = await auth.exchangeGoogleCode(code);\n\n if (!res.success || !res.data?.access_token || !res.data.refresh_token) {\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const target = safeRedirectPath(\n carrierParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const response = NextResponse.redirect(\n new URL(target === \"/\" ? `${base}/` : target, publicNextUrl(request).toString())\n );\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: res.data.access_token,\n refresh_token: res.data.refresh_token,\n },\n cookiePath\n );\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n\n return response;\n }\n\n default:\n // Unreachable: AUTH_ACTION_METHOD is checked first, and every key it\n // holds has a case above. Kept so adding a key without a case is a\n // 404 rather than an undefined response.\n return fail(404, `Unknown auth action: ${action}`);\n }\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B;AAA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AAiB,mBAAmB;AAE5D,UAAI,CAAC,QAAQ,CAAC,cAAc;AAI1B,cAAMA,YAAW,aAAa,SAAS,WAAW;AAClD,8BAAsBA,WAAU,UAAU,UAAU;AACpD,eAAOA;AAAA,MACT;AAEA,YAAM,MAAM,MAAM,KAAK,mBAAmB,IAAI;AAE9C,UAAI,CAAC,IAAI,WAAW,CAAC,IAAI,MAAM,gBAAgB,CAAC,IAAI,KAAK,eAAe;AACtE,cAAMA,YAAW,aAAa,SAAS,WAAW;AAClD,8BAAsBA,WAAU,UAAU,UAAU;AACpD,eAAOA;AAAA,MACT;AAEA,YAAM,SAAS;AAAA,QACb,cAAc,IAAI,gBAAgB;AAAA,QAClC,cAAc,OAAO,EAAE,SAAS;AAAA,MAClC;AACA,YAAM,WAAW,aAAa;AAAA,QAC5B,IAAI,IAAI,WAAW,MAAM,GAAG,IAAI,MAAM,QAAQ,cAAc,OAAO,EAAE,SAAS,CAAC;AAAA,MACjF;AAEA;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,UACE,cAAc,IAAI,KAAK;AAAA,UACvB,eAAe,IAAI,KAAK;AAAA,QAC1B;AAAA,QACA;AAAA,MACF;AACA,4BAAsB,UAAU,UAAU,UAAU;AAEpD,aAAO;AAAA,IACT;AAAA,IAEA;AAIE,aAAO,KAAK,KAAK,wBAAwB,MAAM,EAAE;AAAA,EACrD;AACF;","names":["response"]}
@@ -1,11 +1,13 @@
1
1
  import {
2
2
  accessCookieName,
3
+ authCookiePath,
3
4
  refreshCookieName,
4
5
  HOST_MAPPED_HEADER
5
6
  } from "./cookies.js";
6
7
  import { forwardedForHeader } from "./client-ip.js";
7
8
  import { publicConfig } from "../config/public.js";
8
9
  import { serverConfig } from "../config/server.js";
10
+ import { THEME_PREVIEW_HOST_HEADER } from "../theme/preview-host.js";
9
11
  const REFRESH_WINDOW_SECONDS = 120;
10
12
  const REFRESH_FETCH_TIMEOUT_MS = 2500;
11
13
  function expiresWithin(token, seconds) {
@@ -19,9 +21,11 @@ function expiresWithin(token, seconds) {
19
21
  return false;
20
22
  }
21
23
  }
22
- async function refreshIfNearExpiry(req, storeRef) {
23
- const access = req.cookies.get(accessCookieName(storeRef))?.value;
24
- const refresh = req.cookies.get(refreshCookieName(storeRef))?.value;
24
+ async function refreshIfNearExpiry(req, storeRef, cookiePath) {
25
+ const access = req.cookies.get(accessCookieName(storeRef, cookiePath))?.value;
26
+ const refresh = req.cookies.get(
27
+ refreshCookieName(storeRef, cookiePath)
28
+ )?.value;
25
29
  if (!access || !refresh) return null;
26
30
  if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;
27
31
  try {
@@ -62,10 +66,12 @@ async function refreshIfNearExpiry(req, storeRef) {
62
66
  function downstreamRequestHeaders(req, hostMapped, storeRef, rotated) {
63
67
  const headers = new Headers(req.headers);
64
68
  headers.set(HOST_MAPPED_HEADER, hostMapped ? "1" : "0");
69
+ headers.delete(THEME_PREVIEW_HOST_HEADER);
65
70
  if (rotated && storeRef) {
66
71
  const jar = new Map(req.cookies.getAll().map((c) => [c.name, c.value]));
67
- jar.set(accessCookieName(storeRef), rotated.access_token);
68
- jar.set(refreshCookieName(storeRef), rotated.refresh_token);
72
+ const path = authCookiePath(storeRef, hostMapped);
73
+ jar.set(accessCookieName(storeRef, path), rotated.access_token);
74
+ jar.set(refreshCookieName(storeRef, path), rotated.refresh_token);
69
75
  headers.set(
70
76
  "cookie",
71
77
  [...jar].map(([name, value]) => `${name}=${value}`).join("; ")
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/session-refresh.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\nimport {\n accessCookieName,\n refreshCookieName,\n HOST_MAPPED_HEADER,\n} from \"./cookies\";\nimport { forwardedForHeader } from \"./client-ip\";\nimport { publicConfig } from \"../config/public\";\nimport { serverConfig } from \"../config/server\";\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 */\nexport async function refreshIfNearExpiry(\n req: NextRequest,\n storeRef: string\n): Promise<RotatedTokens | null> {\n const access = req.cookies.get(accessCookieName(storeRef))?.value;\n const refresh = req.cookies.get(refreshCookieName(storeRef))?.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\n if (rotated && storeRef) {\n const jar = new Map(req.cookies.getAll().map(c => [c.name, c.value]));\n jar.set(accessCookieName(storeRef), rotated.access_token);\n jar.set(refreshCookieName(storeRef), 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,OACK;AACP,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAQ7B,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AAY1B,SAAS,cAAc,OAAe,SAA0B;AACrE,MAAI;AACF,UAAM,UAAU,KA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AAM,UAAU,IAAI,QAAQ,IAAI,OAAO;AACvC,UAAQ,IAAI,oBAAoB,aAAa,MAAM,GAAG;AAEtD,MAAI,WAAW,UAAU;AACvB,UAAM,MAAM,IAAI,IAAI,IAAI,QAAQ,OAAO,EAAE,IAAI,OAAK,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AACpE,QAAI,IAAI,iBAAiB,QAAQ,GAAG,QAAQ,YAAY;AACxD,QAAI,IAAI,kBAAkB,QAAQ,GAAG,QAAQ,aAAa;AAC1D,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 { serverConfig } from \"../config/server\";\nimport { THEME_PREVIEW_HOST_HEADER } from \"../theme/preview-host\";\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\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,oBAAoB;AAC7B,SAAS,iCAAiC;AAQ1C,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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