@ecomweb/storefront-kit 0.9.0 → 0.11.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.
- package/README.md +85 -3
- package/dist/api/client.js +32 -1
- package/dist/api/client.js.map +1 -1
- package/dist/api/proxy.js +29 -4
- package/dist/api/proxy.js.map +1 -1
- package/dist/api/store-preview-header.js +42 -0
- package/dist/api/store-preview-header.js.map +1 -0
- package/dist/auth/error-copy.js +5 -1
- package/dist/auth/error-copy.js.map +1 -1
- package/dist/auth/session-refresh.js +2 -0
- package/dist/auth/session-refresh.js.map +1 -1
- package/dist/cart/server-context.js +26 -0
- package/dist/cart/server-context.js.map +1 -1
- package/dist/checkout/quote-changed.js +16 -0
- package/dist/checkout/quote-changed.js.map +1 -0
- package/dist/checkout/use-checkout.js +45 -5
- package/dist/checkout/use-checkout.js.map +1 -1
- package/dist/index.d.ts +152 -5
- package/dist/index.js +39 -1
- package/dist/index.js.map +1 -1
- package/dist/middleware/create-storefront-middleware.js +58 -11
- package/dist/middleware/create-storefront-middleware.js.map +1 -1
- package/dist/middleware.d.ts +5 -2
- package/dist/orders/index.js +17 -1
- package/dist/orders/index.js.map +1 -1
- package/dist/orders/shipment-tracking.js +80 -0
- package/dist/orders/shipment-tracking.js.map +1 -0
- package/dist/provider.js +22 -0
- package/dist/provider.js.map +1 -1
- package/dist/redirects/lookup-redirect.js +2 -1
- package/dist/redirects/lookup-redirect.js.map +1 -1
- package/dist/server.d.ts +20 -1
- package/dist/server.js +4 -0
- package/dist/server.js.map +1 -1
- package/dist/shipping/format-shipping-option.js +28 -0
- package/dist/shipping/format-shipping-option.js.map +1 -1
- package/dist/shipping/messages.js +2 -0
- package/dist/shipping/messages.js.map +1 -1
- package/dist/shipping/option-id.js +7 -0
- package/dist/shipping/option-id.js.map +1 -0
- package/dist/shipping/shipping-calculation-reducer.js +60 -12
- package/dist/shipping/shipping-calculation-reducer.js.map +1 -1
- package/dist/shipping/use-shipping-calculation.js +38 -5
- package/dist/shipping/use-shipping-calculation.js.map +1 -1
- package/dist/stores/get-store-by-host.js +34 -7
- package/dist/stores/get-store-by-host.js.map +1 -1
- package/dist/stores/metadata.js +17 -0
- package/dist/stores/metadata.js.map +1 -1
- package/dist/stores/read-store-preview-token.js +10 -0
- package/dist/stores/read-store-preview-token.js.map +1 -0
- package/dist/stores/resolve-coming-soon.js +30 -0
- package/dist/stores/resolve-coming-soon.js.map +1 -0
- package/dist/stores/store-coming-soon.js +21 -0
- package/dist/stores/store-coming-soon.js.map +1 -0
- package/dist/stores/store-preview-cookie.js +64 -0
- package/dist/stores/store-preview-cookie.js.map +1 -0
- package/dist/stores/store-preview-guard.js +12 -0
- package/dist/stores/store-preview-guard.js.map +1 -0
- package/dist/stores/store-subdomain.js +10 -5
- package/dist/stores/store-subdomain.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -10,8 +10,8 @@ pnpm add @ecomweb/storefront-kit @ecomweb/sdk
|
|
|
10
10
|
|
|
11
11
|
| Entry | Use it from | Main exports |
|
|
12
12
|
|---|---|---|
|
|
13
|
-
| `@ecomweb/storefront-kit` | client and server components | `StorefrontKitProvider`, `useAuth`, `useCart`, `useCheckout`, `useOrderStatus`, `useOrderLookup`, `storePath`, `storeApiPath`, `metafield`, `metaobjectField`, `getMetaobjects`, `getMetaobject`, `RichText` |
|
|
14
|
-
| `@ecomweb/storefront-kit/server` | route handlers, server components | `createAuthRoutes`, `createBackendProxy`, `requireSession`, `serverConfig`, `resolveRootStoreRef` |
|
|
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` |
|
|
15
15
|
| `@ecomweb/storefront-kit/middleware` | `proxy.ts` | `createStorefrontMiddleware`, `storefrontMiddlewareConfig` |
|
|
16
16
|
| `@ecomweb/storefront-kit/config` | anywhere | `publicConfig`, `parsePublicConfig`, `resolveMode` |
|
|
17
17
|
|
|
@@ -46,7 +46,89 @@ export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();
|
|
|
46
46
|
Wrap the store layout in `<StorefrontKitProvider store={store} onNotice={…}>`;
|
|
47
47
|
`onNotice` receives the kit's messages (item added, request failed) for your
|
|
48
48
|
toasts. `useCheckout().placeOrder()` returns `redirect`, `redirect_failed`,
|
|
49
|
-
`success`, `stock_issues` or `
|
|
49
|
+
`success`, `stock_issues`, `error`, `quote_changed` or `busy`, and your page decides what to show.
|
|
50
|
+
|
|
51
|
+
## Coming soon stores and store previews
|
|
52
|
+
|
|
53
|
+
Needs kit 0.11.0. Until the merchant opens a store, the API answers every
|
|
54
|
+
storefront read with `403 STORE_COMING_SOON` (details: `{ name }`). The kit
|
|
55
|
+
turns that into a page:
|
|
56
|
+
|
|
57
|
+
- The middleware rewrites the request to `/coming-soon`, and the store layout
|
|
58
|
+
renders the page inline when it meets the error itself. Your app owns
|
|
59
|
+
`app/coming-soon/page.tsx`: call `resolveComingSoonStore()` for the store
|
|
60
|
+
name and return `comingSoonStoreMetadata(name)` (`noindex`). The sitemap is
|
|
61
|
+
empty because no store resolves.
|
|
62
|
+
- `isStoreComingSoonError(error)` and `comingSoonStoreNameOf(error)` let your
|
|
63
|
+
own data loaders recognise the error. `errorCopy("STORE_COMING_SOON")` has
|
|
64
|
+
the shopper-facing text.
|
|
65
|
+
|
|
66
|
+
The merchant sees the real store through a preview link from the dashboard:
|
|
67
|
+
`/preview?token=<token>` on the store's host, `/store/<ref>/preview?token=<token>`
|
|
68
|
+
on path-based localhost. The kit stores the token in the httpOnly
|
|
69
|
+
`ecw_store_preview` cookie for 24 h (`__Host-` prefixed on the store's host in
|
|
70
|
+
production), redirects to the store's home, and every kit client (server,
|
|
71
|
+
browser and the backend proxy) sends it as `X-Store-Preview`. Theme preview
|
|
72
|
+
hosts (`p-<slug>`) and `?preview_theme=` links on the store's own host work
|
|
73
|
+
for a coming soon store too. The token sent is, in order: a theme preview
|
|
74
|
+
host's own token, then the store preview cookie, then the theme preview cookie.
|
|
75
|
+
|
|
76
|
+
Wrap the layout so the browser can send the token as well, only while the
|
|
77
|
+
store is coming soon:
|
|
78
|
+
|
|
79
|
+
```tsx
|
|
80
|
+
// in your async layout
|
|
81
|
+
const storePreviewToken = store.coming_soon ? await readStorePreviewToken() : null;
|
|
82
|
+
<StorefrontKitProvider store={store} storePreviewToken={storePreviewToken}>
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
On a theme preview host also pass `onStorePreviewRenew` (for example
|
|
86
|
+
`router.refresh`), because that host's token lasts 1 h.
|
|
87
|
+
|
|
88
|
+
Previews are read-only: the API opens GET and HEAD only. In the browser, cart
|
|
89
|
+
writes and `placeOrder` are refused with a preview notice, and a refused write
|
|
90
|
+
does not redirect. `placeOrder`'s refusal message is
|
|
91
|
+
`STORE_PREVIEW_READ_ONLY_MESSAGE`: show it as is, and map any other
|
|
92
|
+
`STORE_COMING_SOON` message (the API's English) through `errorCopy`.
|
|
93
|
+
|
|
94
|
+
Older kits (0.10.0 and below) show their 404 or error page for a coming soon
|
|
95
|
+
store, never the real store, so upgrade to get the page.
|
|
96
|
+
|
|
97
|
+
Known limitations:
|
|
98
|
+
|
|
99
|
+
- The shared apex `/store/<ref>` path of a coming soon (or suspended) store
|
|
100
|
+
still returns 404. Use the store's subdomain or custom domain.
|
|
101
|
+
- Development only: on a path-based `localhost` store, a preview that expires
|
|
102
|
+
mid-session redirects to `/coming-soon`, which 404s there.
|
|
103
|
+
- A tab left open when the store opens keeps showing the preview notice until
|
|
104
|
+
the layout re-renders; a reload clears it.
|
|
105
|
+
|
|
106
|
+
## Carrier shipping options and tracking
|
|
107
|
+
|
|
108
|
+
Carrier-calculated options (AllinGo) are opt-in:
|
|
109
|
+
`useCheckout({ includeCarrierOptions: true })`. Without it you get fixed rates
|
|
110
|
+
only, as before. When on:
|
|
111
|
+
|
|
112
|
+
- Key and select options by `optionIdOf(option)`, not `rate_id`
|
|
113
|
+
(`shipping.selectedOptionId`, `shipping.selectOption`). `selectRate` is
|
|
114
|
+
deprecated and only reaches fixed rates.
|
|
115
|
+
- Render each option with `describeShippingOption`. Logo and track links are
|
|
116
|
+
`http(s)` only.
|
|
117
|
+
- `placeOrder()` sends `shipping_service_id` and `shipping_quoted_amount` for a
|
|
118
|
+
carrier option. If the carrier price moved, the API answers 409
|
|
119
|
+
`SHIPPING_QUOTE_CHANGED`; the kit swaps in the new options and returns
|
|
120
|
+
`{ kind: "quote_changed" }`. The new amounts are merged into the list by
|
|
121
|
+
option id (other options are kept; the API re-checks them at placement).
|
|
122
|
+
Nothing was placed: show the new price and make the buyer confirm again. An
|
|
123
|
+
unavailable rate surfaces as an `error` with code
|
|
124
|
+
`ORDER_SHIPPING_RATE_UNAVAILABLE`, and the kit re-quotes the options.
|
|
125
|
+
|
|
126
|
+
On order pages, `deriveShipmentTracking(order)` builds the tracking view,
|
|
127
|
+
`canCustomerCancel(order)` follows the API's `can_cancel`, and
|
|
128
|
+
`isHandedToCarrier(order)` says whether the parcel has left the merchant.
|
|
129
|
+
`isCarrierShipment(order)` is false for a manual shipment (status `null`: show
|
|
130
|
+
only carrier and tracking number), and `shipmentEventLabel(event)` gives an
|
|
131
|
+
event's text with a neutral fallback.
|
|
50
132
|
|
|
51
133
|
## Metafields and metaobjects
|
|
52
134
|
|
package/dist/api/client.js
CHANGED
|
@@ -3,9 +3,28 @@ import {
|
|
|
3
3
|
isStoreSuspendedResponseBody,
|
|
4
4
|
STORE_SUSPENDED_REDIRECT_PATH
|
|
5
5
|
} from "../stores/store-suspension.js";
|
|
6
|
+
import {
|
|
7
|
+
isStoreComingSoonResponseBody,
|
|
8
|
+
STORE_COMING_SOON_REDIRECT_PATH
|
|
9
|
+
} from "../stores/store-coming-soon.js";
|
|
10
|
+
import {
|
|
11
|
+
skipsStorePreview,
|
|
12
|
+
STORE_PREVIEW_HEADER
|
|
13
|
+
} from "../stores/store-preview-cookie.js";
|
|
14
|
+
import {
|
|
15
|
+
currentStorePreviewToken,
|
|
16
|
+
isBrowserStorePreview,
|
|
17
|
+
requestStorePreviewRenewal
|
|
18
|
+
} from "./store-preview-header.js";
|
|
6
19
|
import { publicConfig } from "../config.js";
|
|
7
20
|
import { storeApiPath } from "../store-scope/index.js";
|
|
8
21
|
const DEFAULT_TIMEOUT = 1e4;
|
|
22
|
+
function comingSoonEndsThisVisit(method) {
|
|
23
|
+
if (!isBrowserStorePreview()) return true;
|
|
24
|
+
const verb = (method ?? "get").toUpperCase();
|
|
25
|
+
if (verb !== "GET" && verb !== "HEAD") return false;
|
|
26
|
+
return !requestStorePreviewRenewal();
|
|
27
|
+
}
|
|
9
28
|
class ApiClient {
|
|
10
29
|
axiosInstance;
|
|
11
30
|
withApiKey;
|
|
@@ -33,6 +52,10 @@ class ApiClient {
|
|
|
33
52
|
if (this.withApiKey && platformApiKey && !config.headers["x-storefront-api-key"]) {
|
|
34
53
|
config.headers["x-storefront-api-key"] = platformApiKey;
|
|
35
54
|
}
|
|
55
|
+
const previewToken = await currentStorePreviewToken();
|
|
56
|
+
if (previewToken && !skipsStorePreview(config) && !config.headers.get(STORE_PREVIEW_HEADER)) {
|
|
57
|
+
config.headers.set(STORE_PREVIEW_HEADER, previewToken);
|
|
58
|
+
}
|
|
36
59
|
return config;
|
|
37
60
|
},
|
|
38
61
|
(error) => {
|
|
@@ -44,7 +67,12 @@ class ApiClient {
|
|
|
44
67
|
return response;
|
|
45
68
|
},
|
|
46
69
|
(error) => {
|
|
47
|
-
console.error("API Client Error:",
|
|
70
|
+
console.error("API Client Error:", {
|
|
71
|
+
method: error.config?.method?.toUpperCase(),
|
|
72
|
+
url: error.config?.url,
|
|
73
|
+
status: error.response?.status,
|
|
74
|
+
code: error.response?.data?.code ?? error.code
|
|
75
|
+
});
|
|
48
76
|
if (error.code === "ECONNABORTED") {
|
|
49
77
|
error.message = "Request timeout - please try again";
|
|
50
78
|
} else if (!error.response) {
|
|
@@ -53,6 +81,9 @@ class ApiClient {
|
|
|
53
81
|
if (typeof window !== "undefined" && error.response?.status === 403 && isStoreSuspendedResponseBody(error.response?.data)) {
|
|
54
82
|
window.location.href = STORE_SUSPENDED_REDIRECT_PATH;
|
|
55
83
|
}
|
|
84
|
+
if (typeof window !== "undefined" && error.response?.status === 403 && isStoreComingSoonResponseBody(error.response?.data) && window.location.pathname !== STORE_COMING_SOON_REDIRECT_PATH && comingSoonEndsThisVisit(error.config?.method)) {
|
|
85
|
+
window.location.href = STORE_COMING_SOON_REDIRECT_PATH;
|
|
86
|
+
}
|
|
56
87
|
return Promise.reject(error);
|
|
57
88
|
}
|
|
58
89
|
);
|
package/dist/api/client.js.map
CHANGED
|
@@ -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 { publicConfig } from \"../config\";\nimport { storeApiPath } from \"../store-scope\";\n\nconst DEFAULT_TIMEOUT = 10000; // 10 seconds\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 // 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 console.error(\"API Client Error:\", error);\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 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,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAE7B,MAAM,kBAAkB;AAYxB,MAAM,UAA4C;AAAA,EACxC;AAAA,EACA;AAAA,EAER,YACE,UAAkB,aAAa,EAAE,QACjC,SACA;AACA,SAAK,aA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B,QAAI;AACF,YAAM,WAAW,MAAM,KAAK,cAAc,MAAS,KAAK,MAAM,MAAM;AACpE,aAAO,KAAK,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\";\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: 20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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":[]}
|
package/dist/api/proxy.js
CHANGED
|
@@ -11,6 +11,12 @@ import {
|
|
|
11
11
|
forwardingHeaders
|
|
12
12
|
} from "../auth/client-ip.js";
|
|
13
13
|
import { backendBaseUrl, createAuthApi, storefrontApiKey } from "../auth/sdk.js";
|
|
14
|
+
import { multiTenantStorePath } from "../store-scope/index.js";
|
|
15
|
+
import {
|
|
16
|
+
STORE_PREVIEW_HEADER,
|
|
17
|
+
STORE_PREVIEW_TOKEN_HEADER,
|
|
18
|
+
storePreviewTokenFrom
|
|
19
|
+
} from "../stores/store-preview-cookie.js";
|
|
14
20
|
const BLOCKED_REQUEST_HEADERS = /* @__PURE__ */ new Set([
|
|
15
21
|
"connection",
|
|
16
22
|
"keep-alive",
|
|
@@ -30,7 +36,9 @@ const BLOCKED_REQUEST_HEADERS = /* @__PURE__ */ new Set([
|
|
|
30
36
|
"x-forwarded-for",
|
|
31
37
|
"x-real-ip",
|
|
32
38
|
"cf-connecting-ip",
|
|
33
|
-
FORWARDER_SECRET_HEADER
|
|
39
|
+
FORWARDER_SECRET_HEADER,
|
|
40
|
+
STORE_PREVIEW_HEADER,
|
|
41
|
+
STORE_PREVIEW_TOKEN_HEADER
|
|
34
42
|
]);
|
|
35
43
|
const METHODS_WITH_BODY = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
36
44
|
function jsonError(status, message, code) {
|
|
@@ -54,7 +62,20 @@ function resolveTarget(segments, search) {
|
|
|
54
62
|
target.search = search;
|
|
55
63
|
return target;
|
|
56
64
|
}
|
|
57
|
-
function
|
|
65
|
+
function storePreviewTokenFor(request, storeRef) {
|
|
66
|
+
const stamped = request.nextUrl.pathname.startsWith(
|
|
67
|
+
`${multiTenantStorePath(storeRef)}/`
|
|
68
|
+
);
|
|
69
|
+
return storePreviewTokenFrom(
|
|
70
|
+
request.cookies,
|
|
71
|
+
stamped ? request : {
|
|
72
|
+
headers: {
|
|
73
|
+
get: (name) => name.toLowerCase() === STORE_PREVIEW_TOKEN_HEADER ? null : request.headers.get(name)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
function forwardedHeaders(request, storeRef, accessToken) {
|
|
58
79
|
const headers = new Headers();
|
|
59
80
|
request.headers.forEach((value, key) => {
|
|
60
81
|
if (!BLOCKED_REQUEST_HEADERS.has(key.toLowerCase())) {
|
|
@@ -67,13 +88,15 @@ function forwardedHeaders(request, accessToken) {
|
|
|
67
88
|
)) {
|
|
68
89
|
headers.set(key, value);
|
|
69
90
|
}
|
|
91
|
+
const previewToken = storePreviewTokenFor(request, storeRef);
|
|
92
|
+
if (previewToken) headers.set(STORE_PREVIEW_HEADER, previewToken);
|
|
70
93
|
if (accessToken) headers.set("authorization", `Bearer ${accessToken}`);
|
|
71
94
|
return headers;
|
|
72
95
|
}
|
|
73
|
-
async function callUpstream(request, target, body, accessToken) {
|
|
96
|
+
async function callUpstream(request, storeRef, target, body, accessToken) {
|
|
74
97
|
const response = await fetch(target, {
|
|
75
98
|
method: request.method,
|
|
76
|
-
headers: forwardedHeaders(request, accessToken),
|
|
99
|
+
headers: forwardedHeaders(request, storeRef, accessToken),
|
|
77
100
|
body,
|
|
78
101
|
cache: "no-store",
|
|
79
102
|
redirect: "manual"
|
|
@@ -105,6 +128,7 @@ async function handleBackendProxy(request, storeRef, segments) {
|
|
|
105
128
|
try {
|
|
106
129
|
result = await callUpstream(
|
|
107
130
|
request,
|
|
131
|
+
storeRef,
|
|
108
132
|
target,
|
|
109
133
|
body || void 0,
|
|
110
134
|
tokens?.access_token
|
|
@@ -124,6 +148,7 @@ async function handleBackendProxy(request, storeRef, segments) {
|
|
|
124
148
|
try {
|
|
125
149
|
retry = await callUpstream(
|
|
126
150
|
request,
|
|
151
|
+
storeRef,
|
|
127
152
|
target,
|
|
128
153
|
body || void 0,
|
|
129
154
|
refreshed.data.access_token
|
package/dist/api/proxy.js.map
CHANGED
|
@@ -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(\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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Q;AAAA,IACR;AAAA,IACA,kBAAkB,SAAS,QAAQ;AAAA,EACrC;AAEA,MAAI;AAEJ,MAAI;AACF,aAAS,MAAM;AAAA,MACb;AAAA,MACA;AAAA,MACA,QAAQ;AAAA,MACR,QAAQ;AAAA,IACV;AAAA,EACF,QAAQ;AACN,WAAO,UAAU,KAAK,2BAA2B,sBAAsB;AAAA,EACzE;AAIA,MAAI,OAAO,WAAW,OAAO,CAAC,OAAQ,QAAO,QAAQ,MAAM;AAG3D,QAAM,YAAY,MAAM;AAAA,IACtB;AAAA,IACA,aAAa,QAAQ,OAAO;AAAA,EAC9B,EAAE,QAAQ,OAAO,aAAa;AAe9B,MACE,CAAC,UAAU,WACX,CAAC,UAAU,MAAM,gBACjB,CAAC,UAAU,KAAK,eAChB;AACA,WAAO,QAAQ,MAAM;AAAA,EACvB;AAEA,MAAI;AAEJ,MAAI;AACF,YAAQ,MAAM;AAAA,MACZ;AAAA,MACA;AAAA,MACA,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
|
+
{"version":3,"sources":["../../src/api/proxy.ts"],"sourcesContent":["import \"server-only\";\n\nimport { NextResponse, type NextRequest } from \"next/server\";\n\nimport {\n authCookiePathFor,\n readAuthCookies,\n writeAuthCookies,\n} from \"../auth/cookies\";\nimport {\n clientIpFrom,\n FORWARDER_SECRET_HEADER,\n forwardingHeaders,\n} from \"../auth/client-ip\";\nimport { backendBaseUrl, createAuthApi, storefrontApiKey } from \"../auth/sdk\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport {\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewTokenFrom,\n} from \"../stores/store-preview-cookie\";\n\n/**\n * Same-origin server proxy for the storefront's authenticated backend calls.\n *\n * Session tokens live in httpOnly, store-scoped cookies (`lib/auth/cookies.ts`)\n * that browser JS cannot read, and the backend runs on a different origin, so a\n * direct browser->backend call carries neither cookie nor bearer token. The\n * browser therefore calls `/store/<storeRef>/api/backend/<path>` — same origin,\n * so the cookie is sent — and this handler, running on the server, attaches the\n * bearer token and the storefront API key before forwarding.\n *\n * This is the same shape as `lib/auth/route-handlers.ts`, which is why this\n * module is the third (and last) place allowed to touch auth cookies. It still\n * goes through `lib/auth/cookies.ts` rather than naming cookies itself.\n */\n\n/**\n * Never forwarded upstream:\n * - hop-by-hop headers (RFC 9110 s7.6.1) are per-connection by definition;\n * - `host`/`content-length`/`accept-encoding` are owned by `fetch`;\n * - `origin` describes the browser->proxy hop, not the proxy->backend one;\n * - `authorization` and `cookie` because the httpOnly cookie is the ONLY\n * trusted source of identity here — a browser-supplied `Authorization`\n * header must never reach the backend through this route;\n * - `x-storefront-api-key` because the server attaches its own;\n * - `x-forwarded-for` and `x-real-ip` because neither is a Fetch-forbidden\n * header name, so browser JS can set them — and the backend derives the\n * client IP from exactly those, for the auth throttle key and for API-key IP\n * allowlisting. They are dropped here and re-set below from the value the\n * platform edge gave *this* server. Block first, then set: the reverse order\n * would hand the choice back to the caller;\n * - `x-ecomweb-forwarder-secret` because it is what makes the backend trust\n * `x-forwarded-for`. Only this server attaches it, from a server-only env\n * var; a browser-supplied one must never pass through, least of all when\n * the var is unset here and nothing would overwrite it;\n * - `x-store-preview` and the middleware's internal store preview token\n * header, because the token sent upstream comes only from this request's\n * cookie or the middleware's stamp (`storePreviewTokenFor` below).\n */\nconst BLOCKED_REQUEST_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n \"content-length\",\n \"accept-encoding\",\n \"origin\",\n \"authorization\",\n \"cookie\",\n \"x-storefront-api-key\",\n \"x-forwarded-for\",\n \"x-real-ip\",\n \"cf-connecting-ip\",\n FORWARDER_SECRET_HEADER,\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n]);\n\nconst METHODS_WITH_BODY = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\nfunction jsonError(status: number, message: string, code: string) {\n return NextResponse.json({ code, message }, { status });\n}\n\n/**\n * Rebuilds the upstream URL from the catch-all segments. Next has already\n * percent-decoded them, so `..` arrives literally and is rejected here; the\n * origin/prefix check afterwards is the backstop that keeps this route from\n * becoming an open forward proxy.\n */\nfunction resolveTarget(segments: string[], search: string): URL | null {\n if (segments.length === 0) return null;\n\n for (const segment of segments) {\n if (\n segment === \"\" ||\n segment === \".\" ||\n segment === \"..\" ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\")\n ) {\n return null;\n }\n }\n\n const base = new URL(backendBaseUrl());\n const prefix = base.pathname.replace(/\\/$/, \"\");\n const target = new URL(\n `${prefix}/${segments.map(encodeURIComponent).join(\"/\")}`,\n base\n );\n\n if (target.origin !== base.origin) return null;\n if (!target.pathname.startsWith(`${prefix}/`)) return null;\n\n target.search = search;\n return target;\n}\n\n/**\n * The store preview token to send upstream as `X-Store-Preview`, or null:\n * a preview host's token the middleware stamped, else the store preview\n * cookie, else the theme preview cookie (`storePreviewTokenFrom`).\n *\n * The stamp is trusted only under `/store/<ref>/`: the middleware's matcher\n * covers that path, and every response there that reaches this route drops\n * a client's copy of the header first. Root `/api/*` (the single-store\n * proxy) is outside the matcher, so the header there is whatever the client\n * sent, and only the cookies count.\n */\nfunction storePreviewTokenFor(\n request: NextRequest,\n storeRef: string\n): string | null {\n const stamped = request.nextUrl.pathname.startsWith(\n `${multiTenantStorePath(storeRef)}/`\n );\n return storePreviewTokenFrom(\n request.cookies,\n stamped\n ? request\n : {\n headers: {\n get: name =>\n name.toLowerCase() === STORE_PREVIEW_TOKEN_HEADER\n ? null\n : request.headers.get(name),\n },\n }\n );\n}\n\nfunction forwardedHeaders(\n request: NextRequest,\n storeRef: string,\n accessToken?: string\n) {\n const headers = new Headers();\n\n request.headers.forEach((value, key) => {\n if (!BLOCKED_REQUEST_HEADERS.has(key.toLowerCase())) {\n headers.set(key, value);\n }\n });\n\n headers.set(\"x-storefront-api-key\", storefrontApiKey());\n\n // Set only after the blocklist has stripped whatever the browser sent.\n for (const [key, value] of Object.entries(\n forwardingHeaders(clientIpFrom(request.headers))\n )) {\n headers.set(key, value);\n }\n\n // Set only after the blocklist has dropped whatever the browser sent.\n const previewToken = storePreviewTokenFor(request, storeRef);\n if (previewToken) headers.set(STORE_PREVIEW_HEADER, previewToken);\n\n if (accessToken) headers.set(\"authorization\", `Bearer ${accessToken}`);\n\n return headers;\n}\n\ninterface UpstreamResult {\n status: number;\n body: string;\n contentType: string | null;\n}\n\nasync function callUpstream(\n request: NextRequest,\n storeRef: string,\n target: URL,\n body: string | undefined,\n accessToken?: string\n): Promise<UpstreamResult> {\n const response = await fetch(target, {\n method: request.method,\n headers: forwardedHeaders(request, storeRef, accessToken),\n body,\n cache: \"no-store\",\n redirect: \"manual\",\n });\n\n return {\n status: response.status,\n body: await response.text(),\n contentType: response.headers.get(\"content-type\"),\n };\n}\n\n/**\n * Passes the backend's status and body through untouched — callers read\n * `{ code, message }` off the body, so rewriting it would break their error\n * handling.\n */\nfunction respond(result: UpstreamResult): NextResponse {\n return new NextResponse(result.body || null, {\n status: result.status,\n headers: result.contentType\n ? { \"content-type\": result.contentType }\n : undefined,\n });\n}\n\nexport async function handleBackendProxy(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const target = resolveTarget(segments, request.nextUrl.search);\n\n if (!target) {\n return jsonError(400, \"Invalid proxy path\", \"PROXY_INVALID_PATH\");\n }\n\n // Buffered once so the 401 retry below can replay it.\n const body = METHODS_WITH_BODY.has(request.method)\n ? await request.text()\n : undefined;\n\n const tokens = readAuthCookies(\n request.cookies,\n storeRef,\n authCookiePathFor(request, storeRef)\n );\n\n let result: UpstreamResult;\n\n try {\n result = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n tokens?.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n // Anonymous callers and non-401 answers are done: public endpoints must keep\n // working through this proxy.\n if (result.status !== 401 || !tokens) return respond(result);\n\n // Exactly one refresh + retry. Never a loop.\n const refreshed = await createAuthApi(\n storeRef,\n clientIpFrom(request.headers)\n ).refresh(tokens.refresh_token);\n\n // A failed refresh does NOT clear the cookies, because \"failed\" and \"the\n // session is dead\" are not the same thing here. `SessionService.rotate()`\n // revokes the presented refresh token before issuing its replacement, so a\n // token can be rejected simply for having lost a race: `proxy.ts` refreshes\n // near-expiry tokens on every matched request, this route refreshes again on\n // a 401, and a page load fires several of both at once. Each of those reads\n // the refresh token from its own request snapshot, so whichever rotation\n // lands second presents an already-revoked token through no fault of the\n // shopper. Clearing here would log them out mid-page.\n //\n // Leaving stale cookies in place is safe: the `(protected)` layout resolves\n // the session server-side on the next navigation and redirects to /login if\n // it really is gone, and signing in overwrites them.\n if (\n !refreshed.success ||\n !refreshed.data?.access_token ||\n !refreshed.data.refresh_token\n ) {\n return respond(result);\n }\n\n let retry: UpstreamResult;\n\n try {\n retry = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n refreshed.data.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n const response = respond(retry);\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: refreshed.data.access_token,\n refresh_token: refreshed.data.refresh_token,\n },\n authCookiePathFor(request, storeRef)\n );\n\n return response;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,oBAAsC;AAE/C;AAAA,EACE;AAA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A;AAAA,IACA;AAAA,MACE,cAAc,UAAU,KAAK;AAAA,MAC7B,eAAe,UAAU,KAAK;AAAA,IAChC;AAAA,IACA,kBAAkB,SAAS,QAAQ;AAAA,EACrC;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { storePreviewTokenFrom } from "../stores/store-preview-cookie.js";
|
|
2
|
+
let browserToken = null;
|
|
3
|
+
function setBrowserStorePreviewToken(token) {
|
|
4
|
+
if (typeof window === "undefined") return;
|
|
5
|
+
browserToken = token;
|
|
6
|
+
}
|
|
7
|
+
function isBrowserStorePreview() {
|
|
8
|
+
return typeof window !== "undefined" && browserToken !== null;
|
|
9
|
+
}
|
|
10
|
+
let renewer = null;
|
|
11
|
+
let lastRenewalAt = null;
|
|
12
|
+
const RENEWAL_THROTTLE_MS = 6e4;
|
|
13
|
+
function setStorePreviewRenewer(renew) {
|
|
14
|
+
renewer = renew;
|
|
15
|
+
lastRenewalAt = null;
|
|
16
|
+
}
|
|
17
|
+
function requestStorePreviewRenewal() {
|
|
18
|
+
if (!renewer) return false;
|
|
19
|
+
const now = Date.now();
|
|
20
|
+
if (lastRenewalAt === null || now - lastRenewalAt >= RENEWAL_THROTTLE_MS) {
|
|
21
|
+
lastRenewalAt = now;
|
|
22
|
+
renewer();
|
|
23
|
+
}
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
async function currentStorePreviewToken() {
|
|
27
|
+
if (typeof window !== "undefined") return browserToken;
|
|
28
|
+
try {
|
|
29
|
+
const { cookies, headers } = await import("next/headers");
|
|
30
|
+
return storePreviewTokenFrom(await cookies(), { headers: await headers() });
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export {
|
|
36
|
+
currentStorePreviewToken,
|
|
37
|
+
isBrowserStorePreview,
|
|
38
|
+
requestStorePreviewRenewal,
|
|
39
|
+
setBrowserStorePreviewToken,
|
|
40
|
+
setStorePreviewRenewer
|
|
41
|
+
};
|
|
42
|
+
//# sourceMappingURL=store-preview-header.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/api/store-preview-header.ts"],"sourcesContent":["import { storePreviewTokenFrom } from \"../stores/store-preview-cookie\";\n\n/**\n * The browser's store preview token, which the layout hands over through\n * `StorefrontKitProvider` (see `storePreviewToken` there). Module-level: one\n * browser tab is one store. It stays set after the store opens until the\n * next layout render passes null (a reload); accepted: an open store needs\n * no token, so the API's answers do not change, only the kit's preview\n * cues lag in a tab left open across the opening.\n */\nlet browserToken: string | null = null;\n\n/**\n * Sets the token the browser's kit clients send as `X-Store-Preview`. Does\n * nothing on the server: a server module is shared by every request, so a\n * value set there would reach other shoppers.\n */\nexport function setBrowserStorePreviewToken(token: string | null): void {\n if (typeof window === \"undefined\") return;\n browserToken = token;\n}\n\n/**\n * True in the browser while a store preview token is set: the shopper is a\n * previewer, and the API refuses every write. The cart and checkout check\n * this to refuse a write without sending it.\n */\nexport function isBrowserStorePreview(): boolean {\n return typeof window !== \"undefined\" && browserToken !== null;\n}\n\n/**\n * Fetches a fresh preview token, set by `StorefrontKitProvider` only on a\n * theme preview host, whose token lasts 1 h (the app re-renders the layout,\n * which hands the new token over). A link preview's 24 h cookie has none.\n */\nlet renewer: (() => void) | null = null;\nlet lastRenewalAt: number | null = null;\n\n/** The shortest gap between two renewals a 403 asks for. */\nconst RENEWAL_THROTTLE_MS = 60_000;\n\n/** Sets or clears the renewer; a new one may renew at once. */\nexport function setStorePreviewRenewer(renew: (() => void) | null): void {\n renewer = renew;\n lastRenewalAt = null;\n}\n\n/**\n * Asks for a fresh preview token after a read was refused with\n * `STORE_COMING_SOON`. False when there is no renewer: the preview is over.\n * Otherwise true, and the renewer runs at most once per minute, so a page\n * whose reads all fail together renews once.\n */\nexport function requestStorePreviewRenewal(): boolean {\n if (!renewer) return false;\n const now = Date.now();\n if (lastRenewalAt === null || now - lastRenewalAt >= RENEWAL_THROTTLE_MS) {\n lastRenewalAt = now;\n renewer();\n }\n return true;\n}\n\n/**\n * The token this call should send as `X-Store-Preview`, or null. In the\n * browser, the one the layout handed over. On the server, the request's own\n * (`storePreviewTokenFrom`: a preview host's stamped token, else the store\n * preview cookie, else the theme preview cookie). Outside a request scope\n * (build time), `next/headers` throws and this is null.\n *\n * In the middleware it does not throw: Next 16 runs the middleware inside a\n * request store, so `next/headers` is the middleware's own incoming\n * request, before any sanitising, and this returns whatever token the\n * client sent, a forged `STORE_PREVIEW_TOKEN_HEADER` included. So every SDK\n * call the middleware makes must pass `SKIP_STORE_PREVIEW` or an explicit\n * `X-Store-Preview` header (as getStoreByHost, lookupRedirect and\n * getStoreSubdomain do).\n */\nexport async function currentStorePreviewToken(): Promise<string | null> {\n if (typeof window !== \"undefined\") return browserToken;\n try {\n // Imported lazily: this module is in the browser bundle too (as in\n // api/server-client.ts).\n const { cookies, headers } = await import(\"next/headers\");\n return storePreviewTokenFrom(await cookies(), { headers: await headers() });\n } catch {\n return null;\n }\n}\n"],"mappings":"AAAA,SAAS,6BAA6B;AAUtC,IAAI,eAA8B;AAO3B,SAAS,4BAA4B,OAA4B;AACtE,MAAI,OAAO,WAAW,YAAa;AACnC,iBAAe;AACjB;AAOO,SAAS,wBAAiC;AAC/C,SAAO,OAAO,WAAW,eAAe,iBAAiB;AAC3D;AAOA,IAAI,UAA+B;AACnC,IAAI,gBAA+B;AAGnC,MAAM,sBAAsB;AAGrB,SAAS,uBAAuB,OAAkC;AACvE,YAAU;AACV,kBAAgB;AAClB;AAQO,SAAS,6BAAsC;AACpD,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,kBAAkB,QAAQ,MAAM,iBAAiB,qBAAqB;AACxE,oBAAgB;AAChB,YAAQ;AAAA,EACV;AACA,SAAO;AACT;AAiBA,eAAsB,2BAAmD;AACvE,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI;AAGF,UAAM,EAAE,SAAS,QAAQ,IAAI,MAAM,OAAO,cAAc;AACxD,WAAO,sBAAsB,MAAM,QAAQ,GAAG,EAAE,SAAS,MAAM,QAAQ,EAAE,CAAC;AAAA,EAC5E,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/auth/error-copy.js
CHANGED
|
@@ -17,7 +17,11 @@ const ERROR_COPY = {
|
|
|
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
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
|
+
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.",
|
|
21
|
+
SHIPPING_QUOTE_CHANGED: "Ph\xED v\u1EADn chuy\u1EC3n \u0111\xE3 thay \u0111\u1ED5i. Vui l\xF2ng ki\u1EC3m tra l\u1EA1i r\u1ED3i \u0111\u1EB7t h\xE0ng.",
|
|
22
|
+
ORDER_SHIPPING_RATE_UNAVAILABLE: "Ph\u01B0\u01A1ng th\u1EE9c v\u1EADn chuy\u1EC3n \u0111\xE3 ch\u1ECDn kh\xF4ng c\xF2n kh\u1EA3 d\u1EE5ng. Vui l\xF2ng ch\u1ECDn l\u1EA1i.",
|
|
23
|
+
ORDER_CANCEL_BLOCKED_BY_SHIPMENT: "\u0110\u01A1n \u0111\xE3 \u0111\u01B0\u1EE3c giao cho h\xE3ng v\u1EADn chuy\u1EC3n, kh\xF4ng th\u1EC3 hu\u1EF7. Vui l\xF2ng li\xEAn h\u1EC7 c\u1EEDa h\xE0ng.",
|
|
24
|
+
STORE_COMING_SOON: "C\u1EEDa h\xE0ng ch\u01B0a m\u1EDF c\u1EEDa n\xEAn ch\u01B0a th\u1EC3 th\u1EF1c hi\u1EC7n thao t\xE1c n\xE0y."
|
|
21
25
|
};
|
|
22
26
|
const STATUS_COPY = {
|
|
23
27
|
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 * - `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;
|
|
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 * - `SHIPPING_QUOTE_CHANGED` and `ORDER_SHIPPING_RATE_UNAVAILABLE`:\n * `SHIPPING_ERROR_CODES` in `@ecomweb/sdk`, returned by order creation\n * when the carrier's price moved since the quote (409, `details.options`\n * holds the new ones; `useCheckout` handles it as `quote_changed`) or the\n * chosen rate can no longer be quoted.\n * - `ORDER_CANCEL_BLOCKED_BY_SHIPMENT`: `ORDER_SHIPMENT_ERROR_CODES` in\n * `@ecomweb/sdk`, returned when a customer cancels an order whose carrier\n * shipment is already in progress.\n * - `STORE_COMING_SOON`: `src/modules/tenant/domain/services/store-access.ts`,\n * the 403 for a store its merchant has not opened yet (details\n * `{ name }`), applied by `StorefrontApiKeyGuard`. A preview token opens\n * only GET and HEAD, so in a preview every write gets it: customer\n * sign-in and sign-up, reviews, blog comments.\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 SHIPPING_QUOTE_CHANGED:\n \"Phí vận chuyển đã thay đổi. Vui lòng kiểm tra lại rồi đặt hàng.\",\n ORDER_SHIPPING_RATE_UNAVAILABLE:\n \"Phương thức vận chuyển đã chọn không còn khả dụng. Vui lòng chọn lại.\",\n ORDER_CANCEL_BLOCKED_BY_SHIPMENT:\n \"Đơn đã được giao cho hãng vận chuyển, không thể huỷ. Vui lòng liên hệ cửa hàng.\",\n STORE_COMING_SOON:\n \"Cửa hàng chưa mở cửa nên chưa thể thực hiện thao tác này.\",\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;AAsClC,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;AAAA,EACF,wBACE;AAAA,EACF,iCACE;AAAA,EACF,kCACE;AAAA,EACF,mBACE;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":[]}
|
|
@@ -8,6 +8,7 @@ import { forwardedForHeader } from "./client-ip.js";
|
|
|
8
8
|
import { publicConfig } from "../config/public.js";
|
|
9
9
|
import { serverConfig } from "../config/server.js";
|
|
10
10
|
import { THEME_PREVIEW_HOST_HEADER } from "../theme/preview-host.js";
|
|
11
|
+
import { STORE_PREVIEW_TOKEN_HEADER } from "../stores/store-preview-cookie.js";
|
|
11
12
|
const REFRESH_WINDOW_SECONDS = 120;
|
|
12
13
|
const REFRESH_FETCH_TIMEOUT_MS = 2500;
|
|
13
14
|
function expiresWithin(token, seconds) {
|
|
@@ -67,6 +68,7 @@ function downstreamRequestHeaders(req, hostMapped, storeRef, rotated) {
|
|
|
67
68
|
const headers = new Headers(req.headers);
|
|
68
69
|
headers.set(HOST_MAPPED_HEADER, hostMapped ? "1" : "0");
|
|
69
70
|
headers.delete(THEME_PREVIEW_HOST_HEADER);
|
|
71
|
+
headers.delete(STORE_PREVIEW_TOKEN_HEADER);
|
|
70
72
|
if (rotated && storeRef) {
|
|
71
73
|
const jar = new Map(req.cookies.getAll().map((c) => [c.name, c.value]));
|
|
72
74
|
const path = authCookiePath(storeRef, hostMapped);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/auth/session-refresh.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\nimport {\n accessCookieName,\n authCookiePath,\n refreshCookieName,\n HOST_MAPPED_HEADER,\n} from \"./cookies\";\nimport { forwardedForHeader } from \"./client-ip\";\nimport { publicConfig } from \"../config/public\";\nimport { serverConfig } from \"../config/server\";\nimport { THEME_PREVIEW_HOST_HEADER } from \"../theme/preview-host\";\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;
|
|
1
|
+
{"version":3,"sources":["../../src/auth/session-refresh.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\nimport {\n accessCookieName,\n authCookiePath,\n refreshCookieName,\n HOST_MAPPED_HEADER,\n} from \"./cookies\";\nimport { forwardedForHeader } from \"./client-ip\";\nimport { publicConfig } from \"../config/public\";\nimport { serverConfig } from \"../config/server\";\nimport { THEME_PREVIEW_HOST_HEADER } from \"../theme/preview-host\";\nimport { STORE_PREVIEW_TOKEN_HEADER } from \"../stores/store-preview-cookie\";\n\n/**\n * Session upkeep shared by both middleware modes (createStorefrontMiddleware):\n * refresh a near-expiry access token, and pass the downstream render the\n * rotated tokens plus the host-mapped stamp.\n */\n\nconst REFRESH_WINDOW_SECONDS = 120;\nconst REFRESH_FETCH_TIMEOUT_MS = 2500;\n\nexport interface RotatedTokens {\n access_token: string;\n refresh_token: string;\n}\n\n/**\n * Reads `exp` without verifying the signature — the API verifies. This only\n * decides whether to refresh early, so a forged token gains nothing: it still\n * fails at the API.\n */\nexport function expiresWithin(token: string, seconds: number): boolean {\n try {\n const payload = JSON.parse(\n Buffer.from(token.split(\".\")[1], \"base64\").toString(\"utf8\")\n );\n if (typeof payload.exp !== \"number\") return false;\n return payload.exp - Math.floor(Date.now() / 1000) < seconds;\n } catch {\n return false;\n }\n}\n\n/**\n * Proactively refresh a near-expiry access token so requests don't hit a 401\n * on it. Returns the rotated pair, or null if there was nothing to do or the\n * attempt failed — a failed refresh is non-fatal and the request proceeds on\n * the old token, letting the 401 paths handle it.\n *\n * This runs for **every** request the matcher admits, not just host-mapped\n * ones: the server-rendered pages read the session straight off the cookie\n * (`lib/auth/session.ts`) and have no other way to renew it. Part A's backend\n * proxy refreshes on a 401, but that only covers browser-initiated calls.\n * `cookiePath` is the session cookies' path (authCookiePath).\n */\nexport async function refreshIfNearExpiry(\n req: NextRequest,\n storeRef: string,\n cookiePath: string\n): Promise<RotatedTokens | null> {\n const access = req.cookies.get(accessCookieName(storeRef, cookiePath))?.value;\n const refresh = req.cookies.get(\n refreshCookieName(storeRef, cookiePath)\n )?.value;\n\n if (!access || !refresh) return null;\n if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;\n\n try {\n const res = await fetch(\n `${publicConfig().apiUrl}/public/stores/${encodeURIComponent(storeRef)}/auth/refresh`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": serverConfig().platformApiKey,\n // The backend throttles per `storeId:clientIp`; without this (the\n // shopper IP plus the forwarder secret that makes the backend\n // believe it) every shopper's refresh lands in one store-wide bucket.\n ...forwardedForHeader(req.headers),\n },\n body: JSON.stringify({ refresh_token: refresh }),\n // This is a latency budget added to a page load the user did not\n // ask for, not an API call worth waiting out — bound it so a slow\n // (not down) API can't turn a fast page load into a stall. An\n // abort rejects `fetch`, which the surrounding catch below\n // treats the same as any other network failure: non-fatal,\n // the request proceeds on the old token.\n signal: AbortSignal.timeout(REFRESH_FETCH_TIMEOUT_MS),\n }\n );\n\n if (!res.ok) return null;\n\n const data = await res.json();\n if (data?.access_token && data?.refresh_token) {\n return {\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n };\n }\n } catch {\n // Non-fatal: proceed on the old token, the normal 401 path handles it.\n }\n\n return null;\n}\n\n/**\n * The request headers every downstream render and route handler sees.\n *\n * Two jobs:\n *\n * 1. `HOST_MAPPED_HEADER` records whether the **Host** named the store. This\n * middleware is the only place that resolves Host → store, and the auth\n * route handler needs the answer to choose the cookie `path` and to know\n * where the store's own root is — it cannot tell the deployments apart from\n * the request path, which is `/store/<ref>/api/…` on both. Always set, so a\n * browser-supplied value can never survive.\n * 2. When a token was rotated, the new pair replaces the old one in the cookie\n * header, so the render *this* request triggers already sees the new\n * session. Without it a shopper returning after their access token expired\n * would be bounced to `/login` on the very request that renewed it.\n */\nexport function downstreamRequestHeaders(\n req: NextRequest,\n hostMapped: boolean,\n storeRef: string | null,\n rotated: RotatedTokens | null\n): Headers {\n const headers = new Headers(req.headers);\n headers.set(HOST_MAPPED_HEADER, hostMapped ? \"1\" : \"0\");\n // Only the middleware names a preview host's theme (theme/preview-host).\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n // Only the middleware hands on a preview host's store preview token; a\n // copy the client sent never survives (stores/store-preview-cookie).\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n\n if (rotated && storeRef) {\n const jar = new Map(req.cookies.getAll().map(c => [c.name, c.value]));\n const path = authCookiePath(storeRef, hostMapped);\n jar.set(accessCookieName(storeRef, path), rotated.access_token);\n jar.set(refreshCookieName(storeRef, path), rotated.refresh_token);\n headers.set(\n \"cookie\",\n [...jar].map(([name, value]) => `${name}=${value}`).join(\"; \")\n );\n }\n\n return headers;\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BA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AAI,KAAK;AAC5B,QAAI,MAAM,gBAAgB,MAAM,eAAe;AAC7C,aAAO;AAAA,QACL,cAAc,KAAK;AAAA,QACnB,eAAe,KAAK;AAAA,MACtB;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO;AACT;AAkBO,SAAS,yBACd,KACA,YACA,UACA,SACS;AACT,QAAM,UAAU,IAAI,QAAQ,IAAI,OAAO;AACvC,UAAQ,IAAI,oBAAoB,aAAa,MAAM,GAAG;AAEtD,UAAQ,OAAO,yBAAyB;AAGxC,UAAQ,OAAO,0BAA0B;AAEzC,MAAI,WAAW,UAAU;AACvB,UAAM,MAAM,IAAI,IAAI,IAAI,QAAQ,OAAO,EAAE,IAAI,OAAK,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AACpE,UAAM,OAAO,eAAe,UAAU,UAAU;AAChD,QAAI,IAAI,iBAAiB,UAAU,IAAI,GAAG,QAAQ,YAAY;AAC9D,QAAI,IAAI,kBAAkB,UAAU,IAAI,GAAG,QAAQ,aAAa;AAChE,YAAQ;AAAA,MACN;AAAA,MACA,CAAC,GAAG,GAAG,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,KAAK,EAAE,EAAE,KAAK,IAAI;AAAA,IAC/D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -8,6 +8,8 @@ import {
|
|
|
8
8
|
useCallback
|
|
9
9
|
} from "react";
|
|
10
10
|
import { useNotify } from "../notices.js";
|
|
11
|
+
import { isBrowserStorePreview } from "../api/store-preview-header.js";
|
|
12
|
+
import { STORE_PREVIEW_READ_ONLY_NOTICE } from "../stores/store-preview-guard.js";
|
|
11
13
|
import { cartApiService } from "./api.js";
|
|
12
14
|
const cartReducer = (state, action) => {
|
|
13
15
|
switch (action.type) {
|
|
@@ -110,6 +112,10 @@ function CartProvider({
|
|
|
110
112
|
loadCart();
|
|
111
113
|
}, [loadCart]);
|
|
112
114
|
const addItem = async (item) => {
|
|
115
|
+
if (isBrowserStorePreview()) {
|
|
116
|
+
notify(STORE_PREVIEW_READ_ONLY_NOTICE);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
113
119
|
if (!storeRef) return;
|
|
114
120
|
try {
|
|
115
121
|
await cartApiService.addToCart(
|
|
@@ -140,6 +146,10 @@ function CartProvider({
|
|
|
140
146
|
}
|
|
141
147
|
};
|
|
142
148
|
const reorderItems = async (items) => {
|
|
149
|
+
if (isBrowserStorePreview()) {
|
|
150
|
+
notify(STORE_PREVIEW_READ_ONLY_NOTICE);
|
|
151
|
+
return { added: 0, total: items.length };
|
|
152
|
+
}
|
|
143
153
|
if (!storeRef) return { added: 0, total: items.length };
|
|
144
154
|
let added = 0;
|
|
145
155
|
for (const item of items) {
|
|
@@ -162,6 +172,10 @@ function CartProvider({
|
|
|
162
172
|
return { added, total: items.length };
|
|
163
173
|
};
|
|
164
174
|
const removeItem = async (id) => {
|
|
175
|
+
if (isBrowserStorePreview()) {
|
|
176
|
+
notify(STORE_PREVIEW_READ_ONLY_NOTICE);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
165
179
|
if (!storeRef) return;
|
|
166
180
|
const item = state.items.find((item2) => item2.id === id);
|
|
167
181
|
try {
|
|
@@ -187,6 +201,10 @@ function CartProvider({
|
|
|
187
201
|
}
|
|
188
202
|
};
|
|
189
203
|
const updateQuantity = async (id, quantity) => {
|
|
204
|
+
if (isBrowserStorePreview()) {
|
|
205
|
+
notify(STORE_PREVIEW_READ_ONLY_NOTICE);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
190
208
|
if (!storeRef) return;
|
|
191
209
|
try {
|
|
192
210
|
await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);
|
|
@@ -202,6 +220,10 @@ function CartProvider({
|
|
|
202
220
|
}
|
|
203
221
|
};
|
|
204
222
|
const clearCart = async (notifyCleared = true) => {
|
|
223
|
+
if (isBrowserStorePreview()) {
|
|
224
|
+
notify(STORE_PREVIEW_READ_ONLY_NOTICE);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
205
227
|
if (!storeRef) return;
|
|
206
228
|
try {
|
|
207
229
|
await cartApiService.clearCart(storeRef, isAuth);
|
|
@@ -228,6 +250,10 @@ function CartProvider({
|
|
|
228
250
|
await loadCart();
|
|
229
251
|
};
|
|
230
252
|
const mergeCarts = async (_userId) => {
|
|
253
|
+
if (isBrowserStorePreview()) {
|
|
254
|
+
notify(STORE_PREVIEW_READ_ONLY_NOTICE);
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
231
257
|
if (!storeRef || !state.sessionId) return;
|
|
232
258
|
try {
|
|
233
259
|
await cartApiService.mergeCarts(storeRef);
|