@ecomweb/storefront-kit 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +25 -1
  2. package/bin/check-client-bundle-lib.d.mts +16 -0
  3. package/bin/check-client-bundle-lib.mjs +58 -0
  4. package/bin/check-client-bundle.d.mts +11 -0
  5. package/bin/check-client-bundle.mjs +8 -0
  6. package/dist/api/client.js +39 -0
  7. package/dist/api/client.js.map +1 -1
  8. package/dist/api/index.js.map +1 -1
  9. package/dist/api/proxy-guard.js +29 -0
  10. package/dist/api/proxy-guard.js.map +1 -0
  11. package/dist/api/proxy-routes.js +126 -0
  12. package/dist/api/proxy-routes.js.map +1 -0
  13. package/dist/api/proxy.js +17 -4
  14. package/dist/api/proxy.js.map +1 -1
  15. package/dist/api/server-sdk.js +41 -0
  16. package/dist/api/server-sdk.js.map +1 -0
  17. package/dist/api/store-preview-header.js.map +1 -1
  18. package/dist/auth/sdk.js +15 -5
  19. package/dist/auth/sdk.js.map +1 -1
  20. package/dist/auth/session-refresh.js +7 -4
  21. package/dist/auth/session-refresh.js.map +1 -1
  22. package/dist/cart/api.js.map +1 -1
  23. package/dist/checkout/get-payment-state.js +4 -8
  24. package/dist/checkout/get-payment-state.js.map +1 -1
  25. package/dist/checkout/initiate-gateway-payment.js +5 -7
  26. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  27. package/dist/checkout/order-handoff.js.map +1 -1
  28. package/dist/checkout/payment-redirect.js.map +1 -1
  29. package/dist/client-info.js +1 -1
  30. package/dist/config/public.js +2 -0
  31. package/dist/config/public.js.map +1 -1
  32. package/dist/config/schema.js +16 -4
  33. package/dist/config/schema.js.map +1 -1
  34. package/dist/config/secret-guard.js +20 -0
  35. package/dist/config/secret-guard.js.map +1 -0
  36. package/dist/config/server.js +15 -8
  37. package/dist/config/server.js.map +1 -1
  38. package/dist/config.d.ts +14 -4
  39. package/dist/config.js +2 -0
  40. package/dist/config.js.map +1 -1
  41. package/dist/index.d.ts +25 -68
  42. package/dist/index.js.map +1 -1
  43. package/dist/middleware/create-storefront-middleware.js +14 -3
  44. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  45. package/dist/middleware.d.ts +2 -2
  46. package/dist/{mode-DXo-EhTJ.d.ts → mode-oVZCQxrc.d.ts} +1 -1
  47. package/dist/orders/api-client.js +3 -3
  48. package/dist/orders/api-client.js.map +1 -1
  49. package/dist/orders/bank-transfer.js +1 -1
  50. package/dist/orders/bank-transfer.js.map +1 -1
  51. package/dist/orders/use-order-status.js +2 -2
  52. package/dist/orders/use-order-status.js.map +1 -1
  53. package/dist/promotions/use-promotion-validation.js +2 -2
  54. package/dist/promotions/use-promotion-validation.js.map +1 -1
  55. package/dist/request/served-store.js +5 -0
  56. package/dist/request/served-store.js.map +1 -0
  57. package/dist/{schema-DIF0CZNV.d.ts → schema-B3nAYiwT.d.ts} +1 -1
  58. package/dist/sdk.js +3 -3
  59. package/dist/sdk.js.map +1 -1
  60. package/dist/server/routes.js +16 -9
  61. package/dist/server/routes.js.map +1 -1
  62. package/dist/server.d.ts +38 -5
  63. package/dist/server.js +2 -0
  64. package/dist/server.js.map +1 -1
  65. package/dist/shipping/use-shipping-calculation.js +2 -2
  66. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  67. package/package.json +6 -2
  68. package/dist/api/server-client.js +0 -162
  69. package/dist/api/server-client.js.map +0 -1
package/README.md CHANGED
@@ -11,7 +11,7 @@ pnpm add @ecomweb/storefront-kit @ecomweb/sdk
11
11
  | Entry | Use it from | Main exports |
12
12
  |---|---|---|
13
13
  | `@ecomweb/storefront-kit` | client and server components | `StorefrontKitProvider`, `useAuth`, `useCart`, `useCheckout`, `useOrderStatus`, `useOrderLookup`, `storePath`, `storeApiPath`, `metafield`, `metaobjectField`, `getMetaobjects`, `getMetaobject`, `RichText`, `isStoreComingSoonError`, `comingSoonStoreNameOf`, `comingSoonStoreMetadata`, `STORE_COMING_SOON_REDIRECT_PATH` |
14
- | `@ecomweb/storefront-kit/server` | route handlers, server components | `createAuthRoutes`, `createBackendProxy`, `requireSession`, `serverConfig`, `resolveRootStoreRef`, `resolveComingSoonStore`, `readStorePreviewToken` |
14
+ | `@ecomweb/storefront-kit/server` | route handlers, server components | `createAuthRoutes`, `createBackendProxy`, `getServerSdk`, `requireSession`, `serverConfig`, `resolveRootStoreRef`, `resolveComingSoonStore`, `readStorePreviewToken` |
15
15
  | `@ecomweb/storefront-kit/middleware` | `proxy.ts` | `createStorefrontMiddleware`, `storefrontMiddlewareConfig` |
16
16
  | `@ecomweb/storefront-kit/config` | anywhere | `publicConfig`, `parsePublicConfig`, `resolveMode` |
17
17
 
@@ -48,6 +48,30 @@ Wrap the store layout in `<StorefrontKitProvider store={store} onNotice={…}>`;
48
48
  toasts. `useCheckout().placeOrder()` returns `redirect`, `redirect_failed`,
49
49
  `success`, `stock_issues`, `error`, `quote_changed` or `busy`, and your page decides what to show.
50
50
 
51
+ ## Secret keys and the proxy
52
+
53
+ Needs kit 0.15.0. Carts, checkout, orders and accounts need a storefront
54
+ **secret key**, set in the server environment only: `PLATFORM_SECRET_KEY`
55
+ (shared app) or `ECOMWEB_SECRET_KEY` (one store). The browser key stays
56
+ `NEXT_PUBLIC_PLATFORM_API_KEY` / `ECOMWEB_PUBLISHABLE_KEY`. Server-side
57
+ `PLATFORM_API_KEY` is retired. `next build` needs no secret.
58
+
59
+ - `createStoreSdk(storeRef)` (browser): public calls go direct; private calls
60
+ go to the same-origin proxy, which holds the secret.
61
+ - `getServerSdk()` (`/server`): the server SDK signed with the secret key, for
62
+ server components and route handlers. Shopper-side methods on it fail with
63
+ `SDK_SHOPPER_CALL_ON_SERVER`.
64
+ - `createBackendProxy()` forwards only routes listed in
65
+ `PROXIED_STOREFRONT_ROUTES`, only for the store it serves, only for
66
+ same-origin callers; everything else is `404 NOT_FOUND`. Same checks on
67
+ `createAuthRoutes()`.
68
+ - Any `sk_` value in a `NEXT_PUBLIC_*` variable fails the build and the boot.
69
+ - Run `ecomweb-check-client-bundle` after `next build` (`"build": "next build
70
+ && ecomweb-check-client-bundle"`): it fails the build if a secret ended up
71
+ in the client output.
72
+
73
+ See [docs/storefront-keys.md](../../docs/storefront-keys.md).
74
+
51
75
  ## Coming soon stores and store previews
52
76
 
53
77
  Needs kit 0.11.0. Until the merchant opens a store, the API answers every
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Scans a Next.js build output for secrets that reached client code.
3
+ *
4
+ * @param nextDir - the `.next` directory
5
+ * @param env - environment to match exact secret values from
6
+ * @returns one `"<relative file>: <what matched>"` line per hit; never the value
7
+ */
8
+ export function findSecretsInClientBundle(
9
+ nextDir: string,
10
+ env: Record<string, string | undefined>,
11
+ ): string[];
12
+
13
+ /**
14
+ * CLI body: checks `argv[0]` (default `.next`) and exits 1 on a hit or a missing directory.
15
+ */
16
+ export function main(argv?: string[], env?: Record<string, string | undefined>): void;
@@ -0,0 +1,58 @@
1
+ // Logic of ecomweb-check-client-bundle (the bin is a thin entry).
2
+ // Fails a build when a secret key reached client code: scans
3
+ // <nextDir>/static/**/*.js and <nextDir>/server/app/**/*.{html,rsc,body}.
4
+ // Reports file paths and which pattern/env var matched, never the value.
5
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
6
+ import { join, relative, resolve } from "node:path";
7
+
8
+ const KEY_SHAPE = /sk_(storefront|platform|live)_[A-Za-z0-9]{16,}/;
9
+ // Shorter values would match unrelated text; real secrets are far longer.
10
+ const MIN_VALUE_LENGTH = 8;
11
+ const SECRET_ENV_NAMES = ["ECOMWEB_SECRET_KEY", "PLATFORM_SECRET_KEY", "CLIENT_IP_FORWARDER_SECRET"];
12
+
13
+ function walk(dir, accept, out = []) {
14
+ if (!existsSync(dir)) return out;
15
+ for (const name of readdirSync(dir)) {
16
+ const full = join(dir, name);
17
+ const st = statSync(full);
18
+ if (st.isDirectory()) walk(full, accept, out);
19
+ else if (accept(name)) out.push(full);
20
+ }
21
+ return out;
22
+ }
23
+
24
+ /** @returns {string[]} "<relative file>: <what>" per hit, never the secret itself. */
25
+ export function findSecretsInClientBundle(nextDir, env) {
26
+ const files = [
27
+ ...walk(join(nextDir, "static"), (n) => /\.(js|map|json)$/.test(n)),
28
+ ...walk(join(nextDir, "server", "app"), (n) => /\.(html|rsc|body|meta)$/.test(n)),
29
+ ];
30
+ const hits = [];
31
+ for (const file of files) {
32
+ const text = readFileSync(file, "utf8");
33
+ const rel = relative(nextDir, file).split("\\").join("/");
34
+ if (KEY_SHAPE.test(text)) hits.push(`${rel}: an sk_storefront_/sk_live_/sk_platform_ key`);
35
+ for (const name of SECRET_ENV_NAMES) {
36
+ const value = env[name];
37
+ if (value && value.length >= MIN_VALUE_LENGTH && text.includes(value)) hits.push(`${rel}: the value of ${name}`);
38
+ }
39
+ }
40
+ return hits;
41
+ }
42
+
43
+
44
+ /** Runs the check; exits 1 on a hit or a missing nextDir. */
45
+ export function main(argv = process.argv.slice(2), env = process.env) {
46
+ const nextDir = resolve(argv[0] ?? ".next");
47
+ if (!existsSync(nextDir)) {
48
+ console.error(`ecomweb-check-client-bundle: ${nextDir} not found; run next build first`);
49
+ process.exit(1);
50
+ }
51
+ const hits = findSecretsInClientBundle(nextDir, env);
52
+ if (hits.length > 0) {
53
+ console.error("ecomweb-check-client-bundle: a secret reached client code:");
54
+ for (const hit of hits) console.error(` ${hit}`);
55
+ process.exit(1);
56
+ }
57
+ console.log("ecomweb-check-client-bundle: no secret found in the client bundle");
58
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Scans a Next.js build output for secrets that reached client code.
3
+ *
4
+ * @param nextDir - the `.next` directory
5
+ * @param env - environment to match exact secret values from
6
+ * @returns one `"<relative file>: <what matched>"` line per hit; never the value
7
+ */
8
+ export function findSecretsInClientBundle(
9
+ nextDir: string,
10
+ env: Record<string, string | undefined>,
11
+ ): string[];
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // ecomweb-check-client-bundle [nextDir=.next]
3
+ // Unguarded entry: invoking it always runs the check (no argv/realpath test
4
+ // that could turn the build gate into a silent no-op).
5
+ import { main } from "./check-client-bundle-lib.mjs";
6
+
7
+ export { findSecretsInClientBundle } from "./check-client-bundle-lib.mjs";
8
+ main();
@@ -18,6 +18,7 @@ import {
18
18
  } from "./store-preview-header.js";
19
19
  import { publicConfig } from "../config.js";
20
20
  import { storeApiPath } from "../store-scope/index.js";
21
+ import { findPrivateStorefrontRoute } from "./proxy-routes.js";
21
22
  const DEFAULT_TIMEOUT = 1e4;
22
23
  function comingSoonEndsThisVisit(method) {
23
24
  if (!isBrowserStorePreview()) return true;
@@ -25,6 +26,8 @@ function comingSoonEndsThisVisit(method) {
25
26
  if (verb !== "GET" && verb !== "HEAD") return false;
26
27
  return !requestStorePreviewRenewal();
27
28
  }
29
+ const PRIVATE_ROUTE_MESSAGE = "This route needs the storefront's secret key: call it with createStoreSdk(storeRef) in the browser or getServerSdk() on the server";
30
+ const reportedPrivateRoutes = /* @__PURE__ */ new Set();
28
31
  class ApiClient {
29
32
  axiosInstance;
30
33
  withApiKey;
@@ -125,7 +128,35 @@ class ApiClient {
125
128
  }
126
129
  };
127
130
  }
131
+ /**
132
+ * The direct, publishable-key client cannot call a private route: the API
133
+ * would refuse it, so refuse here, before the network. Logs the matched
134
+ * route pattern, never the raw path (it can carry a review token or an
135
+ * order code).
136
+ */
137
+ refusePrivateRoute(method, url) {
138
+ if (!this.withApiKey) return null;
139
+ const route = findPrivateStorefrontRoute(method, url);
140
+ if (!route) return null;
141
+ const label = `${route.method} ${route.path}`;
142
+ if (!reportedPrivateRoutes.has(label)) {
143
+ reportedPrivateRoutes.add(label);
144
+ console.error(
145
+ `STOREFRONT_PRIVATE_ROUTE: ${label}. ${PRIVATE_ROUTE_MESSAGE}`
146
+ );
147
+ }
148
+ return {
149
+ success: false,
150
+ error: {
151
+ message: PRIVATE_ROUTE_MESSAGE,
152
+ statusCode: 0,
153
+ error: "STOREFRONT_PRIVATE_ROUTE"
154
+ }
155
+ };
156
+ }
128
157
  async get(url, config) {
158
+ const refused = this.refusePrivateRoute("GET", url);
159
+ if (refused) return refused;
129
160
  try {
130
161
  const response = await this.axiosInstance.get(url, config);
131
162
  return this.handleResponse(response);
@@ -134,6 +165,8 @@ class ApiClient {
134
165
  }
135
166
  }
136
167
  async post(url, data, config) {
168
+ const refused = this.refusePrivateRoute("POST", url);
169
+ if (refused) return refused;
137
170
  try {
138
171
  const response = await this.axiosInstance.post(url, data, config);
139
172
  return this.handleResponse(response);
@@ -142,6 +175,8 @@ class ApiClient {
142
175
  }
143
176
  }
144
177
  async put(url, data, config) {
178
+ const refused = this.refusePrivateRoute("PUT", url);
179
+ if (refused) return refused;
145
180
  try {
146
181
  const response = await this.axiosInstance.put(url, data, config);
147
182
  return this.handleResponse(response);
@@ -150,6 +185,8 @@ class ApiClient {
150
185
  }
151
186
  }
152
187
  async patch(url, data, config) {
188
+ const refused = this.refusePrivateRoute("PATCH", url);
189
+ if (refused) return refused;
153
190
  try {
154
191
  const response = await this.axiosInstance.patch(url, data, config);
155
192
  return this.handleResponse(response);
@@ -158,6 +195,8 @@ class ApiClient {
158
195
  }
159
196
  }
160
197
  async delete(url, config) {
198
+ const refused = this.refusePrivateRoute("DELETE", url);
199
+ if (refused) return refused;
161
200
  try {
162
201
  const response = await this.axiosInstance.delete(url, config);
163
202
  return this.handleResponse(response);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/client.ts"],"sourcesContent":["import axios, {\n AxiosInstance,\n AxiosRequestConfig,\n AxiosResponse,\n AxiosError,\n} from \"axios\";\nimport { ApiResponse, AuthenticatedApiClient } from \"../interfaces\";\nimport {\n isStoreSuspendedResponseBody,\n STORE_SUSPENDED_REDIRECT_PATH,\n} from \"../stores/store-suspension\";\nimport {\n isStoreComingSoonResponseBody,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"../stores/store-coming-soon\";\nimport {\n skipsStorePreview,\n STORE_PREVIEW_HEADER,\n} from \"../stores/store-preview-cookie\";\nimport {\n currentStorePreviewToken,\n isBrowserStorePreview,\n requestStorePreviewRenewal,\n} from \"./store-preview-header\";\nimport { publicConfig } from \"../config\";\nimport { storeApiPath } from \"../store-scope\";\n\nconst DEFAULT_TIMEOUT = 10000; // 10 seconds\n\n/**\n * Whether a browser call's STORE_COMING_SOON 403 ends this visit, so the\n * browser goes to the coming soon page.\n * - Not previewing: yes, the store is closed to this shopper.\n * - Previewing, a write: no. A preview is read-only (the API opens GET and\n * HEAD only), so the write was refused, not the preview; the caller\n * reports it.\n * - Previewing, a read: the token ran out. A preview host renews it\n * (`requestStorePreviewRenewal`), so the preview goes on; a link\n * preview has no renewer, and its preview is over.\n */\nfunction comingSoonEndsThisVisit(method: string | undefined): boolean {\n if (!isBrowserStorePreview()) return true;\n const verb = (method ?? \"get\").toUpperCase();\n if (verb !== \"GET\" && verb !== \"HEAD\") return false;\n return !requestStorePreviewRenewal();\n}\n\ninterface ApiClientOptions {\n /**\n * Send `x-storefront-api-key` from the browser. True for direct calls to the\n * backend's own origin; false for calls routed through the same-origin proxy\n * (`lib/api/proxy.ts`), which attaches the key server-side.\n */\n withApiKey?: boolean;\n timeout?: number;\n}\n\nclass ApiClient implements AuthenticatedApiClient {\n private axiosInstance: AxiosInstance;\n private withApiKey: boolean;\n\n constructor(\n baseUrl: string = publicConfig().apiUrl,\n options?: ApiClientOptions\n ) {\n this.withApiKey = options?.withApiKey ?? true;\n\n const defaultHeaders: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n const platformApiKey = publicConfig().storefrontApiKey;\n if (this.withApiKey && platformApiKey) {\n defaultHeaders[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n this.axiosInstance = axios.create({\n baseURL: baseUrl.replace(/\\/$/, \"\"), // Remove trailing slash\n timeout: options?.timeout ?? DEFAULT_TIMEOUT,\n headers: defaultHeaders,\n });\n\n this.setupInterceptors();\n }\n\n private setupInterceptors(): void {\n // Request interceptor - add platform API key\n this.axiosInstance.interceptors.request.use(\n async config => {\n // Ensure API key is always present (in case instance was created before env loaded)\n const platformApiKey = publicConfig().storefrontApiKey;\n if (\n this.withApiKey &&\n platformApiKey &&\n !config.headers[\"x-storefront-api-key\"]\n ) {\n config.headers[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n // Opens a coming soon store for a previewer (read-only on the API's\n // side). An explicit header wins, such as the token the middleware\n // passes to `getByDomain`, and a call carrying SKIP_STORE_PREVIEW (a\n // plain, cached host lookup) never gets the request's token.\n // `get`/`set` match the header name case-insensitively.\n const previewToken = await currentStorePreviewToken();\n if (\n previewToken &&\n !skipsStorePreview(config) &&\n !config.headers.get(STORE_PREVIEW_HEADER)\n ) {\n config.headers.set(STORE_PREVIEW_HEADER, previewToken);\n }\n\n // No Authorization header is ever set here. Session tokens live in\n // httpOnly, store-scoped cookies (lib/auth/cookies.ts) that browser JS\n // cannot read; authenticated calls go through the same-origin proxy\n // built by createStoreApiClient() below, which attaches the bearer\n // token server-side.\n return config;\n },\n error => {\n return Promise.reject(error);\n }\n );\n\n // Response interceptor - handle common errors and format responses\n this.axiosInstance.interceptors.response.use(\n (response: AxiosResponse) => {\n // Success response\n return response;\n },\n (error: AxiosError) => {\n // Never the error itself: its config carries the request headers,\n // the preview token and the API key among them.\n console.error(\"API Client Error:\", {\n method: error.config?.method?.toUpperCase(),\n url: error.config?.url,\n status: error.response?.status,\n code:\n (error.response?.data as { code?: unknown } | undefined)?.code ??\n error.code,\n });\n // Handle common error scenarios\n if (error.code === \"ECONNABORTED\") {\n // Timeout error\n error.message = \"Request timeout - please try again\";\n } else if (!error.response) {\n // Network error\n error.message = \"Network error - check your connection\";\n }\n\n // A platform admin suspended this store mid-session. The initial\n // page render already handles suspension at store-resolution time\n // (app/store/[storeRef]/layout.tsx, proxy.ts) — but a client-side\n // call *after* that render (add-to-cart, checkout, a review\n // submission) hits this same guarded backend independently, and\n // isn't covered by that one-time check. Only the browser can\n // navigate on it; server-side callers still just get the rejection.\n if (\n typeof window !== \"undefined\" &&\n error.response?.status === 403 &&\n isStoreSuspendedResponseBody(error.response?.data)\n ) {\n window.location.href = STORE_SUSPENDED_REDIRECT_PATH;\n }\n\n // Likewise, the store went (or still is) coming soon. Not from the\n // coming soon page itself, so a call made there cannot reload it in\n // a loop. It is always this root path in the browser: the\n // middleware rewrites to it without changing the URL, and the shared\n // path-based host has no such page (known limitation,\n // create-storefront-middleware.ts).\n if (\n typeof window !== \"undefined\" &&\n error.response?.status === 403 &&\n isStoreComingSoonResponseBody(error.response?.data) &&\n window.location.pathname !== STORE_COMING_SOON_REDIRECT_PATH &&\n comingSoonEndsThisVisit(error.config?.method)\n ) {\n window.location.href = STORE_COMING_SOON_REDIRECT_PATH;\n }\n\n return Promise.reject(error);\n }\n );\n }\n\n private handleResponse<T>(response: AxiosResponse<T>): ApiResponse<T> {\n return {\n success: true,\n data: response.data,\n };\n }\n\n private handleError(error: any): ApiResponse<never> {\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError<any>;\n const responseData = axiosError.response?.data || {};\n return {\n success: false,\n error: {\n message:\n responseData.message || axiosError.message || \"Request failed\",\n statusCode: axiosError.response?.status || 0,\n // The backend serialises business errors as\n // `{ code, message, details, timestamp }`, so the stable identifier\n // lands in `code` — this is the browser-side twin of the same read\n // in `lib/auth/sdk.ts`. `unwrap()` copies it onto\n // `ApiClientError.code`, which `lib/auth/error-copy.ts` localises.\n // `responseData.error` is kept for any endpoint using Nest's default\n // envelope, and the axios code (ECONNABORTED, ERR_NETWORK) last.\n error: responseData.code || responseData.error || axiosError.code,\n // `unwrap()` copies this onto `ApiClientError.details`; checkout\n // reads `details.items` to mark the cart lines that are short.\n details: responseData.details,\n },\n };\n }\n\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 async get<T>(\n url: string,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n try {\n const response = await this.axiosInstance.get<T>(url, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async post<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n try {\n const response = await this.axiosInstance.post<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async put<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n try {\n const response = await this.axiosInstance.put<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async patch<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n try {\n const response = await this.axiosInstance.patch<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async delete<T>(\n url: string,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n try {\n const response = await this.axiosInstance.delete<T>(url, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n // Additional utility methods\n getAxiosInstance(): AxiosInstance {\n return this.axiosInstance;\n }\n\n // Method to update base URL if needed\n setBaseURL(baseUrl: string): void {\n this.axiosInstance.defaults.baseURL = baseUrl.replace(/\\/$/, \"\");\n }\n\n // Method to set default timeout\n setTimeout(timeout: number): void {\n this.axiosInstance.defaults.timeout = timeout;\n }\n}\n\n/**\n * Direct, key-authenticated client for the backend's own origin. Public\n * endpoints only — it can never carry a session token (see the request\n * interceptor above).\n */\nexport const publicApiClient = new ApiClient(publicConfig().apiUrl);\n\n/**\n * A store-scoped instance whose baseURL is the same-origin proxy route\n * `/store/<storeRef>/api/backend`, so the httpOnly session cookie is sent with\n * every request and `lib/api/proxy.ts` turns it into a bearer token\n * server-side. It deliberately does NOT send `x-storefront-api-key` from the\n * browser: the proxy attaches it.\n *\n * The timeout is wider than the direct client's because a proxied call may\n * include one refresh round trip plus a retry.\n */\nexport function createStoreApiClient(storeRef: string): ApiClient {\n return new ApiClient(storeApiPath(storeRef, \"backend\"), {\n withApiKey: false,\n timeout: 20000,\n });\n}\n\n// Export the class for custom instances\nexport { ApiClient };\n"],"mappings":"AAAA,OAAO,WAKA;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAE7B,MAAM,kBAAkB;AAaxB,SAAS,wBAAwB,QAAqC;AACpE,MAAI,CAAC,sBAAsB,EAAG,QAAO;AACrC,QAAM,QAAQ,UAAU,OAAO,YAAY;AAC3C,MAAI,SAAS,SAAS,SAAS,OAAQ,QAAO;AAC9C,SAAO,CAAC,2BAA2B;AACrC;AAYA,MAAM,UAA4C;AAAA,EACxC;AAAA,EACA;AAAA,EAER,YACE,UAAkB,aAAa,EAAE,QACjC,SACA;AACA,SAAK,aAAa,SAAS,cAAc;AAEzC,UAAM,iBAAyC;AAAA,MAC7C,gBAAgB;AAAA,IAClB;AAEA,UAAM,iBAAiB,aAAa,EAAE;AACtC,QAAI,KAAK,cAAc,gBAAgB;AACrC,qBAAe,sBAAsB,IAAI;AAAA,IAC3C;AAEA,SAAK,gBAAgB,MAAM,OAAO;AAAA,MAChC,SAAS,QAAQ,QAAQ,OAAO,EAAE;AAAA;AAAA,MAClC,SAAS,SAAS,WAAW;AAAA,MAC7B,SAAS;AAAA,IACX,CAAC;AAED,SAAK,kBAAkB;AAAA,EACzB;AAAA,EAEQ,oBAA0B;AAEhC,SAAK,cAAc,aAAa,QAAQ;AAAA,MACtC,OAAM,WAAU;AAEd,cAAM,iBAAiB,aAAa,EAAE;AACtC,YACE,KAAK,cACL,kBACA,CAAC,OAAO,QAAQ,sBAAsB,GACtC;AACA,iBAAO,QAAQ,sBAAsB,IAAI;AAAA,QAC3C;AAOA,cAAM,eAAe,MAAM,yBAA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,eAAe,QAAQ;AAAA,IACrC,SAAS,OAAO;AACd,aAAO,KAAK,YAAY,KAAK;AAAA,IAC/B;AAAA,EACF;AAAA,EAEA,MAAM,OACJ,KACA,QACyB;AACzB,QAAI;AACF,YAAM,WAAW,MAAM,KAAK,cAAc,OAAU,KAAK,MAAM;AAC/D,aAAO,KAAK,eAAe,QAAQ;AAAA,IACrC,SAAS,OAAO;AACd,aAAO,KAAK,YAAY,KAAK;AAAA,IAC/B;AAAA,EACF;AAAA;AAAA,EAGA,mBAAkC;AAChC,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,WAAW,SAAuB;AAChC,SAAK,cAAc,SAAS,UAAU,QAAQ,QAAQ,OAAO,EAAE;AAAA,EACjE;AAAA;AAAA,EAGA,WAAW,SAAuB;AAChC,SAAK,cAAc,SAAS,UAAU;AAAA,EACxC;AACF;AAOO,MAAM,kBAAkB,IAAI,UAAU,aAAa,EAAE,MAAM;AAY3D,SAAS,qBAAqB,UAA6B;AAChE,SAAO,IAAI,UAAU,aAAa,UAAU,SAAS,GAAG;AAAA,IACtD,YAAY;AAAA,IACZ,SAAS;AAAA,EACX,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/api/client.ts"],"sourcesContent":["import axios, {\n AxiosInstance,\n AxiosRequestConfig,\n AxiosResponse,\n AxiosError,\n} from \"axios\";\nimport { ApiResponse, AuthenticatedApiClient } from \"../interfaces\";\nimport {\n isStoreSuspendedResponseBody,\n STORE_SUSPENDED_REDIRECT_PATH,\n} from \"../stores/store-suspension\";\nimport {\n isStoreComingSoonResponseBody,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"../stores/store-coming-soon\";\nimport {\n skipsStorePreview,\n STORE_PREVIEW_HEADER,\n} from \"../stores/store-preview-cookie\";\nimport {\n currentStorePreviewToken,\n isBrowserStorePreview,\n requestStorePreviewRenewal,\n} from \"./store-preview-header\";\nimport { publicConfig } from \"../config\";\nimport { storeApiPath } from \"../store-scope\";\nimport { findPrivateStorefrontRoute } from \"./proxy-routes\";\n\nconst DEFAULT_TIMEOUT = 10000; // 10 seconds\n\n/**\n * Whether a browser call's STORE_COMING_SOON 403 ends this visit, so the\n * browser goes to the coming soon page.\n * - Not previewing: yes, the store is closed to this shopper.\n * - Previewing, a write: no. A preview is read-only (the API opens GET and\n * HEAD only), so the write was refused, not the preview; the caller\n * reports it.\n * - Previewing, a read: the token ran out. A preview host renews it\n * (`requestStorePreviewRenewal`), so the preview goes on; a link\n * preview has no renewer, and its preview is over.\n */\nfunction comingSoonEndsThisVisit(method: string | undefined): boolean {\n if (!isBrowserStorePreview()) return true;\n const verb = (method ?? \"get\").toUpperCase();\n if (verb !== \"GET\" && verb !== \"HEAD\") return false;\n return !requestStorePreviewRenewal();\n}\n\ninterface ApiClientOptions {\n /**\n * Send `x-storefront-api-key` from the browser. True for direct calls to the\n * backend's own origin; false for calls routed through the same-origin proxy\n * (`lib/api/proxy.ts`), which attaches the key server-side.\n */\n withApiKey?: boolean;\n timeout?: number;\n}\n\nconst PRIVATE_ROUTE_MESSAGE =\n \"This route needs the storefront's secret key: call it with createStoreSdk(storeRef) in the browser or getServerSdk() on the server\";\n\n// Route patterns already reported, so a retry loop logs once.\nconst reportedPrivateRoutes = new Set<string>();\n\nclass ApiClient implements AuthenticatedApiClient {\n private axiosInstance: AxiosInstance;\n private withApiKey: boolean;\n\n constructor(\n baseUrl: string = publicConfig().apiUrl,\n options?: ApiClientOptions\n ) {\n this.withApiKey = options?.withApiKey ?? true;\n\n const defaultHeaders: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n const platformApiKey = publicConfig().storefrontApiKey;\n if (this.withApiKey && platformApiKey) {\n defaultHeaders[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n this.axiosInstance = axios.create({\n baseURL: baseUrl.replace(/\\/$/, \"\"), // Remove trailing slash\n timeout: options?.timeout ?? DEFAULT_TIMEOUT,\n headers: defaultHeaders,\n });\n\n this.setupInterceptors();\n }\n\n private setupInterceptors(): void {\n // Request interceptor - add platform API key\n this.axiosInstance.interceptors.request.use(\n async config => {\n // Ensure API key is always present (in case instance was created before env loaded)\n const platformApiKey = publicConfig().storefrontApiKey;\n if (\n this.withApiKey &&\n platformApiKey &&\n !config.headers[\"x-storefront-api-key\"]\n ) {\n config.headers[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n // Opens a coming soon store for a previewer (read-only on the API's\n // side). An explicit header wins, such as the token the middleware\n // passes to `getByDomain`, and a call carrying SKIP_STORE_PREVIEW (a\n // plain, cached host lookup) never gets the request's token.\n // `get`/`set` match the header name case-insensitively.\n const previewToken = await currentStorePreviewToken();\n if (\n previewToken &&\n !skipsStorePreview(config) &&\n !config.headers.get(STORE_PREVIEW_HEADER)\n ) {\n config.headers.set(STORE_PREVIEW_HEADER, previewToken);\n }\n\n // No Authorization header is ever set here. Session tokens live in\n // httpOnly, store-scoped cookies (lib/auth/cookies.ts) that browser JS\n // cannot read; authenticated calls go through the same-origin proxy\n // built by createStoreApiClient() below, which attaches the bearer\n // token server-side.\n return config;\n },\n error => {\n return Promise.reject(error);\n }\n );\n\n // Response interceptor - handle common errors and format responses\n this.axiosInstance.interceptors.response.use(\n (response: AxiosResponse) => {\n // Success response\n return response;\n },\n (error: AxiosError) => {\n // Never the error itself: its config carries the request headers,\n // the preview token and the API key among them.\n console.error(\"API Client Error:\", {\n method: error.config?.method?.toUpperCase(),\n url: error.config?.url,\n status: error.response?.status,\n code:\n (error.response?.data as { code?: unknown } | undefined)?.code ??\n error.code,\n });\n // Handle common error scenarios\n if (error.code === \"ECONNABORTED\") {\n // Timeout error\n error.message = \"Request timeout - please try again\";\n } else if (!error.response) {\n // Network error\n error.message = \"Network error - check your connection\";\n }\n\n // A platform admin suspended this store mid-session. The initial\n // page render already handles suspension at store-resolution time\n // (app/store/[storeRef]/layout.tsx, proxy.ts) — but a client-side\n // call *after* that render (add-to-cart, checkout, a review\n // submission) hits this same guarded backend independently, and\n // isn't covered by that one-time check. Only the browser can\n // navigate on it; server-side callers still just get the rejection.\n if (\n typeof window !== \"undefined\" &&\n error.response?.status === 403 &&\n isStoreSuspendedResponseBody(error.response?.data)\n ) {\n window.location.href = STORE_SUSPENDED_REDIRECT_PATH;\n }\n\n // Likewise, the store went (or still is) coming soon. Not from the\n // coming soon page itself, so a call made there cannot reload it in\n // a loop. It is always this root path in the browser: the\n // middleware rewrites to it without changing the URL, and the shared\n // path-based host has no such page (known limitation,\n // create-storefront-middleware.ts).\n if (\n typeof window !== \"undefined\" &&\n error.response?.status === 403 &&\n isStoreComingSoonResponseBody(error.response?.data) &&\n window.location.pathname !== STORE_COMING_SOON_REDIRECT_PATH &&\n comingSoonEndsThisVisit(error.config?.method)\n ) {\n window.location.href = STORE_COMING_SOON_REDIRECT_PATH;\n }\n\n return Promise.reject(error);\n }\n );\n }\n\n private handleResponse<T>(response: AxiosResponse<T>): ApiResponse<T> {\n return {\n success: true,\n data: response.data,\n };\n }\n\n private handleError(error: any): ApiResponse<never> {\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError<any>;\n const responseData = axiosError.response?.data || {};\n return {\n success: false,\n error: {\n message:\n responseData.message || axiosError.message || \"Request failed\",\n statusCode: axiosError.response?.status || 0,\n // The backend serialises business errors as\n // `{ code, message, details, timestamp }`, so the stable identifier\n // lands in `code` — this is the browser-side twin of the same read\n // in `lib/auth/sdk.ts`. `unwrap()` copies it onto\n // `ApiClientError.code`, which `lib/auth/error-copy.ts` localises.\n // `responseData.error` is kept for any endpoint using Nest's default\n // envelope, and the axios code (ECONNABORTED, ERR_NETWORK) last.\n error: responseData.code || responseData.error || axiosError.code,\n // `unwrap()` copies this onto `ApiClientError.details`; checkout\n // reads `details.items` to mark the cart lines that are short.\n details: responseData.details,\n },\n };\n }\n\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 * The direct, publishable-key client cannot call a private route: the API\n * would refuse it, so refuse here, before the network. Logs the matched\n * route pattern, never the raw path (it can carry a review token or an\n * order code).\n */\n private refusePrivateRoute(\n method: string,\n url: string\n ): ApiResponse<never> | null {\n if (!this.withApiKey) return null;\n const route = findPrivateStorefrontRoute(method, url);\n if (!route) return null;\n const label = `${route.method} ${route.path}`;\n if (!reportedPrivateRoutes.has(label)) {\n reportedPrivateRoutes.add(label);\n console.error(\n `STOREFRONT_PRIVATE_ROUTE: ${label}. ${PRIVATE_ROUTE_MESSAGE}`\n );\n }\n return {\n success: false,\n error: {\n message: PRIVATE_ROUTE_MESSAGE,\n statusCode: 0,\n error: \"STOREFRONT_PRIVATE_ROUTE\",\n },\n };\n }\n\n async get<T>(\n url: string,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"GET\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.get<T>(url, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async post<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"POST\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.post<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async put<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"PUT\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.put<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async patch<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"PATCH\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.patch<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async delete<T>(\n url: string,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"DELETE\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.delete<T>(url, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n // Additional utility methods\n getAxiosInstance(): AxiosInstance {\n return this.axiosInstance;\n }\n\n // Method to update base URL if needed\n setBaseURL(baseUrl: string): void {\n this.axiosInstance.defaults.baseURL = baseUrl.replace(/\\/$/, \"\");\n }\n\n // Method to set default timeout\n setTimeout(timeout: number): void {\n this.axiosInstance.defaults.timeout = timeout;\n }\n}\n\n/**\n * Direct, key-authenticated client for the backend's own origin. Public\n * endpoints only — it can never carry a session token (see the request\n * interceptor above).\n */\nexport const publicApiClient = new ApiClient(publicConfig().apiUrl);\n\n/**\n * A store-scoped instance whose baseURL is the same-origin proxy route\n * `/store/<storeRef>/api/backend`, so the httpOnly session cookie is sent with\n * every request and `lib/api/proxy.ts` turns it into a bearer token\n * server-side. It deliberately does NOT send `x-storefront-api-key` from the\n * browser: the proxy attaches it.\n *\n * The timeout is wider than the direct client's because a proxied call may\n * include one refresh round trip plus a retry.\n */\nexport function createStoreApiClient(storeRef: string): ApiClient {\n return new ApiClient(storeApiPath(storeRef, \"backend\"), {\n withApiKey: false,\n timeout: 20000,\n });\n}\n\n// Export the class for custom instances\nexport { ApiClient };\n"],"mappings":"AAAA,OAAO,WAKA;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,kCAAkC;AAE3C,MAAM,kBAAkB;AAaxB,SAAS,wBAAwB,QAAqC;AACpE,MAAI,CAAC,sBAAsB,EAAG,QAAO;AACrC,QAAM,QAAQ,UAAU,OAAO,YAAY;AAC3C,MAAI,SAAS,SAAS,S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use in React components).\n// `publicApiClient` talks to the backend origin directly and can never carry a\n// session token; `createStoreApiClient(storeRef)` routes through the\n// same-origin proxy that attaches one server-side.\nexport { publicApiClient, createStoreApiClient, ApiClient } from \"./client\";\n\n// Note: serverApiClient is not exported here to avoid bundling server-only\n// dependencies on the client. Use getApiClient() for universal usage,\n// or import { serverApiClient } from './server-client' directly\n// in server-only contexts if needed.\n"],"mappings":"AAIA,SAAS,iBAAiB,sBAAsB,iBAAiB;","names":[]}
1
+ {"version":3,"sources":["../../src/api/index.ts"],"sourcesContent":["// Client-side API clients (for use in React components).\n// `publicApiClient` talks to the backend origin directly and can never carry a\n// session token; `createStoreApiClient(storeRef)` routes through the\n// same-origin proxy that attaches one server-side.\nexport { publicApiClient, createStoreApiClient, ApiClient } from \"./client\";\n\n// Server-side private reads go through getServerSdk() from\n// `@ecomweb/storefront-kit/server`, which signs with the secret key.\n"],"mappings":"AAIA,SAAS,iBAAiB,sBAAsB,iBAAiB;","names":[]}
@@ -0,0 +1,29 @@
1
+ import { NextResponse } from "next/server";
2
+ import { publicConfig } from "../config/public.js";
3
+ import { publicNextUrl } from "../request/public-url.js";
4
+ import { SERVED_STORE_HEADER } from "../request/served-store.js";
5
+ function servedStoreRef(request) {
6
+ const config = publicConfig();
7
+ if (config.mode === "single") return config.storeRef ?? null;
8
+ if (/^\/api/.test(request.nextUrl.pathname)) return null;
9
+ return request.headers.get(SERVED_STORE_HEADER) || null;
10
+ }
11
+ function isSameOriginRequest(request) {
12
+ const site = request.headers.get("sec-fetch-site");
13
+ if (site !== null) return site === "same-origin";
14
+ const origin = request.headers.get("origin");
15
+ if (!origin) return request.method === "GET" || request.method === "HEAD";
16
+ return origin === publicNextUrl(request).origin;
17
+ }
18
+ function proxyNotFound() {
19
+ return NextResponse.json(
20
+ { code: "NOT_FOUND", message: "Not found" },
21
+ { status: 404 }
22
+ );
23
+ }
24
+ export {
25
+ isSameOriginRequest,
26
+ proxyNotFound,
27
+ servedStoreRef
28
+ };
29
+ //# sourceMappingURL=proxy-guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/api/proxy-guard.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { publicConfig } from \"../config/public\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport { SERVED_STORE_HEADER } from \"../request/served-store\";\n\n/**\n * The store this request serves: the configured store in single mode, the\n * middleware's stamp in multi mode (null when it stamped none, and on paths\n * the middleware does not process).\n */\nexport function servedStoreRef(request: {\n headers: { get(name: string): string | null };\n nextUrl: { pathname: string };\n}): string | null {\n const config = publicConfig();\n if (config.mode === \"single\") return config.storeRef ?? null;\n // The middleware matcher excludes paths starting with `api` (e.g.\n // /api/auth/*), so such a request never had a client copy stripped: its\n // stamp is whatever the client sent.\n if (/^\\/api/.test(request.nextUrl.pathname)) return null;\n return request.headers.get(SERVED_STORE_HEADER) || null;\n}\n\n/**\n * True when the browser says the request came from this storefront's own\n * origin. `Sec-Fetch-Site`, when present, decides alone (only `same-origin`\n * passes); without it, `Origin` must equal the shopper-facing origin.\n *\n * A request with neither header passes only as a GET or HEAD. Safari before\n * 16.4 sends no `Sec-Fetch-*`, and browsers send no `Origin` on a same-origin\n * GET, so refusing those would lock older iPhones out of every private read.\n * A cross-site page cannot read the response (no CORS), proxied GETs change\n * nothing, and a script can forge both headers anyway: this check is CSRF\n * protection, not bot protection. Any other method with neither header is\n * refused.\n */\nexport function isSameOriginRequest(\n request: Pick<NextRequest, \"headers\" | \"nextUrl\" | \"method\">\n): boolean {\n const site = request.headers.get(\"sec-fetch-site\");\n if (site !== null) return site === \"same-origin\";\n const origin = request.headers.get(\"origin\");\n if (!origin) return request.method === \"GET\" || request.method === \"HEAD\";\n return origin === publicNextUrl(request).origin;\n}\n\n/**\n * The one answer for every refusal by the backend proxy and the auth routes,\n * whichever check failed, so a caller cannot tell which one it tripped.\n */\nexport function proxyNotFound(): NextResponse {\n return NextResponse.json(\n { code: \"NOT_FOUND\", message: \"Not found\" },\n { status: 404 }\n );\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AAO7B,SAAS,eAAe,SAGb;AAChB,QAAM,SAAS,aAAa;AAC5B,MAAI,OAAO,SAAS,SAAU,QAAO,OAAO,YAAY;AAIxD,MAAI,SAAS,KAAK,QAAQ,QAAQ,QAAQ,EAAG,QAAO;AACpD,SAAO,QAAQ,QAAQ,IAAI,mBAAmB,KAAK;AACrD;AAeO,SAAS,oBACd,SACS;AACT,QAAM,OAAO,QAAQ,QAAQ,IAAI,gBAAgB;AACjD,MAAI,SAAS,KAAM,QAAO,SAAS;AACnC,QAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ;AAC3C,MAAI,CAAC,OAAQ,QAAO,QAAQ,WAAW,SAAS,QAAQ,WAAW;AACnE,SAAO,WAAW,cAAc,OAAO,EAAE;AAC3C;AAMO,SAAS,gBAA8B;AAC5C,SAAO,aAAa;AAAA,IAClB,EAAE,MAAM,aAAa,SAAS,YAAY;AAAA,IAC1C,EAAE,QAAQ,IAAI;AAAA,EAChB;AACF;","names":[]}
@@ -0,0 +1,126 @@
1
+ const GUEST = "storefront/stores/:storeRef";
2
+ const CUSTOMER = "storefront/stores/:storeRef/customers";
3
+ const TENANT = CUSTOMER;
4
+ const priv = (method, path) => ({
5
+ method,
6
+ path,
7
+ access: "private"
8
+ });
9
+ const shopperRead = (path) => ({
10
+ method: "GET",
11
+ path,
12
+ access: "shopper-read"
13
+ });
14
+ const PROXIED_STOREFRONT_ROUTES = [
15
+ // Guest cart
16
+ priv("GET", `${GUEST}/cart`),
17
+ priv("DELETE", `${GUEST}/cart`),
18
+ priv("POST", `${GUEST}/cart/items`),
19
+ priv("PUT", `${GUEST}/cart/items/:itemId`),
20
+ priv("DELETE", `${GUEST}/cart/items/:itemId`),
21
+ // Customer cart
22
+ priv("GET", `${CUSTOMER}/cart`),
23
+ priv("DELETE", `${CUSTOMER}/cart`),
24
+ priv("POST", `${CUSTOMER}/cart/items`),
25
+ priv("PUT", `${CUSTOMER}/cart/items/:itemId`),
26
+ priv("DELETE", `${CUSTOMER}/cart/items/:itemId`),
27
+ priv("POST", `${CUSTOMER}/cart/merge`),
28
+ // Orders
29
+ priv("POST", `${GUEST}/orders`),
30
+ priv("GET", `${GUEST}/orders/lookup`),
31
+ priv("GET", `${TENANT}/orders`),
32
+ priv("POST", `${TENANT}/orders`),
33
+ priv("GET", `${TENANT}/orders/:id`),
34
+ priv("DELETE", `${TENANT}/orders/:id`),
35
+ // Payments
36
+ priv("POST", `${GUEST}/payments/initiate`),
37
+ priv("GET", `${GUEST}/orders/:orderCode/payment-state`),
38
+ // Review invitations
39
+ priv("GET", `${GUEST}/review-invitations/by-order`),
40
+ priv("GET", `${GUEST}/review-invitations/by-orders`),
41
+ priv("GET", `${GUEST}/review-invitations/:token`),
42
+ priv("POST", `${GUEST}/review-invitations/:token/submit`),
43
+ // Checkout quotes
44
+ priv("POST", `${GUEST}/shipping/calculate`),
45
+ priv("POST", `${GUEST}/promotions/validate`),
46
+ // Blog
47
+ priv("POST", `${GUEST}/blog/posts/:postId/comments`),
48
+ shopperRead(`${GUEST}/blog/posts/:postId/comments`),
49
+ // Metaobjects
50
+ shopperRead(`${GUEST}/metaobjects/:type`),
51
+ shopperRead(`${GUEST}/metaobjects/:type/:handle`),
52
+ // Customer
53
+ priv("GET", `${TENANT}/metafields`),
54
+ priv("PUT", `${TENANT}/metafields`),
55
+ priv("GET", `${TENANT}/address`),
56
+ priv("POST", `${TENANT}/address`),
57
+ priv("GET", `${TENANT}/address/:addressId`),
58
+ priv("PATCH", `${TENANT}/address/:addressId`),
59
+ priv("DELETE", `${TENANT}/address/:addressId`),
60
+ priv("PATCH", `${TENANT}/address/:addressId/set-default`),
61
+ // Web vitals
62
+ priv("POST", `${GUEST}/web-vitals`)
63
+ ];
64
+ const PARSED = PROXIED_STOREFRONT_ROUTES.map((route) => ({
65
+ route,
66
+ parts: route.path.split("/")
67
+ }));
68
+ function isSafeSegment(segment) {
69
+ return segment !== "" && segment !== "." && segment !== ".." && !/[/\\?#%\s]/.test(segment) && ![...segment].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127);
70
+ }
71
+ function matchSegments(method, segments, strict) {
72
+ if (strict && !segments.every(isSafeSegment)) return null;
73
+ const verb = method.toUpperCase();
74
+ for (const { route, parts } of PARSED) {
75
+ if (route.method !== verb || parts.length !== segments.length) continue;
76
+ let storeRef = "";
77
+ let ok = true;
78
+ for (let i = 0; i < parts.length; i++) {
79
+ const part = parts[i];
80
+ const seg = segments[i];
81
+ if (part === ":storeRef") {
82
+ if (!seg) {
83
+ ok = false;
84
+ break;
85
+ }
86
+ storeRef = seg;
87
+ } else if (part.startsWith(":")) {
88
+ if (!seg) {
89
+ ok = false;
90
+ break;
91
+ }
92
+ } else if (part !== seg) {
93
+ ok = false;
94
+ break;
95
+ }
96
+ }
97
+ if (ok) return { route, storeRef };
98
+ }
99
+ return null;
100
+ }
101
+ function matchProxiedRoute(method, segments) {
102
+ return matchSegments(method, segments, true);
103
+ }
104
+ function decodeSegment(segment) {
105
+ try {
106
+ return decodeURIComponent(segment);
107
+ } catch {
108
+ return segment;
109
+ }
110
+ }
111
+ function findPrivateStorefrontRoute(method, url) {
112
+ const path = url.split("?")[0].split("#")[0];
113
+ const segments = path.split("/").filter(Boolean).map(decodeSegment);
114
+ const match = matchSegments(method, segments, false);
115
+ return match && match.route.access === "private" ? match.route : null;
116
+ }
117
+ function isPrivateStorefrontPath(method, url) {
118
+ return findPrivateStorefrontRoute(method, url) !== null;
119
+ }
120
+ export {
121
+ PROXIED_STOREFRONT_ROUTES,
122
+ findPrivateStorefrontRoute,
123
+ isPrivateStorefrontPath,
124
+ matchProxiedRoute
125
+ };
126
+ //# sourceMappingURL=proxy-routes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/api/proxy-routes.ts"],"sourcesContent":["/**\n * The storefront routes that go through the same-origin store proxy.\n *\n * A route in this list goes through the proxy, which attaches the storefront\n * secret key server-side. A public API route may stay listed (a secret key\n * also works on public routes). A private route missing here is broken in the\n * browser and refused by the proxy. This is the single list to edit; it must\n * agree with the API's route table (`@StorefrontAccess` classification).\n *\n * Shopper auth is not listed: it goes through the kit's auth routes, never\n * the backend proxy.\n */\nexport type ProxiedMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport interface ProxiedRoute {\n method: ProxiedMethod;\n /**\n * Relative to the API base. `/`-separated; exactly one `:storeRef`; any\n * other `:name` segment matches one non-empty segment.\n */\n path: string;\n /**\n * `private`: needs the secret key. `shopper-read`: a public route that\n * reads the shopper's session when a bearer is present.\n */\n access: \"private\" | \"shopper-read\";\n}\n\nconst GUEST = \"storefront/stores/:storeRef\";\nconst CUSTOMER = \"storefront/stores/:storeRef/customers\";\nconst TENANT = CUSTOMER;\n\nconst priv = (method: ProxiedMethod, path: string): ProxiedRoute => ({\n method,\n path,\n access: \"private\",\n});\nconst shopperRead = (path: string): ProxiedRoute => ({\n method: \"GET\",\n path,\n access: \"shopper-read\",\n});\n\nexport const PROXIED_STOREFRONT_ROUTES: readonly ProxiedRoute[] = [\n // Guest cart\n priv(\"GET\", `${GUEST}/cart`),\n priv(\"DELETE\", `${GUEST}/cart`),\n priv(\"POST\", `${GUEST}/cart/items`),\n priv(\"PUT\", `${GUEST}/cart/items/:itemId`),\n priv(\"DELETE\", `${GUEST}/cart/items/:itemId`),\n // Customer cart\n priv(\"GET\", `${CUSTOMER}/cart`),\n priv(\"DELETE\", `${CUSTOMER}/cart`),\n priv(\"POST\", `${CUSTOMER}/cart/items`),\n priv(\"PUT\", `${CUSTOMER}/cart/items/:itemId`),\n priv(\"DELETE\", `${CUSTOMER}/cart/items/:itemId`),\n priv(\"POST\", `${CUSTOMER}/cart/merge`),\n // Orders\n priv(\"POST\", `${GUEST}/orders`),\n priv(\"GET\", `${GUEST}/orders/lookup`),\n priv(\"GET\", `${TENANT}/orders`),\n priv(\"POST\", `${TENANT}/orders`),\n priv(\"GET\", `${TENANT}/orders/:id`),\n priv(\"DELETE\", `${TENANT}/orders/:id`),\n // Payments\n priv(\"POST\", `${GUEST}/payments/initiate`),\n priv(\"GET\", `${GUEST}/orders/:orderCode/payment-state`),\n // Review invitations\n priv(\"GET\", `${GUEST}/review-invitations/by-order`),\n priv(\"GET\", `${GUEST}/review-invitations/by-orders`),\n priv(\"GET\", `${GUEST}/review-invitations/:token`),\n priv(\"POST\", `${GUEST}/review-invitations/:token/submit`),\n // Checkout quotes\n priv(\"POST\", `${GUEST}/shipping/calculate`),\n priv(\"POST\", `${GUEST}/promotions/validate`),\n // Blog\n priv(\"POST\", `${GUEST}/blog/posts/:postId/comments`),\n shopperRead(`${GUEST}/blog/posts/:postId/comments`),\n // Metaobjects\n shopperRead(`${GUEST}/metaobjects/:type`),\n shopperRead(`${GUEST}/metaobjects/:type/:handle`),\n // Customer\n priv(\"GET\", `${TENANT}/metafields`),\n priv(\"PUT\", `${TENANT}/metafields`),\n priv(\"GET\", `${TENANT}/address`),\n priv(\"POST\", `${TENANT}/address`),\n priv(\"GET\", `${TENANT}/address/:addressId`),\n priv(\"PATCH\", `${TENANT}/address/:addressId`),\n priv(\"DELETE\", `${TENANT}/address/:addressId`),\n priv(\"PATCH\", `${TENANT}/address/:addressId/set-default`),\n // Web vitals\n priv(\"POST\", `${GUEST}/web-vitals`),\n];\n\nconst PARSED = PROXIED_STOREFRONT_ROUTES.map(route => ({\n route,\n parts: route.path.split(\"/\"),\n}));\n\n/**\n * Whether a decoded segment is safe to forward under the secret key: not\n * empty, not a dot segment, and free of path/query delimiters. A `%` left\n * after the proxy's one decode means a double-encoded value.\n */\nfunction isSafeSegment(segment: string): boolean {\n return (\n segment !== \"\" &&\n segment !== \".\" &&\n segment !== \"..\" &&\n !/[/\\\\?#%\\s]/.test(segment) &&\n ![...segment].some(c => c.charCodeAt(0) < 0x20 || c.charCodeAt(0) === 0x7f)\n );\n}\n\nfunction matchSegments(\n method: string,\n segments: readonly string[],\n strict: boolean\n): { route: ProxiedRoute; storeRef: string } | null {\n if (strict && !segments.every(isSafeSegment)) return null;\n const verb = method.toUpperCase();\n for (const { route, parts } of PARSED) {\n if (route.method !== verb || parts.length !== segments.length) continue;\n let storeRef = \"\";\n let ok = true;\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i]!;\n const seg = segments[i]!;\n if (part === \":storeRef\") {\n if (!seg) {\n ok = false;\n break;\n }\n storeRef = seg;\n } else if (part.startsWith(\":\")) {\n if (!seg) {\n ok = false;\n break;\n }\n } else if (part !== seg) {\n ok = false;\n break;\n }\n }\n if (ok) return { route, storeRef };\n }\n return null;\n}\n\n/**\n * The listed route a request matches, and the store its path names.\n * `segments` are already decoded once, as Next passes them. Any segment that\n * is empty, `.`, `..`, double-encoded or holds `/ \\ ? #` rejects the whole\n * path, since a matched path is forwarded under the secret key. So does any\n * control character or whitespace (URL parsing strips tab/LF/CR, so `.\\t.`\n * could collapse to `..`).\n *\n * Callers that forward the matched segments must `encodeURIComponent` each\n * one when building the upstream URL.\n */\nexport function matchProxiedRoute(\n method: string,\n segments: readonly string[]\n): { route: ProxiedRoute; storeRef: string } | null {\n return matchSegments(method, segments, true);\n}\n\nfunction decodeSegment(segment: string): string {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n}\n\n/** The private entry a request URL (path with optional query) matches. */\nexport function findPrivateStorefrontRoute(\n method: string,\n url: string\n): ProxiedRoute | null {\n const path = url.split(\"?\")[0]!.split(\"#\")[0]!;\n const segments = path.split(\"/\").filter(Boolean).map(decodeSegment);\n // Lenient on purpose: this only refuses, it never forwards.\n const match = matchSegments(method, segments, false);\n return match && match.route.access === \"private\" ? match.route : null;\n}\n\nexport function isPrivateStorefrontPath(method: string, url: string): boolean {\n return findPrivateStorefrontRoute(method, url) !== null;\n}\n"],"mappings":"AA4BA,MAAM,QAAQ;AACd,MAAM,WAAW;AACjB,MAAM,SAAS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Q;AAC/D,QAAI,WAAW;AACf,QAAI,KAAK;AACT,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,YAAM,OAAO,MAAM,CAAC;AACpB,YAAM,MAAM,SAAS,CAAC;AACtB,UAAI,SAAS,aAAa;AACxB,YAAI,CAAC,KAAK;AACR,eAAK;AACL;AAAA,QACF;AACA,mBAAW;AAAA,MACb,WAAW,KAAK,WAAW,GAAG,GAAG;AAC/B,YAAI,CAAC,KAAK;AACR,eAAK;AACL;AAAA,QACF;AAAA,MACF,WAAW,SAAS,KAAK;AACvB,aAAK;AACL;AAAA,MACF;AAAA,IACF;AACA,QAAI,GAAI,QAAO,EAAE,OAAO,SAAS;AAAA,EACnC;AACA,SAAO;AACT;AAaO,SAAS,kBACd,QACA,UACkD;AAClD,SAAO,cAAc,QAAQ,UAAU,IAAI;AAC7C;AAEA,SAAS,cAAc,SAAyB;AAC9C,MAAI;AACF,WAAO,mBAAmB,OAAO;AAAA,EACnC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,2BACd,QACA,KACqB;AACrB,QAAM,OAAO,IAAI,MAAM,GAAG,EAAE,CAAC,EAAG,MAAM,GAAG,EAAE,CAAC;AAC5C,QAAM,WAAW,KAAK,MAAM,GAAG,EAAE,OAAO,OAAO,EAAE,IAAI,aAAa;AAElE,QAAM,QAAQ,cAAc,QAAQ,UAAU,KAAK;AACnD,SAAO,SAAS,MAAM,MAAM,WAAW,YAAY,MAAM,QAAQ;AACnE;AAEO,SAAS,wBAAwB,QAAgB,KAAsB;AAC5E,SAAO,2BAA2B,QAAQ,GAAG,MAAM;AACrD;","names":[]}
package/dist/api/proxy.js CHANGED
@@ -10,13 +10,15 @@ import {
10
10
  FORWARDER_SECRET_HEADER,
11
11
  forwardingHeaders
12
12
  } from "../auth/client-ip.js";
13
- import { backendBaseUrl, createAuthApi, storefrontApiKey } from "../auth/sdk.js";
13
+ import { backendBaseUrl, createAuthApi, storefrontSecretKey } from "../auth/sdk.js";
14
14
  import { multiTenantStorePath } from "../store-scope/index.js";
15
15
  import {
16
16
  STORE_PREVIEW_HEADER,
17
17
  STORE_PREVIEW_TOKEN_HEADER,
18
18
  storePreviewTokenFrom
19
19
  } from "../stores/store-preview-cookie.js";
20
+ import { isSameOriginRequest, proxyNotFound } from "./proxy-guard.js";
21
+ import { matchProxiedRoute } from "./proxy-routes.js";
20
22
  const BLOCKED_REQUEST_HEADERS = /* @__PURE__ */ new Set([
21
23
  "connection",
22
24
  "keep-alive",
@@ -44,6 +46,10 @@ const METHODS_WITH_BODY = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELE
44
46
  function jsonError(status, message, code) {
45
47
  return NextResponse.json({ code, message }, { status });
46
48
  }
49
+ function refuse(reason, storeRef, method) {
50
+ console.debug("backend proxy refused", { reason, storeRef, method });
51
+ return proxyNotFound();
52
+ }
47
53
  function resolveTarget(segments, search) {
48
54
  if (segments.length === 0) return null;
49
55
  for (const segment of segments) {
@@ -82,7 +88,7 @@ function forwardedHeaders(request, storeRef, accessToken) {
82
88
  headers.set(key, value);
83
89
  }
84
90
  });
85
- headers.set("x-storefront-api-key", storefrontApiKey());
91
+ headers.set("x-storefront-api-key", storefrontSecretKey());
86
92
  for (const [key, value] of Object.entries(
87
93
  forwardingHeaders(clientIpFrom(request.headers))
88
94
  )) {
@@ -114,9 +120,16 @@ function respond(result) {
114
120
  });
115
121
  }
116
122
  async function handleBackendProxy(request, storeRef, segments) {
123
+ const method = request.method;
124
+ if (!isSameOriginRequest(request)) {
125
+ return refuse("cross-site", storeRef, method);
126
+ }
117
127
  const target = resolveTarget(segments, request.nextUrl.search);
118
- if (!target) {
119
- return jsonError(400, "Invalid proxy path", "PROXY_INVALID_PATH");
128
+ if (!target) return refuse("invalid-path", storeRef, method);
129
+ const match = matchProxiedRoute(method, segments);
130
+ if (!match) return refuse("not-proxied", storeRef, method);
131
+ if (match.storeRef !== storeRef) {
132
+ return refuse("store-mismatch", storeRef, method);
120
133
  }
121
134
  const body = METHODS_WITH_BODY.has(request.method) ? await request.text() : void 0;
122
135
  const tokens = readAuthCookies(