@ecomweb/storefront-kit 0.12.1 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api/proxy.js CHANGED
@@ -169,6 +169,7 @@ async function handleBackendProxy(request, storeRef, segments) {
169
169
  return response;
170
170
  }
171
171
  export {
172
- handleBackendProxy
172
+ handleBackendProxy,
173
+ storePreviewTokenFor
173
174
  };
174
175
  //# sourceMappingURL=proxy.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/proxy.ts"],"sourcesContent":["import \"server-only\";\n\nimport { NextResponse, type NextRequest } from \"next/server\";\n\nimport {\n authCookiePathFor,\n readAuthCookies,\n writeAuthCookies,\n} from \"../auth/cookies\";\nimport {\n clientIpFrom,\n FORWARDER_SECRET_HEADER,\n forwardingHeaders,\n} from \"../auth/client-ip\";\nimport { backendBaseUrl, createAuthApi, storefrontApiKey } from \"../auth/sdk\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport {\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewTokenFrom,\n} from \"../stores/store-preview-cookie\";\n\n/**\n * Same-origin server proxy for the storefront's authenticated backend calls.\n *\n * Session tokens live in httpOnly, store-scoped cookies (`lib/auth/cookies.ts`)\n * that browser JS cannot read, and the backend runs on a different origin, so a\n * direct browser->backend call carries neither cookie nor bearer token. The\n * browser therefore calls `/store/<storeRef>/api/backend/<path>` — same origin,\n * so the cookie is sent — and this handler, running on the server, attaches the\n * bearer token and the storefront API key before forwarding.\n *\n * This is the same shape as `lib/auth/route-handlers.ts`, which is why this\n * module is the third (and last) place allowed to touch auth cookies. It still\n * goes through `lib/auth/cookies.ts` rather than naming cookies itself.\n */\n\n/**\n * Never forwarded upstream:\n * - hop-by-hop headers (RFC 9110 s7.6.1) are per-connection by definition;\n * - `host`/`content-length`/`accept-encoding` are owned by `fetch`;\n * - `origin` describes the browser->proxy hop, not the proxy->backend one;\n * - `authorization` and `cookie` because the httpOnly cookie is the ONLY\n * trusted source of identity here — a browser-supplied `Authorization`\n * header must never reach the backend through this route;\n * - `x-storefront-api-key` because the server attaches its own;\n * - `x-forwarded-for` and `x-real-ip` because neither is a Fetch-forbidden\n * header name, so browser JS can set them — and the backend derives the\n * client IP from exactly those, for the auth throttle key and for API-key IP\n * allowlisting. They are dropped here and re-set below from the value the\n * platform edge gave *this* server. Block first, then set: the reverse order\n * would hand the choice back to the caller;\n * - `x-ecomweb-forwarder-secret` because it is what makes the backend trust\n * `x-forwarded-for`. Only this server attaches it, from a server-only env\n * var; a browser-supplied one must never pass through, least of all when\n * the var is unset here and nothing would overwrite it;\n * - `x-store-preview` and the middleware's internal store preview token\n * header, because the token sent upstream comes only from this request's\n * cookie or the middleware's stamp (`storePreviewTokenFor` below).\n */\nconst BLOCKED_REQUEST_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n \"content-length\",\n \"accept-encoding\",\n \"origin\",\n \"authorization\",\n \"cookie\",\n \"x-storefront-api-key\",\n \"x-forwarded-for\",\n \"x-real-ip\",\n \"cf-connecting-ip\",\n FORWARDER_SECRET_HEADER,\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n]);\n\nconst METHODS_WITH_BODY = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\nfunction jsonError(status: number, message: string, code: string) {\n return NextResponse.json({ code, message }, { status });\n}\n\n/**\n * Rebuilds the upstream URL from the catch-all segments. Next has already\n * percent-decoded them, so `..` arrives literally and is rejected here; the\n * origin/prefix check afterwards is the backstop that keeps this route from\n * becoming an open forward proxy.\n */\nfunction resolveTarget(segments: string[], search: string): URL | null {\n if (segments.length === 0) return null;\n\n for (const segment of segments) {\n if (\n segment === \"\" ||\n segment === \".\" ||\n segment === \"..\" ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\")\n ) {\n return null;\n }\n }\n\n const base = new URL(backendBaseUrl());\n const prefix = base.pathname.replace(/\\/$/, \"\");\n const target = new URL(\n `${prefix}/${segments.map(encodeURIComponent).join(\"/\")}`,\n base\n );\n\n if (target.origin !== base.origin) return null;\n if (!target.pathname.startsWith(`${prefix}/`)) return null;\n\n target.search = search;\n return target;\n}\n\n/**\n * The store preview token to send upstream as `X-Store-Preview`, or null:\n * a preview host's token the middleware stamped, else the store preview\n * cookie, else the theme preview cookie (`storePreviewTokenFrom`).\n *\n * The stamp is trusted only under `/store/<ref>/`: the middleware's matcher\n * covers that path, and every response there that reaches this route drops\n * a client's copy of the header first. Root `/api/*` (the single-store\n * proxy) is outside the matcher, so the header there is whatever the client\n * sent, and only the cookies count.\n */\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;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,eAAe,wBAAwB;AAChE,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAwCP,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,MAAM,oBAAoB,oBAAI,IAAI,CAAC,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAEpE,SAAS,UAAU,QAAgB,SAAiB,MAAc;AAChE,SAAO,aAAa,KAAK,EAAE,MAAM,QAAQ,GAAG,EA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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;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 */\nexport function storePreviewTokenFor(\n request: NextRequest,\n storeRef: string\n): string | null {\n const stamped = request.nextUrl.pathname.startsWith(\n `${multiTenantStorePath(storeRef)}/`\n );\n return storePreviewTokenFrom(\n request.cookies,\n stamped\n ? request\n : {\n headers: {\n get: name =>\n name.toLowerCase() === STORE_PREVIEW_TOKEN_HEADER\n ? null\n : request.headers.get(name),\n },\n }\n );\n}\n\nfunction forwardedHeaders(\n request: NextRequest,\n storeRef: string,\n accessToken?: string\n) {\n const headers = new Headers();\n\n request.headers.forEach((value, key) => {\n if (!BLOCKED_REQUEST_HEADERS.has(key.toLowerCase())) {\n headers.set(key, value);\n }\n });\n\n headers.set(\"x-storefront-api-key\", storefrontApiKey());\n\n // Set only after the blocklist has stripped whatever the browser sent.\n for (const [key, value] of Object.entries(\n forwardingHeaders(clientIpFrom(request.headers))\n )) {\n headers.set(key, value);\n }\n\n // Set only after the blocklist has dropped whatever the browser sent.\n const previewToken = storePreviewTokenFor(request, storeRef);\n if (previewToken) headers.set(STORE_PREVIEW_HEADER, previewToken);\n\n if (accessToken) headers.set(\"authorization\", `Bearer ${accessToken}`);\n\n return headers;\n}\n\ninterface UpstreamResult {\n status: number;\n body: string;\n contentType: string | null;\n}\n\nasync function callUpstream(\n request: NextRequest,\n storeRef: string,\n target: URL,\n body: string | undefined,\n accessToken?: string\n): Promise<UpstreamResult> {\n const response = await fetch(target, {\n method: request.method,\n headers: forwardedHeaders(request, storeRef, accessToken),\n body,\n cache: \"no-store\",\n redirect: \"manual\",\n });\n\n return {\n status: response.status,\n body: await response.text(),\n contentType: response.headers.get(\"content-type\"),\n };\n}\n\n/**\n * Passes the backend's status and body through untouched — callers read\n * `{ code, message }` off the body, so rewriting it would break their error\n * handling.\n */\nfunction respond(result: UpstreamResult): NextResponse {\n return new NextResponse(result.body || null, {\n status: result.status,\n headers: result.contentType\n ? { \"content-type\": result.contentType }\n : undefined,\n });\n}\n\nexport async function handleBackendProxy(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const target = resolveTarget(segments, request.nextUrl.search);\n\n if (!target) {\n return jsonError(400, \"Invalid proxy path\", \"PROXY_INVALID_PATH\");\n }\n\n // Buffered once so the 401 retry below can replay it.\n const body = METHODS_WITH_BODY.has(request.method)\n ? await request.text()\n : undefined;\n\n const tokens = readAuthCookies(\n request.cookies,\n storeRef,\n authCookiePathFor(request, storeRef)\n );\n\n let result: UpstreamResult;\n\n try {\n result = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n tokens?.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n // Anonymous callers and non-401 answers are done: public endpoints must keep\n // working through this proxy.\n if (result.status !== 401 || !tokens) return respond(result);\n\n // Exactly one refresh + retry. Never a loop.\n const refreshed = await createAuthApi(\n storeRef,\n clientIpFrom(request.headers)\n ).refresh(tokens.refresh_token);\n\n // A failed refresh does NOT clear the cookies, because \"failed\" and \"the\n // session is dead\" are not the same thing here. `SessionService.rotate()`\n // revokes the presented refresh token before issuing its replacement, so a\n // token can be rejected simply for having lost a race: `proxy.ts` refreshes\n // near-expiry tokens on every matched request, this route refreshes again on\n // a 401, and a page load fires several of both at once. Each of those reads\n // the refresh token from its own request snapshot, so whichever rotation\n // lands second presents an already-revoked token through no fault of the\n // shopper. Clearing here would log them out mid-page.\n //\n // Leaving stale cookies in place is safe: the `(protected)` layout resolves\n // the session server-side on the next navigation and redirects to /login if\n // it really is gone, and signing in overwrites them.\n if (\n !refreshed.success ||\n !refreshed.data?.access_token ||\n !refreshed.data.refresh_token\n ) {\n return respond(result);\n }\n\n let retry: UpstreamResult;\n\n try {\n retry = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n refreshed.data.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n const response = respond(retry);\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: refreshed.data.access_token,\n refresh_token: refreshed.data.refresh_token,\n },\n authCookiePathFor(request, storeRef)\n );\n\n return response;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,oBAAsC;AAE/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,eAAe,wBAAwB;AAChE,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AA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,6 +51,38 @@ function clearOAuthNonceCookie(response, storeRef, path) {
51
51
  maxAge: 0
52
52
  });
53
53
  }
54
+ const EMAIL_BINDING_COOKIE_SUFFIX = {
55
+ "verify-email": "vb",
56
+ "change-email": "cb"
57
+ };
58
+ const EMAIL_BINDING_MAX_AGE_SECONDS = {
59
+ "verify-email": 86400,
60
+ "change-email": 3600
61
+ };
62
+ function emailBindingCookieName(purpose, storeRef, path) {
63
+ return hostOnlyCookieName(
64
+ `ecomweb_sf_${storeRef}_${EMAIL_BINDING_COOKIE_SUFFIX[purpose]}`,
65
+ path
66
+ );
67
+ }
68
+ function writeEmailBindingCookie(response, purpose, storeRef, binding, path) {
69
+ response.cookies.set(
70
+ emailBindingCookieName(purpose, storeRef, path),
71
+ binding,
72
+ {
73
+ ...baseOptions(),
74
+ path,
75
+ maxAge: EMAIL_BINDING_MAX_AGE_SECONDS[purpose]
76
+ }
77
+ );
78
+ }
79
+ function clearEmailBindingCookie(response, purpose, storeRef, path) {
80
+ response.cookies.set(emailBindingCookieName(purpose, storeRef, path), "", {
81
+ ...baseOptions(),
82
+ path,
83
+ maxAge: 0
84
+ });
85
+ }
54
86
  function writeAuthCookies(response, storeRef, tokens, path) {
55
87
  response.cookies.set(accessCookieName(storeRef, path), tokens.access_token, {
56
88
  ...baseOptions(),
@@ -101,7 +133,9 @@ export {
101
133
  authCookiePath,
102
134
  authCookiePathFor,
103
135
  clearAuthCookies,
136
+ clearEmailBindingCookie,
104
137
  clearOAuthNonceCookie,
138
+ emailBindingCookieName,
105
139
  hostOnlyCookieName,
106
140
  isHostMappedRequest,
107
141
  oauthNonceCookieName,
@@ -110,6 +144,7 @@ export {
110
144
  secureCookies,
111
145
  storeBasePathFor,
112
146
  writeAuthCookies,
147
+ writeEmailBindingCookie,
113
148
  writeOAuthNonceCookie
114
149
  };
115
150
  //# sourceMappingURL=cookies.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/cookies.ts"],"sourcesContent":["import type { NextResponse } from \"next/server\";\nimport type { AuthTokens } from \"@ecomweb/sdk\";\n\n/** Whether cookies are written `Secure` (everywhere but local dev over http). */\nexport function secureCookies(): boolean {\n return process.env.NODE_ENV === \"production\";\n}\n\n/**\n * `name` with the `__Host-` prefix whenever the cookie can carry it: `Secure`\n * and `Path=/` (the browser rejects a `__Host-` cookie that is not both).\n *\n * Store subdomains are siblings under the platform domain, so a merchant\n * script on one store can set a cookie with `Domain=<platform domain>` that\n * every other store receives: a planted session or OAuth nonce (cookie\n * tossing). Browsers also reject a `__Host-` cookie that names a Domain, so\n * one read under this name was set by this host and no other.\n *\n * Readers must look up the same name the writer used and never fall back to\n * the bare one, which any sibling store can set. Path-scoped cookies (the\n * shared `/store/<ref>` host) cannot take the prefix and keep the bare name.\n */\nexport function hostOnlyCookieName(\n name: string,\n path: string,\n secure = secureCookies()\n): string {\n return secure && path === \"/\" ? `__Host-${name}` : name;\n}\n\n/**\n * Cookie names are store-scoped because the platform serves many stores from\n * one origin (`/store/<storeRef>`). A shared name lets store B read store A's\n * session on the same domain. `path` is the cookie's (see authCookiePath).\n */\nexport function accessCookieName(storeRef: string, path: string): string {\n return hostOnlyCookieName(`ecomweb_sf_${storeRef}_at`, path);\n}\n\nexport function refreshCookieName(storeRef: string, path: string): string {\n return hostOnlyCookieName(`ecomweb_sf_${storeRef}_rt`, path);\n}\n\n/**\n * Request header the middleware (`proxy.ts`) stamps on every request it sees,\n * recording whether the **Host** identified the store — i.e. whether this is a\n * custom domain / subdomain deployment (one store per origin) or the shared\n * path-based host (`<origin>/store/<ref>/…`).\n *\n * It exists because the cookie `path` has to match the URL space the *browser*\n * is in, and the auth route handler cannot tell the two apart on its own: the\n * client calls `/store/<ref>/api/auth/*` in both cases (`lib/auth/context.tsx`).\n * The middleware is the only place that resolves Host → store.\n *\n * Always overwritten by the middleware, so a browser-supplied value cannot\n * survive on any path the middleware matches. On the paths it does not match\n * (root `/api/*`, which is reachable only on a custom domain) the value is\n * absent and the fallback is the unscoped path — the pre-existing behaviour.\n */\nexport const HOST_MAPPED_HEADER = \"x-ecomweb-host-mapped\";\n\n/** Minimal shape shared by `cookies()` and `request.cookies`. */\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** Minimal shape shared by `NextRequest` and a plain `Request`. */\ninterface HeaderReader {\n headers: { get(name: string): string | null };\n}\n\n/** The session pair stored at `path` (see authCookiePath), if both are set. */\nexport function readAuthCookies(\n jar: CookieReader,\n storeRef: string,\n path: string\n): AuthTokens | null {\n const access_token = jar.get(accessCookieName(storeRef, path))?.value;\n const refresh_token = jar.get(refreshCookieName(storeRef, path))?.value;\n\n if (!access_token || !refresh_token) return null;\n\n return { access_token, refresh_token };\n}\n\n/**\n * The unscoped path every auth cookie used to be written with, and still is\n * on a custom domain. Also the path the migration has to clear: sessions\n * created before this change live here.\n */\nconst LEGACY_PATH = \"/\";\n\n/**\n * The `path` for this store's auth cookies.\n *\n * On the shared path-based host every store lives under `/store/<ref>/…`, so\n * scoping the cookie there keeps store B's server code from ever receiving\n * store A's token. On a custom domain the shopper's URLs are rooted at `/`\n * and the cookie must stay unscoped, or the browser would withhold it from\n * every page and the shopper would look signed out.\n */\nexport function authCookiePath(storeRef: string, hostMapped: boolean): string {\n return hostMapped ? LEGACY_PATH : `/store/${encodeURIComponent(storeRef)}`;\n}\n\n/**\n * Whether the Host identified the store for this request, per the middleware.\n *\n * Absent header → treated as host-mapped, i.e. exactly what this code did\n * before the scoping existed. Never guess \"shared host\" without evidence:\n * guessing wrong in that direction scopes the cookie to a path the shopper's\n * pages are not under, and hides their session from them.\n */\nexport function isHostMappedRequest(request: HeaderReader): boolean {\n return request.headers.get(HOST_MAPPED_HEADER) !== \"0\";\n}\n\n/** `authCookiePath` for an incoming request, using the middleware's stamp. */\nexport function authCookiePathFor(\n request: HeaderReader,\n storeRef: string\n): string {\n return authCookiePath(storeRef, isHostMappedRequest(request));\n}\n\n/**\n * The store's own root as the *browser* sees it: `\"\"` on a custom domain or\n * subdomain (the store is the origin), `/store/<ref>` on the shared\n * path-based host. Derived from the same signal as the cookie path so the two\n * can never disagree — and not from the request path, which is\n * `/store/<ref>/api/…` on both deployments.\n */\nexport function storeBasePathFor(\n request: HeaderReader,\n storeRef: string\n): string {\n return isHostMappedRequest(request)\n ? \"\"\n : `/store/${encodeURIComponent(storeRef)}`;\n}\n\nfunction baseOptions() {\n return { httpOnly: true, secure: secureCookies(), sameSite: \"lax\" as const };\n}\n\n/**\n * Binds an OAuth round trip to the browser that started it.\n *\n * `google/complete` has to accept GET — Google's redirect chain lands there —\n * and `sameSite: \"lax\"` sends cookies on a cross-site top-level navigation, so\n * without this a link on any site could feed a victim's browser a one-time\n * code the attacker minted from their OWN Google account and plant the\n * attacker's session in it. The signed `state` cannot help: the backend\n * consumes it before the storefront is ever reached.\n *\n * `lax` (not `strict`) is required here for the same reason it is on the\n * session cookies: the browser arrives from Google's origin.\n */\nexport function oauthNonceCookieName(storeRef: string, path: string): string {\n return hostOnlyCookieName(`ecomweb_sf_${storeRef}_oauth`, path);\n}\n\n/** Long enough for a human to finish Google's consent screen, no longer. */\nconst OAUTH_NONCE_MAX_AGE_SECONDS = 600;\n\nexport function writeOAuthNonceCookie(\n response: NextResponse,\n storeRef: string,\n nonce: string,\n path: string\n): void {\n response.cookies.set(oauthNonceCookieName(storeRef, path), nonce, {\n ...baseOptions(),\n path,\n maxAge: OAUTH_NONCE_MAX_AGE_SECONDS,\n });\n}\n\nexport function clearOAuthNonceCookie(\n response: NextResponse,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(oauthNonceCookieName(storeRef, path), \"\", {\n ...baseOptions(),\n path,\n maxAge: 0,\n });\n}\n\nexport function writeAuthCookies(\n response: NextResponse,\n storeRef: string,\n tokens: AuthTokens,\n path: string\n): void {\n response.cookies.set(accessCookieName(storeRef, path), tokens.access_token, {\n ...baseOptions(),\n path,\n });\n response.cookies.set(\n refreshCookieName(storeRef, path),\n tokens.refresh_token,\n {\n ...baseOptions(),\n path,\n }\n );\n}\n\n/**\n * Clearing has to name the identical path the cookie was written with — a\n * `Set-Cookie` with a different path creates a second, empty cookie and leaves\n * the real one in place. So logout clears BOTH paths, always.\n *\n * Not belt and braces: a cookie can genuinely exist at the other path. Every\n * session that predates the scoping lives at `Path=/`, and a request whose\n * Host lookup failed transiently writes the scoped path on a deployment that\n * otherwise uses the unscoped one. Either survivor would be handed straight\n * back by `readAuthCookies` — a live session the shopper believes they ended.\n */\nexport function clearAuthCookies(\n response: NextResponse,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(accessCookieName(storeRef, path), \"\", {\n ...baseOptions(),\n path,\n maxAge: 0,\n });\n response.cookies.set(refreshCookieName(storeRef, path), \"\", {\n ...baseOptions(),\n path,\n maxAge: 0,\n });\n\n // The same session wherever else it can be stored: at the other path, and\n // in production under the bare names at `/` every session used before the\n // `__Host-` names (still sent to the scoped path, so still readable there).\n const otherPath =\n path === LEGACY_PATH ? authCookiePath(storeRef, false) : LEGACY_PATH;\n const stale: Array<[name: string, path: string]> = [\n [accessCookieName(storeRef, otherPath), otherPath],\n [refreshCookieName(storeRef, otherPath), otherPath],\n ];\n if (secureCookies()) {\n stale.push(\n [`ecomweb_sf_${storeRef}_at`, LEGACY_PATH],\n [`ecomweb_sf_${storeRef}_rt`, LEGACY_PATH]\n );\n }\n\n // `response.cookies` is keyed by name alone and rewrites the whole\n // Set-Cookie list on every `set()`, so a second cookie of the same name\n // cannot go through it and must be appended afterwards, never before.\n const secure = secureCookies() ? \"; Secure\" : \"\";\n for (const [name, stalePath] of stale) {\n response.headers.append(\n \"set-cookie\",\n `${name}=; Path=${stalePath}; Max-Age=0; HttpOnly; SameSite=Lax${secure}`\n );\n }\n}\n"],"mappings":"AAIO,SAAS,gBAAyB;AACvC,SAAO,QAAQ,IAAI,aAAa;AAClC;AAgBO,SAAS,mBACd,MACA,MACA,SAAS,cAAc,GACf;AACR,SAAO,UAAU,SAAS,MAAM,UAAU,IAAI,KAAK;AACrD;AAOO,SAAS,iBAAiB,UA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cesContent":["import type { NextResponse } from \"next/server\";\nimport type { AuthTokens } from \"@ecomweb/sdk\";\n\n/** Whether cookies are written `Secure` (everywhere but local dev over http). */\nexport function secureCookies(): boolean {\n return process.env.NODE_ENV === \"production\";\n}\n\n/**\n * `name` with the `__Host-` prefix whenever the cookie can carry it: `Secure`\n * and `Path=/` (the browser rejects a `__Host-` cookie that is not both).\n *\n * Store subdomains are siblings under the platform domain, so a merchant\n * script on one store can set a cookie with `Domain=<platform domain>` that\n * every other store receives: a planted session or OAuth nonce (cookie\n * tossing). Browsers also reject a `__Host-` cookie that names a Domain, so\n * one read under this name was set by this host and no other.\n *\n * Readers must look up the same name the writer used and never fall back to\n * the bare one, which any sibling store can set. Path-scoped cookies (the\n * shared `/store/<ref>` host) cannot take the prefix and keep the bare name.\n */\nexport function hostOnlyCookieName(\n name: string,\n path: string,\n secure = secureCookies()\n): string {\n return secure && path === \"/\" ? `__Host-${name}` : name;\n}\n\n/**\n * Cookie names are store-scoped because the platform serves many stores from\n * one origin (`/store/<storeRef>`). A shared name lets store B read store A's\n * session on the same domain. `path` is the cookie's (see authCookiePath).\n */\nexport function accessCookieName(storeRef: string, path: string): string {\n return hostOnlyCookieName(`ecomweb_sf_${storeRef}_at`, path);\n}\n\nexport function refreshCookieName(storeRef: string, path: string): string {\n return hostOnlyCookieName(`ecomweb_sf_${storeRef}_rt`, path);\n}\n\n/**\n * Request header the middleware (`proxy.ts`) stamps on every request it sees,\n * recording whether the **Host** identified the store — i.e. whether this is a\n * custom domain / subdomain deployment (one store per origin) or the shared\n * path-based host (`<origin>/store/<ref>/…`).\n *\n * It exists because the cookie `path` has to match the URL space the *browser*\n * is in, and the auth route handler cannot tell the two apart on its own: the\n * client calls `/store/<ref>/api/auth/*` in both cases (`lib/auth/context.tsx`).\n * The middleware is the only place that resolves Host → store.\n *\n * Always overwritten by the middleware, so a browser-supplied value cannot\n * survive on any path the middleware matches. On the paths it does not match\n * (root `/api/*`, which is reachable only on a custom domain) the value is\n * absent and the fallback is the unscoped path — the pre-existing behaviour.\n */\nexport const HOST_MAPPED_HEADER = \"x-ecomweb-host-mapped\";\n\n/** Minimal shape shared by `cookies()` and `request.cookies`. */\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** Minimal shape shared by `NextRequest` and a plain `Request`. */\ninterface HeaderReader {\n headers: { get(name: string): string | null };\n}\n\n/** The session pair stored at `path` (see authCookiePath), if both are set. */\nexport function readAuthCookies(\n jar: CookieReader,\n storeRef: string,\n path: string\n): AuthTokens | null {\n const access_token = jar.get(accessCookieName(storeRef, path))?.value;\n const refresh_token = jar.get(refreshCookieName(storeRef, path))?.value;\n\n if (!access_token || !refresh_token) return null;\n\n return { access_token, refresh_token };\n}\n\n/**\n * The unscoped path every auth cookie used to be written with, and still is\n * on a custom domain. Also the path the migration has to clear: sessions\n * created before this change live here.\n */\nconst LEGACY_PATH = \"/\";\n\n/**\n * The `path` for this store's auth cookies.\n *\n * On the shared path-based host every store lives under `/store/<ref>/…`, so\n * scoping the cookie there keeps store B's server code from ever receiving\n * store A's token. On a custom domain the shopper's URLs are rooted at `/`\n * and the cookie must stay unscoped, or the browser would withhold it from\n * every page and the shopper would look signed out.\n */\nexport function authCookiePath(storeRef: string, hostMapped: boolean): string {\n return hostMapped ? LEGACY_PATH : `/store/${encodeURIComponent(storeRef)}`;\n}\n\n/**\n * Whether the Host identified the store for this request, per the middleware.\n *\n * Absent header → treated as host-mapped, i.e. exactly what this code did\n * before the scoping existed. Never guess \"shared host\" without evidence:\n * guessing wrong in that direction scopes the cookie to a path the shopper's\n * pages are not under, and hides their session from them.\n */\nexport function isHostMappedRequest(request: HeaderReader): boolean {\n return request.headers.get(HOST_MAPPED_HEADER) !== \"0\";\n}\n\n/** `authCookiePath` for an incoming request, using the middleware's stamp. */\nexport function authCookiePathFor(\n request: HeaderReader,\n storeRef: string\n): string {\n return authCookiePath(storeRef, isHostMappedRequest(request));\n}\n\n/**\n * The store's own root as the *browser* sees it: `\"\"` on a custom domain or\n * subdomain (the store is the origin), `/store/<ref>` on the shared\n * path-based host. Derived from the same signal as the cookie path so the two\n * can never disagree — and not from the request path, which is\n * `/store/<ref>/api/…` on both deployments.\n */\nexport function storeBasePathFor(\n request: HeaderReader,\n storeRef: string\n): string {\n return isHostMappedRequest(request)\n ? \"\"\n : `/store/${encodeURIComponent(storeRef)}`;\n}\n\nfunction baseOptions() {\n return { httpOnly: true, secure: secureCookies(), sameSite: \"lax\" as const };\n}\n\n/**\n * Binds an OAuth round trip to the browser that started it.\n *\n * `google/complete` has to accept GET — Google's redirect chain lands there —\n * and `sameSite: \"lax\"` sends cookies on a cross-site top-level navigation, so\n * without this a link on any site could feed a victim's browser a one-time\n * code the attacker minted from their OWN Google account and plant the\n * attacker's session in it. The signed `state` cannot help: the backend\n * consumes it before the storefront is ever reached.\n *\n * `lax` (not `strict`) is required here for the same reason it is on the\n * session cookies: the browser arrives from Google's origin.\n */\nexport function oauthNonceCookieName(storeRef: string, path: string): string {\n return hostOnlyCookieName(`ecomweb_sf_${storeRef}_oauth`, path);\n}\n\n/** Long enough for a human to finish Google's consent screen, no longer. */\nconst OAUTH_NONCE_MAX_AGE_SECONDS = 600;\n\nexport function writeOAuthNonceCookie(\n response: NextResponse,\n storeRef: string,\n nonce: string,\n path: string\n): void {\n response.cookies.set(oauthNonceCookieName(storeRef, path), nonce, {\n ...baseOptions(),\n path,\n maxAge: OAUTH_NONCE_MAX_AGE_SECONDS,\n });\n}\n\nexport function clearOAuthNonceCookie(\n response: NextResponse,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(oauthNonceCookieName(storeRef, path), \"\", {\n ...baseOptions(),\n path,\n maxAge: 0,\n });\n}\n\n/**\n * Which mailed-link flow an email-proof binding belongs to. The API hands the\n * binding to the client that asked (register, change-email) and never mails\n * it; the click must present it with the mailed token, which proves the click\n * came from the same browser. A browser that lost the cookie (another device,\n * expired) still works: verify-email then verifies the address but drops the\n * password set at registration, and newer APIs refuse the email-change\n * confirm.\n */\nexport type EmailBindingPurpose = \"verify-email\" | \"change-email\";\n\nconst EMAIL_BINDING_COOKIE_SUFFIX: Record<EmailBindingPurpose, string> = {\n \"verify-email\": \"vb\",\n \"change-email\": \"cb\",\n};\n\n/** The API's token lifetimes (AUTH_TTL.EMAIL_VERIFICATION / EMAIL_CHANGE). */\nconst EMAIL_BINDING_MAX_AGE_SECONDS: Record<EmailBindingPurpose, number> = {\n \"verify-email\": 86400,\n \"change-email\": 3600,\n};\n\nexport function emailBindingCookieName(\n purpose: EmailBindingPurpose,\n storeRef: string,\n path: string\n): string {\n return hostOnlyCookieName(\n `ecomweb_sf_${storeRef}_${EMAIL_BINDING_COOKIE_SUFFIX[purpose]}`,\n path\n );\n}\n\nexport function writeEmailBindingCookie(\n response: NextResponse,\n purpose: EmailBindingPurpose,\n storeRef: string,\n binding: string,\n path: string\n): void {\n response.cookies.set(\n emailBindingCookieName(purpose, storeRef, path),\n binding,\n {\n ...baseOptions(),\n path,\n maxAge: EMAIL_BINDING_MAX_AGE_SECONDS[purpose],\n }\n );\n}\n\nexport function clearEmailBindingCookie(\n response: NextResponse,\n purpose: EmailBindingPurpose,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(emailBindingCookieName(purpose, storeRef, path), \"\", {\n ...baseOptions(),\n path,\n maxAge: 0,\n });\n}\n\nexport function writeAuthCookies(\n response: NextResponse,\n storeRef: string,\n tokens: AuthTokens,\n path: string\n): void {\n response.cookies.set(accessCookieName(storeRef, path), tokens.access_token, {\n ...baseOptions(),\n path,\n });\n response.cookies.set(\n refreshCookieName(storeRef, path),\n tokens.refresh_token,\n {\n ...baseOptions(),\n path,\n }\n );\n}\n\n/**\n * Clearing has to name the identical path the cookie was written with — a\n * `Set-Cookie` with a different path creates a second, empty cookie and leaves\n * the real one in place. So logout clears BOTH paths, always.\n *\n * Not belt and braces: a cookie can genuinely exist at the other path. Every\n * session that predates the scoping lives at `Path=/`, and a request whose\n * Host lookup failed transiently writes the scoped path on a deployment that\n * otherwise uses the unscoped one. Either survivor would be handed straight\n * back by `readAuthCookies` — a live session the shopper believes they ended.\n */\nexport function clearAuthCookies(\n response: NextResponse,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(accessCookieName(storeRef, path), \"\", {\n ...baseOptions(),\n path,\n maxAge: 0,\n });\n response.cookies.set(refreshCookieName(storeRef, path), \"\", {\n ...baseOptions(),\n path,\n maxAge: 0,\n });\n\n // The same session wherever else it can be stored: at the other path, and\n // in production under the bare names at `/` every session used before the\n // `__Host-` names (still sent to the scoped path, so still readable there).\n const otherPath =\n path === LEGACY_PATH ? authCookiePath(storeRef, false) : LEGACY_PATH;\n const stale: Array<[name: string, path: string]> = [\n [accessCookieName(storeRef, otherPath), otherPath],\n [refreshCookieName(storeRef, otherPath), otherPath],\n ];\n if (secureCookies()) {\n stale.push(\n [`ecomweb_sf_${storeRef}_at`, LEGACY_PATH],\n [`ecomweb_sf_${storeRef}_rt`, LEGACY_PATH]\n );\n }\n\n // `response.cookies` is keyed by name alone and rewrites the whole\n // Set-Cookie list on every `set()`, so a second cookie of the same name\n // cannot go through it and must be appended afterwards, never before.\n const secure = secureCookies() ? \"; Secure\" : \"\";\n for (const [name, stalePath] of stale) {\n response.headers.append(\n \"set-cookie\",\n `${name}=; Path=${stalePath}; Max-Age=0; HttpOnly; SameSite=Lax${secure}`\n );\n }\n}\n"],"mappings":"AAIO,SAAS,gBAAyB;AACvC,SAAO,QAAQ,IAAI,aAAa;AAClC;AAgBO,SAAS,mBACd,MACA,MACA,SAAS,cAAc,GACf;AACR,SAAO,UAAU,SAAS,MAAM,UAAU,IAAI,KAAK;AACrD;AAOO,SAAS,iBAAiB,UAAkB,MAAsB;AACvE,SAAO,mBAAmB,cAAc,QAAQ,OAAO,IAAI;AAC7D;AAEO,SAAS,kBAAkB,UAAkB,MAAsB;AACxE,SAAO,mBAAmB,cAAc,QAAQ,OAAO,IAAI;AAC7D;AAkBO,MAAM,qBAAqB;AAa3B,SAAS,gBACd,KACA,UACA,MACmB;A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A,IACjD,CAAC,kBAAkB,UAAU,SAAS,GAAG,SAAS;AAAA,EACpD;AACA,MAAI,cAAc,GAAG;AACnB,UAAM;AAAA,MACJ,CAAC,cAAc,QAAQ,OAAO,WAAW;AAAA,MACzC,CAAC,cAAc,QAAQ,OAAO,WAAW;AAAA,IAC3C;AAAA,EACF;AAKA,QAAM,SAAS,cAAc,IAAI,aAAa;AAC9C,aAAW,CAAC,MAAM,SAAS,KAAK,OAAO;AACrC,aAAS,QAAQ;AAAA,MACf;AAAA,MACA,GAAG,IAAI,WAAW,SAAS,sCAAsC,MAAM;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
@@ -22,6 +22,7 @@ const ERROR_COPY = {
22
22
  INSUFFICIENT_INVENTORY: "M\u1ED9t s\u1ED1 s\u1EA3n ph\u1EA9m kh\xF4ng \u0111\u1EE7 h\xE0ng.",
23
23
  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.",
24
24
  PROMOTION_USAGE_LIMIT_REACHED: "M\xE3 gi\u1EA3m gi\xE1 \u0111\xE3 h\u1EBFt l\u01B0\u1EE3t s\u1EED d\u1EE5ng 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.",
25
+ PROMOTION_IDENTITY_REQUIRED: "M\xE3 gi\u1EA3m gi\xE1 n\xE0y gi\u1EDBi h\u1EA1n l\u01B0\u1EE3t d\xF9ng cho m\u1ED7i kh\xE1ch h\xE0ng. Vui l\xF2ng nh\u1EADp email \u0111\u1EC3 s\u1EED d\u1EE5ng m\xE3.",
25
26
  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.",
26
27
  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.",
27
28
  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.",
@@ -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 * - `PROMOTION_USAGE_LIMIT_REACHED`: `promotion-usage.ts` in the API's\n * promotions module, when placing the order would pass the code's total\n * or per-customer usage limit. `useCheckout` drops the code too.\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 * - `BLOG_COMMENTS_DISABLED`: the 403 for a blog comment on a store whose\n * blog settings have comments turned off (`allow_comments`). The\n * storefront hides the form then, so this reaches a shopper only when the\n * setting changed while the post was open.\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 // The merchant marked this customer inactive. Sent only after the shopper\n // proved the password, code or Google account.\n AUTH_ACCOUNT_DISABLED:\n \"Tài khoản này không thể đăng nhập. Vui lòng liên hệ cửa hàng.\",\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 PROMOTION_USAGE_LIMIT_REACHED:\n \"Mã giảm giá đã hết lượt sử dụng 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 BLOG_COMMENTS_DISABLED: \"Cửa hàng đã tắt bình luận cho blog.\",\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;AA6ClC,MAAM,aAAqC;AAAA,EACzC,0BAA0B;AAAA,EAC1B,qBAAqB;AAAA;AAAA;AAAA,EAGrB,uBACE;AAAA,EACF,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,+BACE;AAAA,EACF,wBACE;AAAA,EACF,iCACE;AAAA,EACF,kCACE;AAAA,EACF,mBACE;AAAA,EACF,wBAAwB;AAC1B;AAQA,MAAM,cAAsC;AAAA,EAC1C,GAAG;AAAA,EACH,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAGO,SAAS,UACd,MACA,WAAmB,oBACX;AACR,SAAQ,QAAQ,WAAW,IAAI,KAAM;AACvC;AAUO,SAAS,aACd,OACA,WAAmB,oBACX;AACR,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,QAAM,EAAE,MAAM,WAAW,IAAI;AAK7B,MAAI,OAAO,SAAS,YAAY,WAAW,IAAI,EAAG,QAAO,WAAW,IAAI;AACxE,MAAI,OAAO,eAAe,YAAY,YAAY,UAAU,GAAG;AAC7D,WAAO,YAAY,UAAU;AAAA,EAC/B;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/error-copy.ts"],"sourcesContent":["/**\n * Shopper-facing copy for backend errors.\n *\n * Project rule: backend exception messages are written in English and are\n * never shown to a shopper. The backend serialises every business error as\n * `{ code, message, details, timestamp }` (see `src/common/exceptions/` in the\n * api repo) and `code` is the stable identifier — this module is the single\n * place that turns one into Vietnamese.\n *\n * The fallback is always a generic Vietnamese sentence. Never fall back to the\n * backend's `message`.\n */\n\nexport const GENERIC_ERROR_COPY = \"Đã xảy ra lỗi. Vui lòng thử lại.\";\n\n/**\n * Keyed by the backend's stable `code`. Sources, read directly rather than\n * guessed:\n * - `AUTH_*` — `src/modules/customer-auth/domain/constants/auth.constants.ts`\n * (`AUTH_ERROR`).\n * - `ACCESS_DENIED` — `AuthorizationException.accessDenied()`, thrown by\n * `customer-addresses.controller.ts` on an address the caller does not own.\n * - `<RESOURCE>_NOT_FOUND` — `ResourceNotFoundException`, whose code is\n * `${resource.toUpperCase()}_NOT_FOUND`. `Address` and `Order` are the two\n * resources the storefront's authenticated routes can produce.\n * - `VALIDATION_FAILED` — `ValidationException`.\n * - `ORDER_NOT_CANCELLABLE` — `ORDER_ERROR.NOT_CANCELLABLE`\n * (`src/modules/orders/domain/constants/order-error.constants.ts`),\n * thrown by `OrderCancelCommandHandler` when a customer tries to cancel\n * an order outside pending/confirmed/processing.\n * - `INSUFFICIENT_INVENTORY`: `InsufficientInventoryException`\n * (`src/modules/inventory/domain/exceptions/`), thrown when an order asks\n * for more of a deny-policy variant than is available.\n * - `ORDER_PROMOTION_NOT_APPLICABLE`: `ORDER_ERROR.PROMOTION_NOT_APPLICABLE`,\n * thrown by `OrderComputationService.applyPromotionCode` when the applied\n * code can no longer be redeemed at placement (expired, used up, the cart\n * changed). `useCheckout` drops the code when it sees this.\n * - `PROMOTION_USAGE_LIMIT_REACHED`: `promotion-usage.ts` in the API's\n * promotions module, when placing the order would pass the code's total\n * or per-customer usage limit. `useCheckout` drops the code too.\n * - `PROMOTION_IDENTITY_REQUIRED`: `promotion-usage.ts` too (422, details\n * `{ field: \"customer_email\" }`), when a code limited per customer is\n * used on an order with neither a signed-in customer nor an email. The\n * code is kept; the shopper adds an email and places again.\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 * - `BLOG_COMMENTS_DISABLED`: the 403 for a blog comment on a store whose\n * blog settings have comments turned off (`allow_comments`). The\n * storefront hides the form then, so this reaches a shopper only when the\n * setting changed while the post was open.\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 // The merchant marked this customer inactive. Sent only after the shopper\n // proved the password, code or Google account.\n AUTH_ACCOUNT_DISABLED:\n \"Tài khoản này không thể đăng nhập. Vui lòng liên hệ cửa hàng.\",\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 PROMOTION_USAGE_LIMIT_REACHED:\n \"Mã giảm giá đã hết lượt sử dụng nên đã được gỡ. Vui lòng kiểm tra lại tổng tiền rồi đặt hàng.\",\n PROMOTION_IDENTITY_REQUIRED:\n \"Mã giảm giá này giới hạn lượt dùng cho mỗi khách hàng. Vui lòng nhập email để sử dụng mã.\",\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 BLOG_COMMENTS_DISABLED: \"Cửa hàng đã tắt bình luận cho blog.\",\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;AAiDlC,MAAM,aAAqC;AAAA,EACzC,0BAA0B;AAAA,EAC1B,qBAAqB;AAAA;AAAA;AAAA,EAGrB,uBACE;AAAA,EACF,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,+BACE;AAAA,EACF,6BACE;AAAA,EACF,wBACE;AAAA,EACF,iCACE;AAAA,EACF,kCACE;AAAA,EACF,mBACE;AAAA,EACF,wBAAwB;AAC1B;AAQA,MAAM,cAAsC;AAAA,EAC1C,GAAG;AAAA,EACH,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAGO,SAAS,UACd,MACA,WAAmB,oBACX;AACR,SAAQ,QAAQ,WAAW,IAAI,KAAM;AACvC;AAUO,SAAS,aACd,OACA,WAAmB,oBACX;AACR,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,QAAM,EAAE,MAAM,WAAW,IAAI;AAK7B,MAAI,OAAO,SAAS,YAAY,WAAW,IAAI,EAAG,QAAO,WAAW,IAAI;AACxE,MAAI,OAAO,eAAe,YAAY,YAAY,UAAU,GAAG;AAC7D,WAAO,YAAY,UAAU;AAAA,EAC/B;AAEA,SAAO;AACT;","names":[]}
@@ -1,17 +1,21 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { createAuthApi } from "./sdk.js";
3
3
  import { clientIpFrom } from "./client-ip.js";
4
+ import { storePreviewTokenFor } from "../api/proxy.js";
4
5
  import { safeRedirectPath } from "./safe-redirect.js";
5
6
  import { publicNextUrl } from "../request/public-url.js";
6
7
  import {
7
8
  authCookiePath,
8
9
  clearAuthCookies,
10
+ clearEmailBindingCookie,
9
11
  clearOAuthNonceCookie,
12
+ emailBindingCookieName,
10
13
  isHostMappedRequest,
11
14
  oauthNonceCookieName,
12
15
  readAuthCookies,
13
16
  writeAuthCookies,
14
17
  storeBasePathFor,
18
+ writeEmailBindingCookie,
15
19
  writeOAuthNonceCookie
16
20
  } from "./cookies.js";
17
21
  function fail(status, message, code) {
@@ -73,7 +77,11 @@ async function handleAuthRoute(request, storeRef, segments) {
73
77
  const allowedMethod = AUTH_ACTION_METHOD[action];
74
78
  if (!allowedMethod) return fail(404, `Unknown auth action: ${action}`);
75
79
  if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);
76
- const auth = createAuthApi(storeRef, clientIpFrom(request.headers));
80
+ const auth = createAuthApi(
81
+ storeRef,
82
+ clientIpFrom(request.headers),
83
+ storePreviewTokenFor(request, storeRef)
84
+ );
77
85
  const hostMapped = isHostMappedRequest(request);
78
86
  const cookiePath = authCookiePath(storeRef, hostMapped);
79
87
  const tokens = readAuthCookies(request.cookies, storeRef, cookiePath);
@@ -109,7 +117,18 @@ async function handleAuthRoute(request, storeRef, segments) {
109
117
  res.error.message,
110
118
  res.error.error
111
119
  );
112
- return NextResponse.json({ registered: true });
120
+ const registered = NextResponse.json({ registered: true });
121
+ const verificationBinding = res.data?.verification_binding;
122
+ if (verificationBinding) {
123
+ writeEmailBindingCookie(
124
+ registered,
125
+ "verify-email",
126
+ storeRef,
127
+ verificationBinding,
128
+ cookiePath
129
+ );
130
+ }
131
+ return registered;
113
132
  }
114
133
  case "login": {
115
134
  const res = await auth.login(body);
@@ -179,14 +198,19 @@ async function handleAuthRoute(request, storeRef, segments) {
179
198
  return response;
180
199
  }
181
200
  case "verify-email": {
182
- const res = await auth.verifyEmail(body.token);
201
+ const binding = request.cookies.get(
202
+ emailBindingCookieName("verify-email", storeRef, cookiePath)
203
+ )?.value;
204
+ const res = await auth.verifyEmail(body.token, binding || void 0);
183
205
  if (!res.success)
184
206
  return fail(
185
207
  res.error.statusCode,
186
208
  res.error.message,
187
209
  res.error.error
188
210
  );
189
- return NextResponse.json(res.data);
211
+ const verified = NextResponse.json(res.data);
212
+ clearEmailBindingCookie(verified, "verify-email", storeRef, cookiePath);
213
+ return verified;
190
214
  }
191
215
  case "resend-verification": {
192
216
  const res = await auth.resendVerification(body.email);
@@ -246,17 +270,36 @@ async function handleAuthRoute(request, storeRef, segments) {
246
270
  res.error.message,
247
271
  res.error.error
248
272
  );
249
- return NextResponse.json({ sent: true });
273
+ const sent = NextResponse.json({ sent: true });
274
+ const confirmationBinding = res.data?.confirmation_binding;
275
+ if (confirmationBinding) {
276
+ writeEmailBindingCookie(
277
+ sent,
278
+ "change-email",
279
+ storeRef,
280
+ confirmationBinding,
281
+ cookiePath
282
+ );
283
+ }
284
+ return sent;
250
285
  }
251
286
  case "change-email/confirm": {
252
- const res = await auth.confirmEmailChange(body.token);
287
+ const binding = request.cookies.get(
288
+ emailBindingCookieName("change-email", storeRef, cookiePath)
289
+ )?.value;
290
+ const res = await auth.confirmEmailChange(
291
+ body.token,
292
+ binding || void 0
293
+ );
253
294
  if (!res.success)
254
295
  return fail(
255
296
  res.error.statusCode,
256
297
  res.error.message,
257
298
  res.error.error
258
299
  );
259
- return NextResponse.json(res.data);
300
+ const confirmed = NextResponse.json(res.data);
301
+ clearEmailBindingCookie(confirmed, "change-email", storeRef, cookiePath);
302
+ return confirmed;
260
303
  }
261
304
  case "google/url": {
262
305
  const base = storeBasePathFor(request, storeRef);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/route-handlers.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { createAuthApi } from \"./sdk\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { safeRedirectPath } from \"./safe-redirect\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n authCookiePath,\n clearAuthCookies,\n clearOAuthNonceCookie,\n isHostMappedRequest,\n oauthNonceCookieName,\n readAuthCookies,\n writeAuthCookies,\n storeBasePathFor,\n writeOAuthNonceCookie,\n} from \"./cookies\";\nimport type {\n AuthResult,\n ChangeEmailPayload,\n ChangePasswordPayload,\n LoginPayload,\n RegisterPayload,\n ResetPasswordPayload,\n VerifyOtpPayload,\n} from \"@ecomweb/sdk\";\n\n/** Translates the SDK's ApiResponse into a JSON response, preserving the code. */\nfunction fail(status: number, message: string, code?: string) {\n return NextResponse.json(\n { error: { message, code } },\n { status: status || 500 }\n );\n}\n\n/**\n * The HTTP method each action answers on — one entry per action, no defaults.\n *\n * Every one of these used to answer GET as well as POST, and the session\n * cookies are `sameSite: \"lax\"`, which the browser DOES send on a cross-site\n * top-level navigation. A link on any page therefore reached `logout-all`, or\n * `google/complete` with a code of the attacker's choosing. The split is\n * enumerated rather than inferred so that adding an action forces a decision\n * here; an action missing from this map is a 404, not a silent GET.\n *\n * GET is limited to the two reads the client polls (`config`, `session`) and\n * the two halves of the OAuth hand-off: `google/url` is a read, and\n * `google/complete` is the browser's landing spot in a redirect chain, so it\n * cannot be anything else. It carries its own browser binding instead — see\n * the nonce cookie below.\n */\nconst AUTH_ACTION_METHOD = {\n config: \"GET\",\n session: \"GET\",\n \"google/url\": \"GET\",\n \"google/complete\": \"GET\",\n\n register: \"POST\",\n login: \"POST\",\n \"otp/request\": \"POST\",\n \"otp/verify\": \"POST\",\n anonymous: \"POST\",\n logout: \"POST\",\n \"logout-all\": \"POST\",\n \"verify-email\": \"POST\",\n \"resend-verification\": \"POST\",\n \"forgot-password\": \"POST\",\n \"reset-password\": \"POST\",\n \"change-password\": \"POST\",\n \"change-email\": \"POST\",\n \"change-email/confirm\": \"POST\",\n} as const satisfies Record<string, \"GET\" | \"POST\">;\n\ntype AuthAction = keyof typeof AUTH_ACTION_METHOD;\n\n/**\n * The query parameter carrying the OAuth nonce home.\n *\n * `redirect_to` is the only field that survives the round trip through the\n * signed `state` and back out as `next=`, and the backend requires it to be a\n * relative path, so the nonce travels inside it as a query parameter of a\n * path-only URL. The storefront is both the producer and the only consumer of\n * this shape.\n */\nconst OAUTH_NONCE_PARAM = \"sf_oauth\";\nconst OAUTH_NEXT_PARAM = \"next\";\n\n/** Tokens go into cookies and never into the response body. */\nfunction withSession(\n storeRef: string,\n cookiePath: string,\n result: AuthResult,\n body: Record<string, unknown> = {}\n) {\n const response = NextResponse.json({ identity: result.identity, ...body });\n\n if (result.access_token && result.refresh_token) {\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: result.access_token,\n refresh_token: result.refresh_token,\n },\n cookiePath\n );\n }\n\n return response;\n}\n\nfunction methodNotAllowed(allowed: \"GET\" | \"POST\") {\n return NextResponse.json(\n {\n error: {\n message: `This action requires ${allowed}`,\n code: \"METHOD_NOT_ALLOWED\",\n },\n },\n { status: 405, headers: { allow: allowed } }\n );\n}\n\nexport async function handleAuthRoute(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const action = segments.join(\"/\");\n const allowedMethod = AUTH_ACTION_METHOD[action as AuthAction];\n\n if (!allowedMethod) return fail(404, `Unknown auth action: ${action}`);\n if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);\n\n // The shopper's address, not this server's: the backend rate-limits per\n // `storeId:clientIp` and every one of these calls is made server-side.\n const auth = createAuthApi(storeRef, clientIpFrom(request.headers));\n const hostMapped = isHostMappedRequest(request);\n const cookiePath = authCookiePath(storeRef, hostMapped);\n const tokens = readAuthCookies(request.cookies, storeRef, cookiePath);\n\n const body: Record<string, any> =\n request.method === \"POST\" ? await request.json().catch(() => ({})) : {};\n\n switch (action) {\n case \"config\": {\n const res = await auth.getAuthConfig();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"register\": {\n // Never trust a browser-supplied `anonymous_identity_id`: the backend\n // only checks store_id / is_anonymous / !deleted_at, not ownership, so\n // forwarding it would let anyone who learns an anonymous UUID register\n // against it and inherit its cart and orders. Whatever the browser sent\n // is dropped and the id is derived from the httpOnly session instead.\n const payload: Record<string, any> = { ...body };\n delete payload.anonymous_identity_id;\n\n let anonymousIdentityId: string | undefined;\n\n if (tokens) {\n const current = await auth.me(tokens.access_token);\n if (current.success && current.data?.is_anonymous) {\n anonymousIdentityId = current.data.id;\n }\n }\n\n const res = await auth.register({\n ...payload,\n anonymous_identity_id: anonymousIdentityId,\n } as RegisterPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Register never returns tokens, by design.\n return NextResponse.json({ registered: true });\n }\n\n case \"login\": {\n const res = await auth.login(body as LoginPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"otp/request\": {\n const res = await auth.requestOtp(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"otp/verify\": {\n const res = await auth.verifyOtp(body as VerifyOtpPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"anonymous\": {\n const res = await auth.anonymous();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"session\": {\n if (!tokens) return NextResponse.json({ identity: null });\n const res = await auth.me(tokens.access_token);\n if (!res.success) return NextResponse.json({ identity: null });\n return NextResponse.json({ identity: res.data });\n }\n\n case \"logout\": {\n // Best-effort revoke: a failed call must still clear the browser's\n // cookies, or the shopper is stuck logged in against a dead session.\n if (tokens) {\n await auth\n .logout(tokens.access_token, tokens.refresh_token)\n .catch(() => undefined);\n }\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"logout-all\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.logoutAll(tokens.access_token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"verify-email\": {\n const res = await auth.verifyEmail(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"resend-verification\": {\n const res = await auth.resendVerification(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"forgot-password\": {\n const res = await auth.forgotPassword(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"reset-password\": {\n const res = await auth.resetPassword(body as ResetPasswordPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"change-password\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changePassword(\n tokens.access_token,\n body as ChangePasswordPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Changing a password revokes sessions server-side; drop the cookies too.\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"change-email\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changeEmail(\n tokens.access_token,\n body as ChangeEmailPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"change-email/confirm\": {\n const res = await auth.confirmEmailChange(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"google/url\": {\n // Proxied rather than called from the browser so the storefront API key\n // stays server-side.\n const base = storeBasePathFor(request, storeRef);\n const wanted = safeRedirectPath(\n request.nextUrl.searchParams.get(\"redirect_to\"),\n publicNextUrl(request).toString()\n );\n\n // The nonce is minted here, remembered in an httpOnly cookie, and rides\n // out inside `redirect_to`. `google/complete` refuses to issue a session\n // unless the two match, which is what makes that GET unforgeable.\n // `globalThis.crypto` rather than a node:crypto import: this module is\n // bundled for whichever runtime the route runs in.\n const nonce = globalThis.crypto.randomUUID();\n const carrier = new URLSearchParams({\n [OAUTH_NONCE_PARAM]: nonce,\n [OAUTH_NEXT_PARAM]: wanted,\n });\n\n const res = await auth.getGoogleUrl(`${base}/?${carrier.toString()}`);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n\n const response = NextResponse.json(res.data);\n writeOAuthNonceCookie(response, storeRef, nonce, cookiePath);\n return response;\n }\n\n case \"google/complete\": {\n // The backend redirects the BROWSER here with a one-time code. It is\n // redeemed server-side so no token ever reaches the URL bar, history,\n // or a Referer header.\n const base = storeBasePathFor(request, storeRef);\n const errorTarget = new URL(\n `${base}/auth/error?error=oauth_failed`,\n publicNextUrl(request).toString()\n );\n\n const code = request.nextUrl.searchParams.get(\"code\");\n\n // Whatever came back in `next` is the carrier this route wrote in\n // `google/url`: a relative path plus the nonce. Both halves are\n // re-validated — the path against the origin, the nonce against the\n // cookie — before anything is issued.\n const carrier = safeRedirectPath(\n request.nextUrl.searchParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const carrierParams = new URL(carrier, publicNextUrl(request).toString()).searchParams;\n const presentedNonce = carrierParams.get(OAUTH_NONCE_PARAM);\n const expectedNonce = request.cookies.get(\n oauthNonceCookieName(storeRef, cookiePath)\n )?.value;\n\n const nonceMatches =\n !!presentedNonce && !!expectedNonce && presentedNonce === expectedNonce;\n\n if (!code || !nonceMatches) {\n // A missing or mismatched nonce means this browser did not start the\n // flow: someone else's one-time code is being pushed into it. Refuse\n // before any token is exchanged, and burn the nonce either way.\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const res = await auth.exchangeGoogleCode(code);\n\n if (!res.success || !res.data?.access_token || !res.data.refresh_token) {\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const target = safeRedirectPath(\n carrierParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const response = NextResponse.redirect(\n new URL(target === \"/\" ? `${base}/` : target, publicNextUrl(request).toString())\n );\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: res.data.access_token,\n refresh_token: res.data.refresh_token,\n },\n cookiePath\n );\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n\n return response;\n }\n\n default:\n // Unreachable: AUTH_ACTION_METHOD is checked first, and every key it\n // holds has a case above. Kept so adding a key without a case is a\n // 404 rather than an undefined response.\n return fail(404, `Unknown auth action: ${action}`);\n }\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP,SAAS,KAAK,QAAgB,SAAiB,MAAe;AAC5D,SAAO,aAAa;AAAA,IAClB,EAAE,OAAO,EAAE,SAAS,K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,UAAI,CAAC,IAAI,WAAW,CAAC,IAAI,MAAM,gBAAgB,CAAC,IAAI,KAAK,eAAe;AACtE,cAAMA,YAAW,aAAa,SAAS,WAAW;AAClD,8BAAsBA,WAAU,UAAU,UAAU;AACpD,eAAOA;AAAA,MACT;AAEA,YAAM,SAAS;AAAA,QACb,cAAc,IAAI,gBAAgB;AAAA,QAClC,cAAc,OAAO,EAAE,SAAS;AAAA,MAClC;AACA,YAAM,WAAW,aAAa;AAAA,QAC5B,IAAI,IAAI,WAAW,MAAM,GAAG,IAAI,MAAM,QAAQ,cAAc,OAAO,EAAE,SAAS,CAAC;AAAA,MACjF;AAEA;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,UACE,cAAc,IAAI,KAAK;AAAA,UACvB,eAAe,IAAI,KAAK;AAAA,QAC1B;AAAA,QACA;AAAA,MACF;AACA,4BAAsB,UAAU,UAAU,UAAU;AAEpD,aAAO;AAAA,IACT;AAAA,IAEA;AAIE,aAAO,KAAK,KAAK,wBAAwB,MAAM,EAAE;AAAA,EACrD;AACF;","names":["response"]}
1
+ {"version":3,"sources":["../../src/auth/route-handlers.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { createAuthApi } from \"./sdk\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { storePreviewTokenFor } from \"../api/proxy\";\nimport { safeRedirectPath } from \"./safe-redirect\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n authCookiePath,\n clearAuthCookies,\n clearEmailBindingCookie,\n clearOAuthNonceCookie,\n emailBindingCookieName,\n isHostMappedRequest,\n oauthNonceCookieName,\n readAuthCookies,\n writeAuthCookies,\n storeBasePathFor,\n writeEmailBindingCookie,\n writeOAuthNonceCookie,\n} from \"./cookies\";\nimport type {\n AuthResult,\n ChangeEmailPayload,\n ChangePasswordPayload,\n LoginPayload,\n RegisterPayload,\n ResetPasswordPayload,\n VerifyOtpPayload,\n} from \"@ecomweb/sdk\";\n\n/** Translates the SDK's ApiResponse into a JSON response, preserving the code. */\nfunction fail(status: number, message: string, code?: string) {\n return NextResponse.json(\n { error: { message, code } },\n { status: status || 500 }\n );\n}\n\n/**\n * The HTTP method each action answers on — one entry per action, no defaults.\n *\n * Every one of these used to answer GET as well as POST, and the session\n * cookies are `sameSite: \"lax\"`, which the browser DOES send on a cross-site\n * top-level navigation. A link on any page therefore reached `logout-all`, or\n * `google/complete` with a code of the attacker's choosing. The split is\n * enumerated rather than inferred so that adding an action forces a decision\n * here; an action missing from this map is a 404, not a silent GET.\n *\n * GET is limited to the two reads the client polls (`config`, `session`) and\n * the two halves of the OAuth hand-off: `google/url` is a read, and\n * `google/complete` is the browser's landing spot in a redirect chain, so it\n * cannot be anything else. It carries its own browser binding instead — see\n * the nonce cookie below.\n */\nconst AUTH_ACTION_METHOD = {\n config: \"GET\",\n session: \"GET\",\n \"google/url\": \"GET\",\n \"google/complete\": \"GET\",\n\n register: \"POST\",\n login: \"POST\",\n \"otp/request\": \"POST\",\n \"otp/verify\": \"POST\",\n anonymous: \"POST\",\n logout: \"POST\",\n \"logout-all\": \"POST\",\n \"verify-email\": \"POST\",\n \"resend-verification\": \"POST\",\n \"forgot-password\": \"POST\",\n \"reset-password\": \"POST\",\n \"change-password\": \"POST\",\n \"change-email\": \"POST\",\n \"change-email/confirm\": \"POST\",\n} as const satisfies Record<string, \"GET\" | \"POST\">;\n\ntype AuthAction = keyof typeof AUTH_ACTION_METHOD;\n\n/**\n * The query parameter carrying the OAuth nonce home.\n *\n * `redirect_to` is the only field that survives the round trip through the\n * signed `state` and back out as `next=`, and the backend requires it to be a\n * relative path, so the nonce travels inside it as a query parameter of a\n * path-only URL. The storefront is both the producer and the only consumer of\n * this shape.\n */\nconst OAUTH_NONCE_PARAM = \"sf_oauth\";\nconst OAUTH_NEXT_PARAM = \"next\";\n\n/** Tokens go into cookies and never into the response body. */\nfunction withSession(\n storeRef: string,\n cookiePath: string,\n result: AuthResult,\n body: Record<string, unknown> = {}\n) {\n const response = NextResponse.json({ identity: result.identity, ...body });\n\n if (result.access_token && result.refresh_token) {\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: result.access_token,\n refresh_token: result.refresh_token,\n },\n cookiePath\n );\n }\n\n return response;\n}\n\nfunction methodNotAllowed(allowed: \"GET\" | \"POST\") {\n return NextResponse.json(\n {\n error: {\n message: `This action requires ${allowed}`,\n code: \"METHOD_NOT_ALLOWED\",\n },\n },\n { status: 405, headers: { allow: allowed } }\n );\n}\n\nexport async function handleAuthRoute(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const action = segments.join(\"/\");\n const allowedMethod = AUTH_ACTION_METHOD[action as AuthAction];\n\n if (!allowedMethod) return fail(404, `Unknown auth action: ${action}`);\n if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);\n\n // The shopper's address, not this server's: the backend rate-limits per\n // `storeId:clientIp` and every one of these calls is made server-side.\n const auth = createAuthApi(\n storeRef,\n clientIpFrom(request.headers),\n storePreviewTokenFor(request, storeRef)\n );\n const hostMapped = isHostMappedRequest(request);\n const cookiePath = authCookiePath(storeRef, hostMapped);\n const tokens = readAuthCookies(request.cookies, storeRef, cookiePath);\n\n const body: Record<string, any> =\n request.method === \"POST\" ? await request.json().catch(() => ({})) : {};\n\n switch (action) {\n case \"config\": {\n const res = await auth.getAuthConfig();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"register\": {\n // Never trust a browser-supplied `anonymous_identity_id`: the backend\n // only checks store_id / is_anonymous / !deleted_at, not ownership, so\n // forwarding it would let anyone who learns an anonymous UUID register\n // against it and inherit its cart and orders. Whatever the browser sent\n // is dropped and the id is derived from the httpOnly session instead.\n const payload: Record<string, any> = { ...body };\n delete payload.anonymous_identity_id;\n\n let anonymousIdentityId: string | undefined;\n\n if (tokens) {\n const current = await auth.me(tokens.access_token);\n if (current.success && current.data?.is_anonymous) {\n anonymousIdentityId = current.data.id;\n }\n }\n\n const res = await auth.register({\n ...payload,\n anonymous_identity_id: anonymousIdentityId,\n } as RegisterPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Register never returns tokens, by design. The verification binding\n // stays in an httpOnly cookie so only this browser's click on the\n // mailed link keeps the password just set (absent on older APIs).\n const registered = NextResponse.json({ registered: true });\n const verificationBinding = res.data?.verification_binding;\n if (verificationBinding) {\n writeEmailBindingCookie(\n registered,\n \"verify-email\",\n storeRef,\n verificationBinding,\n cookiePath\n );\n }\n return registered;\n }\n\n case \"login\": {\n const res = await auth.login(body as LoginPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"otp/request\": {\n const res = await auth.requestOtp(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"otp/verify\": {\n const res = await auth.verifyOtp(body as VerifyOtpPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"anonymous\": {\n const res = await auth.anonymous();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"session\": {\n if (!tokens) return NextResponse.json({ identity: null });\n const res = await auth.me(tokens.access_token);\n if (!res.success) return NextResponse.json({ identity: null });\n return NextResponse.json({ identity: res.data });\n }\n\n case \"logout\": {\n // Best-effort revoke: a failed call must still clear the browser's\n // cookies, or the shopper is stuck logged in against a dead session.\n if (tokens) {\n await auth\n .logout(tokens.access_token, tokens.refresh_token)\n .catch(() => undefined);\n }\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"logout-all\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.logoutAll(tokens.access_token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"verify-email\": {\n const binding = request.cookies.get(\n emailBindingCookieName(\"verify-email\", storeRef, cookiePath)\n )?.value;\n const res = await auth.verifyEmail(body.token, binding || undefined);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n const verified = NextResponse.json(res.data);\n clearEmailBindingCookie(verified, \"verify-email\", storeRef, cookiePath);\n return verified;\n }\n\n case \"resend-verification\": {\n const res = await auth.resendVerification(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"forgot-password\": {\n const res = await auth.forgotPassword(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"reset-password\": {\n const res = await auth.resetPassword(body as ResetPasswordPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"change-password\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changePassword(\n tokens.access_token,\n body as ChangePasswordPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Changing a password revokes sessions server-side; drop the cookies too.\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"change-email\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changeEmail(\n tokens.access_token,\n body as ChangeEmailPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Kept for the confirm click, like the verification binding above.\n const sent = NextResponse.json({ sent: true });\n const confirmationBinding = res.data?.confirmation_binding;\n if (confirmationBinding) {\n writeEmailBindingCookie(\n sent,\n \"change-email\",\n storeRef,\n confirmationBinding,\n cookiePath\n );\n }\n return sent;\n }\n\n case \"change-email/confirm\": {\n const binding = request.cookies.get(\n emailBindingCookieName(\"change-email\", storeRef, cookiePath)\n )?.value;\n const res = await auth.confirmEmailChange(\n body.token,\n binding || undefined\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n const confirmed = NextResponse.json(res.data);\n clearEmailBindingCookie(confirmed, \"change-email\", storeRef, cookiePath);\n return confirmed;\n }\n\n case \"google/url\": {\n // Proxied rather than called from the browser so the storefront API key\n // stays server-side.\n const base = storeBasePathFor(request, storeRef);\n const wanted = safeRedirectPath(\n request.nextUrl.searchParams.get(\"redirect_to\"),\n publicNextUrl(request).toString()\n );\n\n // The nonce is minted here, remembered in an httpOnly cookie, and rides\n // out inside `redirect_to`. `google/complete` refuses to issue a session\n // unless the two match, which is what makes that GET unforgeable.\n // `globalThis.crypto` rather than a node:crypto import: this module is\n // bundled for whichever runtime the route runs in.\n const nonce = globalThis.crypto.randomUUID();\n const carrier = new URLSearchParams({\n [OAUTH_NONCE_PARAM]: nonce,\n [OAUTH_NEXT_PARAM]: wanted,\n });\n\n const res = await auth.getGoogleUrl(`${base}/?${carrier.toString()}`);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n\n const response = NextResponse.json(res.data);\n writeOAuthNonceCookie(response, storeRef, nonce, cookiePath);\n return response;\n }\n\n case \"google/complete\": {\n // The backend redirects the BROWSER here with a one-time code. It is\n // redeemed server-side so no token ever reaches the URL bar, history,\n // or a Referer header.\n const base = storeBasePathFor(request, storeRef);\n const errorTarget = new URL(\n `${base}/auth/error?error=oauth_failed`,\n publicNextUrl(request).toString()\n );\n\n const code = request.nextUrl.searchParams.get(\"code\");\n\n // Whatever came back in `next` is the carrier this route wrote in\n // `google/url`: a relative path plus the nonce. Both halves are\n // re-validated — the path against the origin, the nonce against the\n // cookie — before anything is issued.\n const carrier = safeRedirectPath(\n request.nextUrl.searchParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const carrierParams = new URL(carrier, publicNextUrl(request).toString()).searchParams;\n const presentedNonce = carrierParams.get(OAUTH_NONCE_PARAM);\n const expectedNonce = request.cookies.get(\n oauthNonceCookieName(storeRef, cookiePath)\n )?.value;\n\n const nonceMatches =\n !!presentedNonce && !!expectedNonce && presentedNonce === expectedNonce;\n\n if (!code || !nonceMatches) {\n // A missing or mismatched nonce means this browser did not start the\n // flow: someone else's one-time code is being pushed into it. Refuse\n // before any token is exchanged, and burn the nonce either way.\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const res = await auth.exchangeGoogleCode(code);\n\n if (!res.success || !res.data?.access_token || !res.data.refresh_token) {\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const target = safeRedirectPath(\n carrierParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const response = NextResponse.redirect(\n new URL(target === \"/\" ? `${base}/` : target, publicNextUrl(request).toString())\n );\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: res.data.access_token,\n refresh_token: res.data.refresh_token,\n },\n cookiePath\n );\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n\n return response;\n }\n\n default:\n // Unreachable: AUTH_ACTION_METHOD is checked first, and every key it\n // holds has a case above. Kept so adding a key without a case is a\n // 404 rather than an undefined response.\n return fail(404, `Unknown auth action: ${action}`);\n }\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AACrC,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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F;AAEA;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,UACE,cAAc,IAAI,KAAK;AAAA,UACvB,eAAe,IAAI,KAAK;AAAA,QAC1B;AAAA,QACA;AAAA,MACF;AACA,4BAAsB,UAAU,UAAU,UAAU;AAEpD,aAAO;AAAA,IACT;AAAA,IAEA;AAIE,aAAO,KAAK,KAAK,wBAAwB,MAAM,EAAE;AAAA,EACrD;AACF;","names":["response"]}
package/dist/auth/sdk.js CHANGED
@@ -3,19 +3,23 @@ import { AuthApi } from "@ecomweb/sdk";
3
3
  import { forwardingHeaders } from "./client-ip.js";
4
4
  import { publicConfig } from "../config.js";
5
5
  import { serverConfig } from "../config/server.js";
6
+ import { STORE_PREVIEW_HEADER } from "../stores/store-preview-cookie.js";
6
7
  function backendBaseUrl() {
7
8
  return publicConfig().apiUrl;
8
9
  }
9
10
  function storefrontApiKey() {
10
11
  return serverConfig().platformApiKey;
11
12
  }
12
- async function send(method, url, data, options, clientIp) {
13
+ async function send(method, url, data, options, clientIp, previewToken) {
13
14
  try {
14
15
  const response = await fetch(`${backendBaseUrl()}${url}`, {
15
16
  method,
16
17
  headers: {
17
18
  "Content-Type": "application/json",
18
19
  "x-storefront-api-key": storefrontApiKey(),
20
+ // A store preview opens a coming soon store for reads only, so the
21
+ // token rides on GETs (auth config, me) and never on writes.
22
+ ...previewToken && method === "GET" ? { [STORE_PREVIEW_HEADER]: previewToken } : {},
19
23
  ...options?.headers ?? {},
20
24
  // The backend's auth throttler keys on the shopper IP, which it only
21
25
  // reads from `x-forwarded-for` when the forwarder secret rides along.
@@ -55,17 +59,17 @@ async function send(method, url, data, options, clientIp) {
55
59
  };
56
60
  }
57
61
  }
58
- function authHttpClient(clientIp) {
62
+ function authHttpClient(clientIp, previewToken) {
59
63
  return {
60
- get: (url, options) => send("GET", url, void 0, options, clientIp),
64
+ get: (url, options) => send("GET", url, void 0, options, clientIp, previewToken),
61
65
  post: (url, data, options) => send("POST", url, data, options, clientIp),
62
66
  put: (url, data, options) => send("PUT", url, data, options, clientIp),
63
67
  patch: (url, data, options) => send("PATCH", url, data, options, clientIp),
64
68
  delete: (url, options) => send("DELETE", url, void 0, options, clientIp)
65
69
  };
66
70
  }
67
- function createAuthApi(storeRef, clientIp) {
68
- return new AuthApi(authHttpClient(clientIp), storeRef);
71
+ function createAuthApi(storeRef, clientIp, previewToken) {
72
+ return new AuthApi(authHttpClient(clientIp, previewToken), storeRef);
69
73
  }
70
74
  export {
71
75
  authHttpClient,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\n\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * StorefrontApiKeyGuard fronts every customer-auth route and also resolves\n * :storeRef into request.storeId, so a missing key fails before auth runs.\n *\n * Only NEXT_PUBLIC_PLATFORM_API_KEY exists in this repo today (see .env /\n * .env.example, lib/api/client.ts, lib/api/server-client.ts). PLATFORM_API_KEY\n * is checked first so a server-only key can be introduced later without\n * another code change.\n */\nexport function storefrontApiKey(): string {\n return serverConfig().platformApiKey;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(`${backendBaseUrl()}${url}`, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontApiKey(),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return { success: true, data: body as T };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(clientIp?: string): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n */\nexport function createAuthApi(storeRef: string, clientIp?: string): AuthApi {\n return new AuthApi(authHttpClient(clientIp), storeRef);\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,eAAe;AAExB,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAQtB,SAAS,iBAAyB;AACvC,SAAO,aAAa,EAAE;AACxB;AAWO,SAAS,mBAA2B;AACzC,SAAO,aAAa,EAAE;AACxB;AAEA,e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AAa,MAAgB,YACtC,KAAQ,SAAS,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC/C,QAAQ,CAAI,KAAa,YACvB,KAAQ,UAAU,KAAK,QAAW,SAAS,QAAQ;AAAA,EACvD;AACF;AAMO,SAAS,cAAc,UAAkB,UAA4B;AAC1E,SAAO,IAAI,QAAQ,eAAe,QAAQ,GAAG,QAAQ;AACvD;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\nimport { STORE_PREVIEW_HEADER } from \"../stores/store-preview-cookie\";\n\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * StorefrontApiKeyGuard fronts every customer-auth route and also resolves\n * :storeRef into request.storeId, so a missing key fails before auth runs.\n *\n * Only NEXT_PUBLIC_PLATFORM_API_KEY exists in this repo today (see .env /\n * .env.example, lib/api/client.ts, lib/api/server-client.ts). PLATFORM_API_KEY\n * is checked first so a server-only key can be introduced later without\n * another code change.\n */\nexport function storefrontApiKey(): string {\n return serverConfig().platformApiKey;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string,\n previewToken?: string | null\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(`${backendBaseUrl()}${url}`, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontApiKey(),\n // A store preview opens a coming soon store for reads only, so the\n // token rides on GETs (auth config, me) and never on writes.\n ...(previewToken && method === \"GET\"\n ? { [STORE_PREVIEW_HEADER]: previewToken }\n : {}),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return { success: true, data: body as T };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(\n clientIp?: string,\n previewToken?: string | null\n): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp, previewToken),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n * @param previewToken the request's store preview token\n * (`storePreviewTokenFrom`), sent as `X-Store-Preview` on GETs so a\n * previewer of a coming soon store still gets the auth config and `me`.\n */\nexport function createAuthApi(\n storeRef: string,\n clientIp?: string,\n previewToken?: string | null\n): AuthApi {\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QAAQ,MAAM,UAAU;AAAA,QAClD,YAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,eACd,UACA,cACa;AACb,SAAO;AAAA,IACL,KAAK,CAAI,KAAa,YACpB,KAAQ,OAAO,KAAK,QAAW,SAAS,UAAU,YAAY;AAAA,IAChE,MAAM,CAAI,KAAa,MAAgB,YACrC,KAAQ,QAAQ,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC9C,KAAK,CAAI,KAAa,MAAgB,YACpC,KAAQ,OAAO,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC7C,OAAO,CAAI,KAAa,MAAgB,YACtC,KAAQ,SAAS,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC/C,QAAQ,CAAI,KAAa,YACvB,KAAQ,UAAU,KAAK,QAAW,SAAS,QAAQ;AAAA,EACvD;AACF;AASO,SAAS,cACd,UACA,UACA,cACS;AACT,SAAO,IAAI,QAAQ,eAAe,UAAU,YAAY,GAAG,QAAQ;AACrE;","names":[]}
@@ -4,6 +4,7 @@ import { cookies, headers } from "next/headers";
4
4
  import { authCookiePathFor, readAuthCookies } from "./cookies.js";
5
5
  import { clientIpFrom } from "./client-ip.js";
6
6
  import { createAuthApi } from "./sdk.js";
7
+ import { storePreviewTokenFrom } from "../stores/store-preview-cookie.js";
7
8
  const getServerIdentity = cache(
8
9
  async (storeRef) => {
9
10
  const requestHeaders = await headers();
@@ -13,9 +14,11 @@ const getServerIdentity = cache(
13
14
  authCookiePathFor({ headers: requestHeaders }, storeRef)
14
15
  );
15
16
  if (!tokens) return null;
16
- const me = await createAuthApi(storeRef, clientIpFrom(requestHeaders)).me(
17
- tokens.access_token
18
- );
17
+ const me = await createAuthApi(
18
+ storeRef,
19
+ clientIpFrom(requestHeaders),
20
+ storePreviewTokenFrom(await cookies(), { headers: requestHeaders })
21
+ ).me(tokens.access_token);
19
22
  return me.success ? me.data ?? null : null;
20
23
  }
21
24
  );
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/session.ts"],"sourcesContent":["import \"server-only\";\n\nimport { cache } from \"react\";\nimport { cookies, headers } from \"next/headers\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { authCookiePathFor, readAuthCookies } from \"./cookies\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { createAuthApi } from \"./sdk\";\n\n/**\n * The one server-side \"who is this request?\" read.\n *\n * Wrapped in React `cache()` so several server components in the same render\n * share a single `me()` round trip — `lib/auth/sdk.ts` sends `cache: \"no-store\"`,\n * so without this every layout and page would issue its own.\n */\nexport const getServerIdentity = cache(\n async (storeRef: string): Promise<CurrentIdentity | null> => {\n // There is no NextRequest in a server component, but the incoming\n // request's headers are still reachable: they name the cookie path, and\n // the backend rate-limits this call per `storeId:clientIp`, so it has to\n // carry the shopper's address like every other server-side auth call does.\n const requestHeaders = await headers();\n const tokens = readAuthCookies(\n await cookies(),\n storeRef,\n authCookiePathFor({ headers: requestHeaders }, storeRef)\n );\n if (!tokens) return null;\n\n const me = await createAuthApi(storeRef, clientIpFrom(requestHeaders)).me(\n tokens.access_token\n );\n return me.success ? (me.data ?? null) : null;\n }\n);\n\n/**\n * Whether the request carries a real, logged-in shopper session.\n *\n * An **anonymous** identity (the guest-cart session the backend issues) has a\n * perfectly valid token but is not a logged-in shopper: it has no\n * `customer_id`, no name and no email. Treating it as authenticated admits it\n * to `/account/*` — where every page is empty or errors — and, worse, bounces\n * it away from `/login`, so a guest with a cart could never sign in.\n */\nexport async function hasCustomerSession(storeRef: string): Promise<boolean> {\n const identity = await getServerIdentity(storeRef);\n return !!identity && !identity.is_anonymous;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,aAAa;AACtB,SAAS,SAAS,eAAe;AAEjC,SAAS,mBAAmB,uBAAuB;AACnD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AASvB,MAAM,oBAAoB;AAAA,EAC/B,OAAO,aAAsD;AAK3D,UAAM,iBAAiB,MAAM,QAAQ;AACrC,UAAM,SAAS;AAAA,MACb,MAAM,QAAQ;AAAA,MACd;AAAA,MACA,kBAAkB,EAAE,SAAS,eAAe,GAAG,QAAQ;AAAA,IACzD;AACA,QAAI,CAAC,OAAQ,QAAO;AAEpB,UAAM,KAAK,MAAM,cAAc,UAAU,aAAa,cAAc,CAAC,EAAE;AAAA,MACrE,OAAO;AAAA,IACT;AACA,WAAO,GAAG,UAAW,GAAG,QAAQ,OAAQ;AAAA,EAC1C;AACF;AAWA,eAAsB,mBAAmB,UAAoC;AAC3E,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,SAAO,CAAC,CAAC,YAAY,CAAC,SAAS;AACjC;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/session.ts"],"sourcesContent":["import \"server-only\";\n\nimport { cache } from \"react\";\nimport { cookies, headers } from \"next/headers\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { authCookiePathFor, readAuthCookies } from \"./cookies\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { createAuthApi } from \"./sdk\";\nimport { storePreviewTokenFrom } from \"../stores/store-preview-cookie\";\n\n/**\n * The one server-side \"who is this request?\" read.\n *\n * Wrapped in React `cache()` so several server components in the same render\n * share a single `me()` round trip — `lib/auth/sdk.ts` sends `cache: \"no-store\"`,\n * so without this every layout and page would issue its own.\n */\nexport const getServerIdentity = cache(\n async (storeRef: string): Promise<CurrentIdentity | null> => {\n // There is no NextRequest in a server component, but the incoming\n // request's headers are still reachable: they name the cookie path, and\n // the backend rate-limits this call per `storeId:clientIp`, so it has to\n // carry the shopper's address like every other server-side auth call does.\n const requestHeaders = await headers();\n const tokens = readAuthCookies(\n await cookies(),\n storeRef,\n authCookiePathFor({ headers: requestHeaders }, storeRef)\n );\n if (!tokens) return null;\n\n const me = await createAuthApi(\n storeRef,\n clientIpFrom(requestHeaders),\n storePreviewTokenFrom(await cookies(), { headers: requestHeaders })\n ).me(tokens.access_token);\n return me.success ? (me.data ?? null) : null;\n }\n);\n\n/**\n * Whether the request carries a real, logged-in shopper session.\n *\n * An **anonymous** identity (the guest-cart session the backend issues) has a\n * perfectly valid token but is not a logged-in shopper: it has no\n * `customer_id`, no name and no email. Treating it as authenticated admits it\n * to `/account/*` — where every page is empty or errors — and, worse, bounces\n * it away from `/login`, so a guest with a cart could never sign in.\n */\nexport async function hasCustomerSession(storeRef: string): Promise<boolean> {\n const identity = await getServerIdentity(storeRef);\n return !!identity && !identity.is_anonymous;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,aAAa;AACtB,SAAS,SAAS,eAAe;AAEjC,SAAS,mBAAmB,uBAAuB;AACnD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AAS/B,MAAM,oBAAoB;AAAA,EAC/B,OAAO,aAAsD;AAK3D,UAAM,iBAAiB,MAAM,QAAQ;AACrC,UAAM,SAAS;AAAA,MACb,MAAM,QAAQ;AAAA,MACd;AAAA,MACA,kBAAkB,EAAE,SAAS,eAAe,GAAG,QAAQ;AAAA,IACzD;AACA,QAAI,CAAC,OAAQ,QAAO;AAEpB,UAAM,KAAK,MAAM;AAAA,MACf;AAAA,MACA,aAAa,cAAc;AAAA,MAC3B,sBAAsB,MAAM,QAAQ,GAAG,EAAE,SAAS,eAAe,CAAC;AAAA,IACpE,EAAE,GAAG,OAAO,YAAY;AACxB,WAAO,GAAG,UAAW,GAAG,QAAQ,OAAQ;AAAA,EAC1C;AACF;AAWA,eAAsB,mBAAmB,UAAoC;AAC3E,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,SAAO,CAAC,CAAC,YAAY,CAAC,SAAS;AACjC;","names":[]}
@@ -156,6 +156,9 @@ function useCheckout({
156
156
  },
157
157
  notes: input.notes || void 0,
158
158
  promotion_id: promotionState.appliedPromotion?.id || void 0,
159
+ // The API applies a discount-code promotion only when the code itself
160
+ // comes with its id; older APIs ignore the field.
161
+ promotion_code: promotionState.appliedPromotion?.code || void 0,
159
162
  ...savedAddressId && { customer_address_id: savedAddressId },
160
163
  items: items.map((item) => ({
161
164
  product_id: item.productId,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"../stores/store-preview-guard\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n // A preview is read-only: the API would refuse the order anyway.\n if (isBrowserStorePreview()) {\n return {\n kind: \"error\",\n message: STORE_PREVIEW_READ_ONLY_MESSAGE,\n code: \"STORE_COMING_SOON\",\n };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown (or the code is used up). Keeping the code would fail every\n // retry the same way.\n if (\n code === \"ORDER_PROMOTION_NOT_APPLICABLE\" ||\n code === \"PROMOTION_USAGE_LIMIT_REACHED\"\n ) {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,6BAA6B;AACtC,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,yBAAmD;AAC5D;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,uBAAuB,yBAAyB;AACzD,SAAS,wBAAwB;AAiEjC,MAAM,2BAA2B,CAAC,QAAgB;AAChD,SAAO,SAAS,OAAO;AACzB;AAOO,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA;AAAA,EACA,wBAAwB;AAAA,EACxB,oBAAoB;AACtB,GAAuB;AACrB,QAAM,QAAQ,aAAa;AAC3B,QAAM,SAAS,UAAU;AACzB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW;AAAA,EACb,IAAI,QAAQ;AACZ,QAAM,EAAE,MAA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A,MACnB,SAAS,cAAc;AAAA,MACvB,cAAc,cAAc;AAAA,MAC5B,eAAe,cAAc;AAAA,MAC7B,eAAe,cAAc;AAAA,MAC7B,mBAAmB,cAAc;AAAA;AAAA,MAEjC,YAAY,cAAc;AAAA,MAC1B,kBAAkB,cAAc;AAAA,MAChC,gBAAgB,cAAc;AAAA,MAC9B,cAAc,cAAc;AAAA,MAC5B,OAAO,cAAc;AAAA,IACvB;AAAA,IACA,WAAW;AAAA,MACT,MAAM,eAAe;AAAA,MACrB,SAAS,eAAe;AAAA,MACxB,SAAS,eAAe;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,cAAc,eAAe;AAAA,MAC7B,OAAO,eAAe;AAAA,MACtB,UAAU,eAAe;AAAA,MACzB,QAAQ,eAAe;AAAA,MACvB,iBAAiB,eAAe;AAAA,IAClC;AAAA;AAAA;AAAA,IAGA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,cAAc;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"../stores/store-preview-guard\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n // A preview is read-only: the API would refuse the order anyway.\n if (isBrowserStorePreview()) {\n return {\n kind: \"error\",\n message: STORE_PREVIEW_READ_ONLY_MESSAGE,\n code: \"STORE_COMING_SOON\",\n };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n // The API applies a discount-code promotion only when the code itself\n // comes with its id; older APIs ignore the field.\n promotion_code: promotionState.appliedPromotion?.code || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown (or the code is used up). Keeping the code would fail every\n // retry the same way. PROMOTION_IDENTITY_REQUIRED keeps the code: the\n // shopper only has to add an email and place again.\n if (\n code === \"ORDER_PROMOTION_NOT_APPLICABLE\" ||\n code === \"PROMOTION_USAGE_LIMIT_REACHED\"\n ) {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,6BAA6B;AACtC,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,yBAAmD;AAC5D;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,uBAAuB,yBAAyB;AACzD,SAAS,wBAAwB;AAiEjC,MAAM,2BAA2B,CAAC,QAAgB;AAChD,SAAO,SAAS,OAAO;AACzB;AAOO,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA;AAAA,EACA,wBAAwB;AAAA,EACxB,oBAAoB;AACtB,GAAuB;AACrB,QAAM,QAAQ,aAAa;AAC3B,QAAM,SAAS,UAAU;AACzB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW;AAAA,EACb,IAAI,QAAQ;AACZ,QAAM,EAAE,MAAM,YAAY,IAAI,QAAQ;AAEtC,QAAM,CAAC,gBAAgB,iBAAiB,IAAI;AAAA,IAC1C,CAAC;AAAA,EACH;AACA,QAAM,CAAC,yBAAyB,0BAA0B,IAAI,SAAS,IAAI;AAC3E,QAAM,CAAC,gBAAgB,iBAAiB,IAAI;AAAA,IAC1C;AAAA,EACF;AACA,QAAM,CAAC,cAAc,eAAe,IAAI,SAAS,KAAK;AAKtD,QAAM,CAAC,eAAe,gBAAgB,IAAI,SAGhC,IAAI;AACd,QAAM,CAAC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AAA,IACA,WAAW;AAAA,MACT,MAAM,eAAe;AAAA,MACrB,SAAS,eAAe;AAAA,MACxB,SAAS,eAAe;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,cAAc,eAAe;AAAA,MAC7B,OAAO,eAAe;AAAA,MACtB,UAAU,eAAe;AAAA,MACzB,QAAQ,eAAe;AAAA,MACvB,iBAAiB,eAAe;AAAA,IAClC;AAAA;AAAA;AAAA,IAGA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,cAAc;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -23,6 +23,7 @@ import { getStoreByHost } from "../stores/get-store-by-host.js";
23
23
  import { STORE_COMING_SOON_REDIRECT_PATH } from "../stores/store-coming-soon.js";
24
24
  import {
25
25
  applyStorePreview,
26
+ firstLivePreviewToken,
26
27
  STORE_PREVIEW_PATH,
27
28
  STORE_PREVIEW_TOKEN_HEADER,
28
29
  storePreviewCookieName
@@ -80,7 +81,10 @@ function hasStorePreview(req, cookiePath) {
80
81
  return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;
81
82
  }
82
83
  function hostLookupPreviewToken(req) {
83
- return req.cookies.get(storePreviewCookieName("/"))?.value || req.cookies.get(themePreviewCookieName("/"))?.value || null;
84
+ return firstLivePreviewToken(
85
+ req.cookies.get(storePreviewCookieName("/"))?.value,
86
+ req.cookies.get(themePreviewCookieName("/"))?.value
87
+ );
84
88
  }
85
89
  function storeRefFromPath(pathname) {
86
90
  const match = /^\/store\/([^/]+)/.exec(pathname);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\nimport { STORE_COMING_SOON_REDIRECT_PATH } from \"../stores/store-coming-soon\";\nimport {\n applyStorePreview,\n STORE_PREVIEW_PATH,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewCookieName,\n} from \"../stores/store-preview-cookie\";\nimport { getStoreSubdomain } from \"../stores/store-subdomain\";\nimport { recordStoreRequest } from \"../stores/store-traffic\";\nimport {\n PREVIEW_HOST_ROBOTS,\n THEME_PREVIEW_HOST_HEADER,\n} from \"../theme/preview-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * Cache-Control on the subdomain → custom domain 301. An hour keeps the 301\n * for search engines and caps how long browsers follow it after the merchant\n * removes the domain.\n */\nconst CUSTOM_DOMAIN_REDIRECT_CACHE = \"public, max-age=3600\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (\n req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) ||\n hasThemePreview(req, authCookiePath(storeRef, true))\n )\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url, withoutInternalHeaders(req));\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The init for a response that lets the request through without the full\n * downstream headers (metadata files, the \"domain not connected\" and apex\n * 404 rewrites): the client's headers minus the middleware's internal ones.\n * With it, every request the matcher covers reaches the app with no client\n * copy of them, so a server-side reader can trust them there.\n */\nfunction withoutInternalHeaders(req: NextRequest): {\n request: { headers: Headers };\n} {\n const headers = new Headers(req.headers);\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n return { request: { headers } };\n}\n\n/** True while the store preview cookie at `cookiePath` holds a token. */\nfunction hasStorePreview(req: NextRequest, cookiePath: string): boolean {\n return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;\n}\n\n/**\n * The preview token for the host lookup on a store host: the store preview\n * cookie, else the theme preview cookie (`?preview_theme=` on the store's own\n * host), both at `/`. Read from the cookies only, never through\n * `storePreviewTokenFrom`: that trusts `STORE_PREVIEW_TOKEN_HEADER`, and on\n * the middleware's incoming request that header is whatever the client sent.\n */\nfunction hostLookupPreviewToken(req: NextRequest): string | null {\n return (\n req.cookies.get(storePreviewCookieName(\"/\"))?.value ||\n req.cookies.get(themePreviewCookieName(\"/\"))?.value ||\n null\n );\n}\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Where a stored redirect sends this request, on this request's own host.\n *\n * The destination is parsed as a URL rather than assigned to `pathname`,\n * which would percent-encode its `?` and lose the query. A destination with\n * a query (or fragment) keeps its own; one without carries the request's\n * query over, as before. Only the destination's path, query and fragment are\n * used, so the redirect never leaves the store's host.\n */\nfunction redirectDestinationUrl(\n req: NextRequest,\n destination: string,\n pathPrefix = \"\"\n) {\n const url = publicNextUrl(req);\n const parsed = new URL(destination, \"http://destination.invalid\");\n url.pathname = `${pathPrefix}${parsed.pathname}`;\n if (parsed.search) url.search = parsed.search;\n if (parsed.hash) url.hash = parsed.hash;\n return url;\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path, pathPrefix),\n { status: redirect.redirect_type }\n );\n}\n\n/**\n * `/store/<ref>/…` on the platform apex: never served here, sent to the\n * store's own subdomain instead.\n *\n * On the apex every store shares one origin, and a merchant's embedded\n * scripts run there. A cookie's Path is no boundary between pages of one\n * origin: store A's script could fetch `/store/B/api/…` with B's shopper\n * cookies attached, or frame `/store/B` and read it. Each store's subdomain\n * is its own origin. Localhost keeps path-based access (it is not the apex).\n *\n * 302 (307 for non-GET), not 301: the merchant may change the subdomain.\n * The subdomain then sends shoppers on to a custom domain when there is one.\n * No store, no subdomain, or the API unreachable: the 404 page.\n */\nasync function apexStoreResponse(\n req: NextRequest,\n storeRef: string,\n platformDomain: string\n): Promise<NextResponse> {\n let subdomain: string | null = null;\n try {\n subdomain = await getStoreSubdomain(storeRef);\n } catch (error) {\n console.error(\"Store lookup failed for apex path:\", storeRef, error);\n }\n\n if (!subdomain) {\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n url.search = \"\";\n return NextResponse.rewrite(url, withoutInternalHeaders(req));\n }\n\n const prefix = multiTenantStorePath(storeRef);\n const pathname = req.nextUrl.pathname;\n const target = publicNextUrl(req);\n target.hostname = `${subdomain}.${platformDomain}`;\n target.port = \"\";\n target.pathname = pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length)\n : \"/\";\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next(withoutInternalHeaders(req));\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n const isPlatformApex =\n host === platformDomain || host === `www.${platformDomain}`;\n if (isPlatformApex) {\n const apexStoreRef = storeRefFromPath(pathname);\n if (apexStoreRef)\n return apexStoreResponse(req, apexStoreRef, platformDomain);\n }\n\n // The dashboard's preview link on the store's own host. Before the lookup:\n // a coming soon store's host resolves to nothing until the cookie is set.\n if (hostIdentifiesStore && pathname === STORE_PREVIEW_PATH) {\n return applyStorePreview(req, \"/\", \"/\");\n }\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n let hostStoreComingSoon = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n // A preview host's store preview token for a coming soon store (lookup).\n let storePreviewToken: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore)\n return NextResponse.next(withoutInternalHeaders(req));\n\n if (hostIdentifiesStore) {\n try {\n // Without a token, the plain call: its answer is cached for the host.\n const previewToken = hostLookupPreviewToken(req);\n const lookup = previewToken\n ? await getStoreByHost(host, { previewToken })\n : await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n hostStoreComingSoon = !storeRef && !!lookup.comingSoon;\n previewSlug = storeRef ? lookup.previewSlug : null;\n storePreviewToken = previewSlug ? lookup.storePreviewToken || null : null;\n\n // Nothing on a preview host is for search engines.\n if (previewSlug && isMetadataFile) {\n return pathname === \"/robots.txt\"\n ? new NextResponse(PREVIEW_HOST_ROBOTS, {\n headers: { \"content-type\": \"text/plain\" },\n })\n : new NextResponse(null, { status: 404 });\n }\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to\n // custom domain. Not a preview host: it is the theme's, not the store's.\n if (isSubDomain && domain && domain !== host && !previewSlug) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n const response = NextResponse.redirect(url, { status: 301 });\n // Browsers keep an uncached 301 forever: if the merchant removes a\n // broken domain, shoppers would never come back to the subdomain.\n response.headers.set(\"Cache-Control\", CUSTOM_DOMAIN_REDIRECT_CACHE);\n return response;\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n if (storeRef) recordStoreRequest(storeRef);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1). A coming soon store's own host resolves\n // no store until a preview token comes with the lookup, so there the link\n // becomes the host's `/` cookie, the lookup's fallback token\n // (hostLookupPreviewToken).\n if (hostStoreComingSoon) {\n const preview = applyThemePreview(req, \"/\");\n if (preview) return preview;\n }\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n // The store preview link on the shared path-based host (localhost; the\n // apex already sent /store/<ref>/… to the store's subdomain above). Not\n // on a store host, even one that resolved no store: it takes `/preview`.\n if (\n !hostIdentifiesStore &&\n pathname === multiTenantStorePath(storeRef, STORE_PREVIEW_PATH)\n ) {\n return applyStorePreview(req, cookiePath, multiTenantStorePath(storeRef));\n }\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated =\n storeRef && cookiePath\n ? await refreshIfNearExpiry(req, storeRef, cookiePath)\n : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);\n // Set after downstreamRequestHeaders deleted any copy the client sent. On\n // every request to the preview host, the backend proxy's included.\n if (previewSlug && storePreviewToken)\n downstream.set(STORE_PREVIEW_TOKEN_HEADER, storePreviewToken);\n const init = { request: { headers: downstream } };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostStoreComingSoon) {\n // The merchant has not opened the store, and the request carried no\n // valid preview token (an expired one lands here too). Like the\n // suspended branch, the 403 carries no ref, so a platform-level page.\n // Known limitation: on the shared path-based host (localhost) nothing\n // routes here; a store that turns coming soon mid-session sends the\n // browser to /coming-soon, which resolves no store there and 404s, as\n // the apex's /store/<ref> already does for these stores.\n const url = req.nextUrl.clone();\n url.pathname = STORE_COMING_SOON_REDIRECT_PATH;\n response = NextResponse.rewrite(url, init);\n response.headers.set(\"x-robots-tag\", \"noindex\");\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n // A store preview cookie lives at `/` on a store host, even when the host\n // resolved no store (coming soon), else at the store's path.\n const storePreviewPath = hostIdentifiesStore ? \"/\" : cookiePath;\n if (\n previewSlug ||\n (cookiePath && hasThemePreview(req, cookiePath)) ||\n (storePreviewPath && hasStorePreview(req, storePreviewPath))\n ) {\n response.headers.set(\"x-robots-tag\", \"noindex\");\n }\n\n if (rotated && storeRef && cookiePath) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname))\n return NextResponse.next(withoutInternalHeaders(req));\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\n if (pathname === STORE_PREVIEW_PATH)\n return applyStorePreview(req, cookiePath, \"/\");\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path),\n { status: redirect.redirect_type }\n );\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))\n response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, coming soon stores (rewritten to /coming-soon, noindex),\n * redirects, session refresh. The store preview link (`/preview?token=`\n * on a store host, `/store/<ref>/preview?token=` on localhost) becomes a\n * cookie before the lookup, and the lookup carries that token.\n * - single: the `/preview?token=` link, redirects and session refresh.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\",\n ],\n};\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAsB,oBAAoB;AAE1C,SAAS,gBAAgB,wBAAwB;AACjD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,sBAAsB;AAC/B,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP,MAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMA,MAAM,0BAA0B,CAAC,eAAe,cAAc;AAG9D,MAAM,4BAA4B;AAOlC,MAAM,+BAA+B;AAcrC,SAAS,sBACP,KACA,MACA,UACA,aACqB;AACrB,MAAI,CAAC,YAAa,QAAO;AACzB,MACE,IAAI,QAAQ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AC/C,QAAM,UAAU,kBAAkB,KAAK,UAAU;AACjD,MAAI,QAAS,QAAO;AAEpB,MAAI;AACF,UAAM,WAAW,MAAM,eAAe,UAAU,QAAQ;AACxD,QAAI,UAAU;AACZ,aAAO,aAAa;AAAA,QAClB,uBAAuB,KAAK,SAAS,gBAAgB;AAAA,QACrD,EAAE,QAAQ,SAAS,cAAc;AAAA,MACnC;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,MAAM,0BAA0B,KAAK;AAAA,EAC/C;AAEA,QAAM,UAAU,MAAM,oBAAoB,KAAK,UAAU,UAAU;AACnE,QAAM,WAAW,aAAa,KAAK;AAAA,IACjC,SAAS;AAAA,MACP,SAAS,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,KAAK,UAAU,KAAK,gBAAgB,KAAK,UAAU;AACrE,aAAS,QAAQ,IAAI,gBAAgB,SAAS;AAChD,MAAI,SAAS;AACX,qBAAiB,UAAU,UAAU,SAAS,UAAU;AAAA,EAC1D;AACA,SAAO;AACT;AAYO,SAAS,2BACd,OAAkC,CAAC,GACU;AAC7C,SAAO,UACJ,KAAK,QAAQ,aAAa,EAAE,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef","response"]}
1
+ {"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\nimport { STORE_COMING_SOON_REDIRECT_PATH } from \"../stores/store-coming-soon\";\nimport {\n applyStorePreview,\n firstLivePreviewToken,\n STORE_PREVIEW_PATH,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewCookieName,\n} from \"../stores/store-preview-cookie\";\nimport { getStoreSubdomain } from \"../stores/store-subdomain\";\nimport { recordStoreRequest } from \"../stores/store-traffic\";\nimport {\n PREVIEW_HOST_ROBOTS,\n THEME_PREVIEW_HOST_HEADER,\n} from \"../theme/preview-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * Cache-Control on the subdomain → custom domain 301. An hour keeps the 301\n * for search engines and caps how long browsers follow it after the merchant\n * removes the domain.\n */\nconst CUSTOM_DOMAIN_REDIRECT_CACHE = \"public, max-age=3600\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (\n req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) ||\n hasThemePreview(req, authCookiePath(storeRef, true))\n )\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url, withoutInternalHeaders(req));\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The init for a response that lets the request through without the full\n * downstream headers (metadata files, the \"domain not connected\" and apex\n * 404 rewrites): the client's headers minus the middleware's internal ones.\n * With it, every request the matcher covers reaches the app with no client\n * copy of them, so a server-side reader can trust them there.\n */\nfunction withoutInternalHeaders(req: NextRequest): {\n request: { headers: Headers };\n} {\n const headers = new Headers(req.headers);\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n return { request: { headers } };\n}\n\n/** True while the store preview cookie at `cookiePath` holds a token. */\nfunction hasStorePreview(req: NextRequest, cookiePath: string): boolean {\n return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;\n}\n\n/**\n * The preview token for the host lookup on a store host: the store preview\n * cookie, else the theme preview cookie (`?preview_theme=` on the store's own\n * host), both at `/`; an expired one yields to the other. Read from the cookies only, never through\n * `storePreviewTokenFrom`: that trusts `STORE_PREVIEW_TOKEN_HEADER`, and on\n * the middleware's incoming request that header is whatever the client sent.\n */\nfunction hostLookupPreviewToken(req: NextRequest): string | null {\n return firstLivePreviewToken(\n req.cookies.get(storePreviewCookieName(\"/\"))?.value,\n req.cookies.get(themePreviewCookieName(\"/\"))?.value\n );\n}\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Where a stored redirect sends this request, on this request's own host.\n *\n * The destination is parsed as a URL rather than assigned to `pathname`,\n * which would percent-encode its `?` and lose the query. A destination with\n * a query (or fragment) keeps its own; one without carries the request's\n * query over, as before. Only the destination's path, query and fragment are\n * used, so the redirect never leaves the store's host.\n */\nfunction redirectDestinationUrl(\n req: NextRequest,\n destination: string,\n pathPrefix = \"\"\n) {\n const url = publicNextUrl(req);\n const parsed = new URL(destination, \"http://destination.invalid\");\n url.pathname = `${pathPrefix}${parsed.pathname}`;\n if (parsed.search) url.search = parsed.search;\n if (parsed.hash) url.hash = parsed.hash;\n return url;\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path, pathPrefix),\n { status: redirect.redirect_type }\n );\n}\n\n/**\n * `/store/<ref>/…` on the platform apex: never served here, sent to the\n * store's own subdomain instead.\n *\n * On the apex every store shares one origin, and a merchant's embedded\n * scripts run there. A cookie's Path is no boundary between pages of one\n * origin: store A's script could fetch `/store/B/api/…` with B's shopper\n * cookies attached, or frame `/store/B` and read it. Each store's subdomain\n * is its own origin. Localhost keeps path-based access (it is not the apex).\n *\n * 302 (307 for non-GET), not 301: the merchant may change the subdomain.\n * The subdomain then sends shoppers on to a custom domain when there is one.\n * No store, no subdomain, or the API unreachable: the 404 page.\n */\nasync function apexStoreResponse(\n req: NextRequest,\n storeRef: string,\n platformDomain: string\n): Promise<NextResponse> {\n let subdomain: string | null = null;\n try {\n subdomain = await getStoreSubdomain(storeRef);\n } catch (error) {\n console.error(\"Store lookup failed for apex path:\", storeRef, error);\n }\n\n if (!subdomain) {\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n url.search = \"\";\n return NextResponse.rewrite(url, withoutInternalHeaders(req));\n }\n\n const prefix = multiTenantStorePath(storeRef);\n const pathname = req.nextUrl.pathname;\n const target = publicNextUrl(req);\n target.hostname = `${subdomain}.${platformDomain}`;\n target.port = \"\";\n target.pathname = pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length)\n : \"/\";\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next(withoutInternalHeaders(req));\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n const isPlatformApex =\n host === platformDomain || host === `www.${platformDomain}`;\n if (isPlatformApex) {\n const apexStoreRef = storeRefFromPath(pathname);\n if (apexStoreRef)\n return apexStoreResponse(req, apexStoreRef, platformDomain);\n }\n\n // The dashboard's preview link on the store's own host. Before the lookup:\n // a coming soon store's host resolves to nothing until the cookie is set.\n if (hostIdentifiesStore && pathname === STORE_PREVIEW_PATH) {\n return applyStorePreview(req, \"/\", \"/\");\n }\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n let hostStoreComingSoon = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n // A preview host's store preview token for a coming soon store (lookup).\n let storePreviewToken: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore)\n return NextResponse.next(withoutInternalHeaders(req));\n\n if (hostIdentifiesStore) {\n try {\n // Without a token, the plain call: its answer is cached for the host.\n const previewToken = hostLookupPreviewToken(req);\n const lookup = previewToken\n ? await getStoreByHost(host, { previewToken })\n : await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n hostStoreComingSoon = !storeRef && !!lookup.comingSoon;\n previewSlug = storeRef ? lookup.previewSlug : null;\n storePreviewToken = previewSlug ? lookup.storePreviewToken || null : null;\n\n // Nothing on a preview host is for search engines.\n if (previewSlug && isMetadataFile) {\n return pathname === \"/robots.txt\"\n ? new NextResponse(PREVIEW_HOST_ROBOTS, {\n headers: { \"content-type\": \"text/plain\" },\n })\n : new NextResponse(null, { status: 404 });\n }\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to\n // custom domain. Not a preview host: it is the theme's, not the store's.\n if (isSubDomain && domain && domain !== host && !previewSlug) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n const response = NextResponse.redirect(url, { status: 301 });\n // Browsers keep an uncached 301 forever: if the merchant removes a\n // broken domain, shoppers would never come back to the subdomain.\n response.headers.set(\"Cache-Control\", CUSTOM_DOMAIN_REDIRECT_CACHE);\n return response;\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n if (storeRef) recordStoreRequest(storeRef);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1). A coming soon store's own host resolves\n // no store until a preview token comes with the lookup, so there the link\n // becomes the host's `/` cookie, the lookup's fallback token\n // (hostLookupPreviewToken).\n if (hostStoreComingSoon) {\n const preview = applyThemePreview(req, \"/\");\n if (preview) return preview;\n }\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n // The store preview link on the shared path-based host (localhost; the\n // apex already sent /store/<ref>/… to the store's subdomain above). Not\n // on a store host, even one that resolved no store: it takes `/preview`.\n if (\n !hostIdentifiesStore &&\n pathname === multiTenantStorePath(storeRef, STORE_PREVIEW_PATH)\n ) {\n return applyStorePreview(req, cookiePath, multiTenantStorePath(storeRef));\n }\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated =\n storeRef && cookiePath\n ? await refreshIfNearExpiry(req, storeRef, cookiePath)\n : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);\n // Set after downstreamRequestHeaders deleted any copy the client sent. On\n // every request to the preview host, the backend proxy's included.\n if (previewSlug && storePreviewToken)\n downstream.set(STORE_PREVIEW_TOKEN_HEADER, storePreviewToken);\n const init = { request: { headers: downstream } };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostStoreComingSoon) {\n // The merchant has not opened the store, and the request carried no\n // valid preview token (an expired one lands here too). Like the\n // suspended branch, the 403 carries no ref, so a platform-level page.\n // Known limitation: on the shared path-based host (localhost) nothing\n // routes here; a store that turns coming soon mid-session sends the\n // browser to /coming-soon, which resolves no store there and 404s, as\n // the apex's /store/<ref> already does for these stores.\n const url = req.nextUrl.clone();\n url.pathname = STORE_COMING_SOON_REDIRECT_PATH;\n response = NextResponse.rewrite(url, init);\n response.headers.set(\"x-robots-tag\", \"noindex\");\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n // A store preview cookie lives at `/` on a store host, even when the host\n // resolved no store (coming soon), else at the store's path.\n const storePreviewPath = hostIdentifiesStore ? \"/\" : cookiePath;\n if (\n previewSlug ||\n (cookiePath && hasThemePreview(req, cookiePath)) ||\n (storePreviewPath && hasStorePreview(req, storePreviewPath))\n ) {\n response.headers.set(\"x-robots-tag\", \"noindex\");\n }\n\n if (rotated && storeRef && cookiePath) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname))\n return NextResponse.next(withoutInternalHeaders(req));\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\n if (pathname === STORE_PREVIEW_PATH)\n return applyStorePreview(req, cookiePath, \"/\");\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path),\n { status: redirect.redirect_type }\n );\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))\n response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, coming soon stores (rewritten to /coming-soon, noindex),\n * redirects, session refresh. The store preview link (`/preview?token=`\n * on a store host, `/store/<ref>/preview?token=` on localhost) becomes a\n * cookie before the lookup, and the lookup carries that token.\n * - single: the `/preview?token=` link, redirects and session refresh.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\",\n ],\n};\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAsB,oBAAoB;AAE1C,SAAS,gBAAgB,wBAAwB;AACjD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,sBAAsB;AAC/B,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP,MAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMA,MAAM,0BAA0B,CAAC,eAAe,cAAc;AAG9D,MAAM,4BAA4B;AAOlC,MAAM,+BAA+B;AAcrC,SAAS,sBACP,KACA,MACA,UACA,aACqB;AACrB,MAAI,CAAC,YAAa,QAAO;AACzB,MACE,IAAI,QAAQ,aAAa,IAAI,mBAAmB,KAChD,gBAAgB,KAAK,eAAe,UAAU,IAAI,CAAC;AAEnD,WAAO;AAET,QAAM,WAAW,IAAI,QAAQ;AAC7B,QAAM,SAAS,qBAAqB,QAAQ;AAC5C,QAAM,cACJ,aAAa,UAAU,SAAS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QAClB,uBAAuB,KAAK,SAAS,gBAAgB;AAAA,QACrD,EAAE,QAAQ,SAAS,cAAc;AAAA,MACnC;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,MAAM,0BAA0B,KAAK;AAAA,EAC/C;AAEA,QAAM,UAAU,MAAM,oBAAoB,KAAK,UAAU,UAAU;AACnE,QAAM,WAAW,aAAa,KAAK;AAAA,IACjC,SAAS;AAAA,MACP,SAAS,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,KAAK,UAAU,KAAK,gBAAgB,KAAK,UAAU;AACrE,aAAS,QAAQ,IAAI,gBAAgB,SAAS;AAChD,MAAI,SAAS;AACX,qBAAiB,UAAU,UAAU,SAAS,UAAU;AAAA,EAC1D;AACA,SAAO;AACT;AAYO,SAAS,2BACd,OAAkC,CAAC,GACU;AAC7C,SAAO,UACJ,KAAK,QAAQ,aAAa,EAAE,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef","response"]}
@@ -6,7 +6,7 @@ const publicOrdersApi = {
6
6
  customer_email: contactInfo.email,
7
7
  customer_phone: contactInfo.phone
8
8
  });
9
- return result.found ? result.order : null;
9
+ return result;
10
10
  },
11
11
  /**
12
12
  * `isAuth` comes from the caller's auth context — this module is not a
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/orders/api-client.ts"],"sourcesContent":["import { createStoreSdk, sdk } from \"../sdk\";\nimport type { CreateOrderRequest, Order, OrderWithItems } from \"@ecomweb/sdk\";\n\nexport const publicOrdersApi = {\n async getPublicOrderStatus(\n storeRef: string,\n orderNumber: number,\n contactInfo: { email?: string; phone?: string }\n ): Promise<Order | null> {\n const result = await sdk.orders.lookupGuest(storeRef, {\n order_number: orderNumber,\n customer_email: contactInfo.email,\n customer_phone: contactInfo.phone,\n });\n return result.found ? result.order : null;\n },\n\n /**\n * `isAuth` comes from the caller's auth context — this module is not a\n * component and must not read context or an httpOnly cookie itself.\n *\n * When true the SDK posts to `/tenant/stores/:ref/customers/orders`, which\n * derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`\n * (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no\n * such fields to carry them in. The request reaches that guarded route\n * through the same-origin proxy, which attaches the bearer token.\n */\n async createStoreOrder(\n storeRef: string,\n data: Omit<CreateOrderRequest, \"store_id\">,\n isAuth: boolean\n ): Promise<OrderWithItems> {\n return createStoreSdk(storeRef).orders.create(\n storeRef,\n data as CreateOrderRequest,\n isAuth\n );\n },\n};\n\nexport type { CreateOrderRequest, CreateOrderItemRequest } from \"@ecomweb/sdk\";\n"],"mappings":"AAAA,SAAS,gBAAgB,WAAW;AAG7B,MAAM,kBAAkB;AAAA,EAC7B,MAAM,qBACJ,UACA,aACA,aACuB;AACvB,UAAM,SAAS,MAAM,IAAI,OAAO,YAAY,UAAU;AAAA,MACpD,cAAc;AAAA,MACd,gBAAgB,YAAY;AAAA,MAC5B,gBAAgB,YAAY;AAAA,IAC9B,CAAC;AACD,WAAO,OAAO,QAAQ,OAAO,QAAQ;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,iBACJ,UACA,MACA,QACyB;AACzB,WAAO,eAAe,QAAQ,EAAE,OAAO;AAAA,MACrC;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/orders/api-client.ts"],"sourcesContent":["import { createStoreSdk, sdk } from \"../sdk\";\nimport type { CreateOrderRequest, Order, OrderWithItems } from \"@ecomweb/sdk\";\n\nexport const publicOrdersApi = {\n async getPublicOrderStatus(\n storeRef: string,\n orderNumber: number,\n contactInfo: { email?: string; phone?: string }\n ): Promise<Order | null> {\n const result = await sdk.orders.lookupGuest(storeRef, {\n order_number: orderNumber,\n customer_email: contactInfo.email,\n customer_phone: contactInfo.phone,\n });\n return result;\n },\n\n /**\n * `isAuth` comes from the caller's auth context — this module is not a\n * component and must not read context or an httpOnly cookie itself.\n *\n * When true the SDK posts to `/tenant/stores/:ref/customers/orders`, which\n * derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`\n * (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no\n * such fields to carry them in. The request reaches that guarded route\n * through the same-origin proxy, which attaches the bearer token.\n */\n async createStoreOrder(\n storeRef: string,\n data: Omit<CreateOrderRequest, \"store_id\">,\n isAuth: boolean\n ): Promise<OrderWithItems> {\n return createStoreSdk(storeRef).orders.create(\n storeRef,\n data as CreateOrderRequest,\n isAuth\n );\n },\n};\n\nexport type { CreateOrderRequest, CreateOrderItemRequest } from \"@ecomweb/sdk\";\n"],"mappings":"AAAA,SAAS,gBAAgB,WAAW;AAG7B,MAAM,kBAAkB;AAAA,EAC7B,MAAM,qBACJ,UACA,aACA,aACuB;AACvB,UAAM,SAAS,MAAM,IAAI,OAAO,YAAY,UAAU;AAAA,MACpD,cAAc;AAAA,MACd,gBAAgB,YAAY;AAAA,MAC5B,gBAAgB,YAAY;AAAA,IAC9B,CAAC;AACD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,iBACJ,UACA,MACA,QACyB;AACzB,WAAO,eAAe,QAAQ,EAAE,OAAO;AAAA,MACrC;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/orders/use-order-status.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport type { OrderWithItems } from \"@ecomweb/sdk\";\nimport { getPaymentState } from \"../checkout/get-payment-state\";\nimport { readOrderHandoff, type OrderHandoff } from \"../checkout/order-handoff\";\nimport { pollPaymentState } from \"../checkout/payment-state-poll\";\nimport {\n resolveInitialState,\n shouldPollForConfirmation,\n type PaymentConfirmationState,\n} from \"../checkout/success-state\";\nimport { sdk } from \"../sdk\";\nimport { useStoreId } from \"../store/store-context\";\nimport { useBankTransferDetails } from \"./bank-transfer\";\n\nexport type { BankAccountView } from \"./bank-transfer\";\n\nconst CANCELLED = new Error(\"order status: unmounted\");\n\nconst timeoutWait = (ms: number) =>\n new Promise<void>(resolve => setTimeout(resolve, ms));\n\n/**\n * What the shopper should be told about a just-placed order (the\n * order-success page, which is also the payment gateway's return URL).\n *\n * Arriving back from a gateway proves nothing about the payment: the\n * provider's server-to-server callback usually lands later, so a gateway\n * order polls the API until it is paid or failed. Offline orders read the\n * checkout's handoff and never poll. See checkout/success-state.ts.\n */\nexport function useOrderStatus({\n orderCode,\n wait = timeoutWait,\n}: {\n orderCode: string | null;\n /** Delay between polls; injectable for tests. */\n wait?: (ms: number) => Promise<void>;\n}) {\n const storeRef = useStoreId();\n // Read in an effect, not a useState initialiser: storage does not exist\n // during the server render, and seeding state from it would make the first\n // client render disagree with the server's.\n const [handoff, setHandoff] = useState<OrderHandoff | null>(null);\n const [handoffLoaded, setHandoffLoaded] = useState(false);\n const [state, setState] = useState<PaymentConfirmationState>(() =>\n resolveInitialState(orderCode, null)\n );\n const [isPolling, setIsPolling] = useState(false);\n\n useEffect(() => {\n const stored = readOrderHandoff(orderCode);\n setHandoff(stored);\n setState(resolveInitialState(orderCode, stored));\n setHandoffLoaded(true);\n }, [orderCode]);\n\n // A bank transfer order needs the merchant's accounts and transfer\n // instruction, which travel on the public payment-methods endpoint.\n const bankTransfer = useBankTransferDetails(state === \"awaiting-transfer\");\n\n useEffect(() => {\n if (!orderCode) return; // no gateway return in play, nothing to poll\n // Until the handoff is read every order looks like \"confirming\"; an\n // offline one would start a poll with no callback coming.\n if (!handoffLoaded) return;\n if (!shouldPollForConfirmation(state)) return;\n\n let cancelled = false;\n setIsPolling(true);\n pollPaymentState({\n poll: () => getPaymentState(storeRef, orderCode),\n // Rejecting once unmounted ends the poll loop, not just its result.\n wait: async ms => {\n if (cancelled) throw CANCELLED;\n await wait(ms);\n if (cancelled) throw CANCELLED;\n },\n }).then(\n outcome => {\n if (cancelled) return;\n // \"pending\" (attempts exhausted, or every attempt errored) is\n // \"still-confirming\", never \"failed\": only the API says failed.\n setState(\n outcome.status === \"paid\"\n ? \"paid\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : \"still-confirming\"\n );\n setIsPolling(false);\n },\n () => {}\n );\n\n return () => {\n cancelled = true;\n };\n // state is read once to decide whether to start; re-running on every\n // transition would restart the poll it just resolved.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [orderCode, storeRef, handoffLoaded]);\n\n return {\n handoff,\n payment: { state, isPolling },\n bankTransfer: { accounts: bankTransfer.accounts, note: bankTransfer.note },\n };\n}\n\n/**\n * A guest's order, looked up by its code plus the email or phone it was\n * placed with (the view-order page).\n */\nexport function useOrderLookup({\n orderCode,\n email,\n phone,\n}: {\n orderCode: string | null;\n email?: string | null;\n phone?: string | null;\n}) {\n const storeRef = useStoreId();\n const [order, setOrder] = useState<OrderWithItems | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchOrder = useCallback(async () => {\n if (!orderCode || (!email && !phone)) {\n setError(\"Thiếu thông tin cần thiết để tra cứu đơn hàng\");\n setIsLoading(false);\n return;\n }\n try {\n setIsLoading(true);\n setError(null);\n const found = await sdk.orders.lookupGuest(storeRef, {\n order_code: orderCode,\n customer_email: email || undefined,\n customer_phone: phone || undefined,\n });\n if (!found) {\n setError(\"Không tìm thấy đơn hàng với thông tin đã cung cấp\");\n return;\n }\n setOrder(found as unknown as OrderWithItems);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"Error fetching order:\", err);\n setError(\"Có lỗi xảy ra khi tra cứu đơn hàng\");\n } finally {\n setIsLoading(false);\n }\n }, [storeRef, orderCode, email, phone]);\n\n useEffect(() => {\n fetchOrder();\n }, [fetchOrder]);\n\n return { order, isLoading, error, retry: fetchOrder };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,gBAAgB;AAEjD,SAAS,uBAAuB;AAChC,SAAS,wBAA2C;AACpD,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,WAAW;AACpB,SAAS,kBAAkB;AAC3B,SAAS,8BAA8B;AAIvC,MAAM,YAAY,IAAI,MAAM,yBAAyB;AAErD,MAAM,cAAc,CAAC,OACnB,IAAI,QAAc,aAAW,WAAW,SAAS,EAAE,CAAC;AAW/C,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA,OAAO;AACT,GAIG;AACD,QAAM,WAAW,WAAW;AAI5B,QAAM,CAAC,SAAS,UAAU,IAAI,SAA8B,IAAI;AAChE,QAAM,CAAC,eAAe,gBAAgB,IAAI,SAAS,KAAK;AACxD,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IAAmC,MAC3D,oBAAoB,WAAW,IAAI;AAAA,EACrC;AACA,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAEhD,YAAU,MAAM;AACd,UAAM,SAAS,iBAAiB,SAAS;AACzC,eAAW,MAAM;AACjB,aAAS,oBAAoB,WAAW,MAAM,CAAC;AAC/C,qBAAiB,IAAI;AAAA,EACvB,GAAG,CAAC,SAAS,CAAC;AAId,QAAM,eAAe,uBAAuB,UAAU,mBAAmB;AAEzE,YAAU,MAAM;AACd,QAAI,CAAC,UAAW;AAGhB,QAAI,CAAC,cAAe;AACpB,QAAI,CAAC,0BAA0B,KAAK,EAAG;AAEvC,QAAI,YAAY;AAChB,iBAAa,IAAI;AACjB,qBAAiB;AAAA,MACf,MAAM,MAAM,gBAAgB,UAAU,SAAS;AAAA;AAAA,MAE/C,MAAM,OAAM,OAAM;AAChB,YAAI,UAAW,OAAM;AACrB,cAAM,KAAK,EA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,IACpB;AAAA,EACF,GAAG,CAAC,UAAU,WAAW,OAAO,KAAK,CAAC;AAEtC,YAAU,MAAM;AACd,eAAW;AAAA,EACb,GAAG,CAAC,UAAU,CAAC;AAEf,SAAO,EAAE,OAAO,WAAW,OAAO,OAAO,WAAW;AACtD;","names":[]}
1
+ {"version":3,"sources":["../../src/orders/use-order-status.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport type { OrderWithItems } from \"@ecomweb/sdk\";\nimport { getPaymentState } from \"../checkout/get-payment-state\";\nimport { readOrderHandoff, type OrderHandoff } from \"../checkout/order-handoff\";\nimport { pollPaymentState } from \"../checkout/payment-state-poll\";\nimport {\n resolveInitialState,\n shouldPollForConfirmation,\n type PaymentConfirmationState,\n} from \"../checkout/success-state\";\nimport { sdk } from \"../sdk\";\nimport { useStoreId } from \"../store/store-context\";\nimport { useBankTransferDetails } from \"./bank-transfer\";\n\nexport type { BankAccountView } from \"./bank-transfer\";\n\nconst CANCELLED = new Error(\"order status: unmounted\");\n\nconst timeoutWait = (ms: number) =>\n new Promise<void>(resolve => setTimeout(resolve, ms));\n\n/**\n * What the shopper should be told about a just-placed order (the\n * order-success page, which is also the payment gateway's return URL).\n *\n * Arriving back from a gateway proves nothing about the payment: the\n * provider's server-to-server callback usually lands later, so a gateway\n * order polls the API until it is paid or failed. Offline orders read the\n * checkout's handoff and never poll. See checkout/success-state.ts.\n */\nexport function useOrderStatus({\n orderCode,\n wait = timeoutWait,\n}: {\n orderCode: string | null;\n /** Delay between polls; injectable for tests. */\n wait?: (ms: number) => Promise<void>;\n}) {\n const storeRef = useStoreId();\n // Read in an effect, not a useState initialiser: storage does not exist\n // during the server render, and seeding state from it would make the first\n // client render disagree with the server's.\n const [handoff, setHandoff] = useState<OrderHandoff | null>(null);\n const [handoffLoaded, setHandoffLoaded] = useState(false);\n const [state, setState] = useState<PaymentConfirmationState>(() =>\n resolveInitialState(orderCode, null)\n );\n const [isPolling, setIsPolling] = useState(false);\n\n useEffect(() => {\n const stored = readOrderHandoff(orderCode);\n setHandoff(stored);\n setState(resolveInitialState(orderCode, stored));\n setHandoffLoaded(true);\n }, [orderCode]);\n\n // A bank transfer order needs the merchant's accounts and transfer\n // instruction, which travel on the public payment-methods endpoint.\n const bankTransfer = useBankTransferDetails(state === \"awaiting-transfer\");\n\n useEffect(() => {\n if (!orderCode) return; // no gateway return in play, nothing to poll\n // Until the handoff is read every order looks like \"confirming\"; an\n // offline one would start a poll with no callback coming.\n if (!handoffLoaded) return;\n if (!shouldPollForConfirmation(state)) return;\n\n let cancelled = false;\n setIsPolling(true);\n pollPaymentState({\n poll: () => getPaymentState(storeRef, orderCode),\n // Rejecting once unmounted ends the poll loop, not just its result.\n wait: async ms => {\n if (cancelled) throw CANCELLED;\n await wait(ms);\n if (cancelled) throw CANCELLED;\n },\n }).then(\n outcome => {\n if (cancelled) return;\n // \"pending\" (attempts exhausted, or every attempt errored) is\n // \"still-confirming\", never \"failed\": only the API says failed.\n setState(\n outcome.status === \"paid\"\n ? \"paid\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : \"still-confirming\"\n );\n setIsPolling(false);\n },\n () => {}\n );\n\n return () => {\n cancelled = true;\n };\n // state is read once to decide whether to start; re-running on every\n // transition would restart the poll it just resolved.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [orderCode, storeRef, handoffLoaded]);\n\n return {\n handoff,\n payment: { state, isPolling },\n bankTransfer: { accounts: bankTransfer.accounts, note: bankTransfer.note },\n };\n}\n\n/**\n * A guest's order, looked up by its code plus the email or phone it was\n * placed with (the view-order page).\n */\nexport function useOrderLookup({\n orderCode,\n email,\n phone,\n}: {\n orderCode: string | null;\n email?: string | null;\n phone?: string | null;\n}) {\n const storeRef = useStoreId();\n const [order, setOrder] = useState<OrderWithItems | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchOrder = useCallback(async () => {\n if (!orderCode || (!email && !phone)) {\n setError(\"Thiếu thông tin cần thiết để tra cứu đơn hàng\");\n setIsLoading(false);\n return;\n }\n try {\n setIsLoading(true);\n setError(null);\n const found = await sdk.orders.lookupGuest(storeRef, {\n order_code: orderCode,\n customer_email: email || undefined,\n customer_phone: phone || undefined,\n });\n if (!found) {\n setError(\"Không tìm thấy đơn hàng với thông tin đã cung cấp\");\n return;\n }\n setOrder(found);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"Error fetching order:\", err);\n setError(\"Có lỗi xảy ra khi tra cứu đơn hàng\");\n } finally {\n setIsLoading(false);\n }\n }, [storeRef, orderCode, email, phone]);\n\n useEffect(() => {\n fetchOrder();\n }, [fetchOrder]);\n\n return { order, isLoading, error, retry: fetchOrder };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,gBAAgB;AAEjD,SAAS,uBAAuB;AAChC,SAAS,wBAA2C;AACpD,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,WAAW;AACpB,SAAS,kBAAkB;AAC3B,SAAS,8BAA8B;AAIvC,MAAM,YAAY,IAAI,MAAM,yBAAyB;AAErD,MAAM,cAAc,CAAC,OACnB,IAAI,QAAc,aAAW,WAAW,SAAS,EAAE,CAAC;AAW/C,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA,OAAO;AACT,GAIG;AACD,QAAM,WAAW,WAAW;AAI5B,QAAM,CAAC,SAAS,UAAU,IAAI,SAA8B,IAAI;AAChE,QAAM,CAAC,eAAe,gBAAgB,IAAI,SAAS,KAAK;AACxD,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IAAmC,MAC3D,oBAAoB,WAAW,IAAI;AAAA,EACrC;AACA,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAEhD,YAAU,MAAM;AACd,UAAM,SAAS,iBAAiB,SAAS;AACzC,eAAW,MAAM;AACjB,aAAS,oBAAoB,WAAW,MAAM,CAAC;AAC/C,qBAAiB,IAAI;AAAA,EACv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S,IAAI;AACb,YAAM,QAAQ,MAAM,IAAI,OAAO,YAAY,UAAU;AAAA,QACnD,YAAY;AAAA,QACZ,gBAAgB,SAAS;AAAA,QACzB,gBAAgB,SAAS;AAAA,MAC3B,CAAC;AACD,UAAI,CAAC,OAAO;AACV,iBAAS,gGAAmD;AAC5D;AAAA,MACF;AACA,eAAS,KAAK;AAAA,IAChB,SAAS,KAAK;AAEZ,cAAQ,MAAM,yBAAyB,GAAG;AAC1C,eAAS,mEAAoC;AAAA,IAC/C,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,UAAU,WAAW,OAAO,KAAK,CAAC;AAEtC,YAAU,MAAM;AACd,eAAW;AAAA,EACb,GAAG,CAAC,UAAU,CAAC;AAEf,SAAO,EAAE,OAAO,WAAW,OAAO,OAAO,WAAW;AACtD;","names":[]}
@@ -3,6 +3,9 @@ import { useReducer, useEffect, useCallback, useRef, useMemo } from "react";
3
3
  import { SHIPPING_MESSAGES } from "./messages.js";
4
4
  import { useNotify } from "../notices.js";
5
5
  import { optionIdOf } from "./option-id.js";
6
+ import { isBrowserStorePreview } from "../api/store-preview-header.js";
7
+ import { STORE_PREVIEW_READ_ONLY_NOTICE } from "../stores/store-preview-guard.js";
8
+ import { isStoreComingSoonError } from "../stores/store-coming-soon.js";
6
9
  import {
7
10
  shippingCalculationReducer,
8
11
  initialShippingCalculationState
@@ -31,6 +34,11 @@ function useShippingCalculation({
31
34
  dispatch({ type: "RESET" });
32
35
  return;
33
36
  }
37
+ if (isBrowserStorePreview()) {
38
+ dispatch({ type: "RESET" });
39
+ notify(STORE_PREVIEW_READ_ONLY_NOTICE);
40
+ return;
41
+ }
34
42
  const next = stateRef.current.requestId + 1;
35
43
  dispatch({ type: "CALCULATION_STARTED" });
36
44
  try {
@@ -45,6 +53,11 @@ function useShippingCalculation({
45
53
  dispatch({ type: "CALCULATION_SUCCEEDED", options, requestId: next });
46
54
  } catch (error) {
47
55
  if (next !== stateRef.current.requestId) return;
56
+ if (isStoreComingSoonError(error)) {
57
+ dispatch({ type: "RESET" });
58
+ notify(STORE_PREVIEW_READ_ONLY_NOTICE);
59
+ return;
60
+ }
48
61
  console.error("Failed to calculate shipping fee:", error);
49
62
  dispatch({ type: "CALCULATION_FAILED", requestId: next });
50
63
  notify({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef, useMemo } from \"react\";\nimport type { ShippingOption } from \"@ecomweb/sdk\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport { optionIdOf } from \"./option-id\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n /**\n * Ask the API for carrier-quoted options too. Off by default so stores\n * that have not updated send exactly the body they always did.\n */\n includeCarrierOptions?: boolean;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n includeCarrierOptions = false,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n ...(includeCarrierOptions && { include_carrier_options: true }),\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [\n city,\n ward,\n itemsCount,\n storeRef,\n subtotal,\n totalWeight,\n includeCarrierOptions,\n notify,\n ]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n const handleShippingOptionSelect = useCallback((optionId: string) => {\n dispatch({ type: \"OPTION_SELECTED\", optionId });\n }, []);\n\n const replaceOptions = useCallback(\n (\n options: ShippingOption[],\n preferOptionId: string | null,\n requestId: number\n ) => {\n dispatch({ type: \"QUOTE_REPLACED\", options, requestId, preferOptionId });\n },\n []\n );\n\n const currentRequestId = useCallback(() => stateRef.current.requestId, []);\n\n const selectedOption = useMemo(\n () =>\n state.selectedOptionId === null\n ? null\n : (state.shippingOptions.find(\n o => optionIdOf(o) === state.selectedOptionId\n ) ?? null),\n [state.shippingOptions, state.selectedOptionId]\n );\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n selectedOptionId: state.selectedOptionId,\n selectedOption,\n handleShippingOptionSelect,\n replaceOptions,\n currentRequestId,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,YAAY,WAAW,aAAa,QAAQ,eAAe;AAEpE,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAgBA,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,wBAAwB;AAC1B,GAAgC;AAC9B,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IACxB;AAAA,IACA;AAAA,EACF;AACA,QAAM,SAAS,UAAU;AAIzB,QAAM,WAAW,OAAO,KAAK;AAC7B,WAAS,UAAU;AAanB,YAAU,MAAM;AACd,aAAS,EAAE,MAAM,QAAQ,CAAC;AAAA,EAC5B,GAAG,CAAC,MAAM,MAAM,UAAU,aAAa,qBAAqB,CAAC;AAE7D,QAAM,uBAAuB,YAAY,YAAY;AACnD,QAAI,CAAC,QAAQ,CAAC,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gBACA,cACG;AACH,eAAS,EAAE,MAAM,kBAAkB,SAAS,WAAW,eAAe,CAAC;AAAA,IACzE;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,mBAAmB,YAAY,MAAM,SAAS,QAAQ,WAAW,CAAC,CAAC;AAEzE,QAAM,iBAAiB;AAAA,IACrB,MACE,MAAM,qBAAqB,OACvB,OACC,MAAM,gBAAgB;AAAA,MACrB,OAAK,WAAW,CAAC,MAAM,MAAM;AAAA,IAC/B,KAAK;AAAA,IACX,CAAC,MAAM,iBAAiB,MAAM,gBAAgB;AAAA,EAChD;AAEA,SAAO;AAAA,IACL,aAAa,MAAM;AAAA,IACnB,uBAAuB,MAAM;AAAA,IAC7B,uBAAuB,MAAM;AAAA,IAC7B,iBAAiB,MAAM;AAAA,IACvB,sBAAsB,MAAM;AAAA,IAC5B,mBAAmB,MAAM;AAAA,IACzB,kBAAkB,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef, useMemo } from \"react\";\nimport type { ShippingOption } from \"@ecomweb/sdk\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport { optionIdOf } from \"./option-id\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { isStoreComingSoonError } from \"../stores/store-coming-soon\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n /**\n * Ask the API for carrier-quoted options too. Off by default so stores\n * that have not updated send exactly the body they always did.\n */\n includeCarrierOptions?: boolean;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n includeCarrierOptions = false,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // A store preview is read-only and the API refuses this POST with\n // STORE_COMING_SOON, which would show as a shipping error. Say it is a\n // preview instead, like the cart and checkout writes do.\n if (isBrowserStorePreview()) {\n dispatch({ type: \"RESET\" });\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n ...(includeCarrierOptions && { include_carrier_options: true }),\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n if (isStoreComingSoonError(error)) {\n dispatch({ type: \"RESET\" });\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [\n city,\n ward,\n itemsCount,\n storeRef,\n subtotal,\n totalWeight,\n includeCarrierOptions,\n notify,\n ]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n const handleShippingOptionSelect = useCallback((optionId: string) => {\n dispatch({ type: \"OPTION_SELECTED\", optionId });\n }, []);\n\n const replaceOptions = useCallback(\n (\n options: ShippingOption[],\n preferOptionId: string | null,\n requestId: number\n ) => {\n dispatch({ type: \"QUOTE_REPLACED\", options, requestId, preferOptionId });\n },\n []\n );\n\n const currentRequestId = useCallback(() => stateRef.current.requestId, []);\n\n const selectedOption = useMemo(\n () =>\n state.selectedOptionId === null\n ? null\n : (state.shippingOptions.find(\n o => optionIdOf(o) === state.selectedOptionId\n ) ?? null),\n [state.shippingOptions, state.selectedOptionId]\n );\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n selectedOptionId: state.selectedOptionId,\n selectedOption,\n handleShippingOptionSelect,\n replaceOptions,\n currentRequestId,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,YAAY,WAAW,aAAa,QAAQ,eAAe;AAEpE,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAC/C,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAgBA,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,wBAAwB;AAC1B,GAAgC;AAC9B,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IACxB;AAAA,IACA;AAAA,EACF;AACA,QAAM,SAAS,UAAU;AAIzB,QAAM,WAAW,OAAO,KAAK;AAC7B,WAAS,UAAU;AAanB,YAAU,MAAM;AACd,aAAS,EAAE,MAAM,QAAQ,CAAC;AAAA,EAC5B,GAAG,CAAC,MAAM,MAAM,UAAU,aAAa,qBAAqB,CAAC;AAE7D,QAAM,uBAAuB,YAAY,YAAY;AACnD,QAAI,CAAC,QAAQ,CAAC,QAAQ,eAAe,GAAG;AACtC,eAAS,EAAE,MAAM,QAAQ,CAAC;AAC1B;AAAA,IACF;AAKA,QAAI,sBAAsB,GAAG;AAC3B,eAAS,EAAE,MAAM,QAAQ,CAAC;AAC1B,aAAO,8BAA8B;AACrC;AAAA,IACF;AAKA,UAAM,OAAO,SAAS,QAAQ,YAAY;AAC1C,aAAS,EAAE,MAAM,sBAAsB,CAAC;AAExC,QAAI;AACF,YAAM,UA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AAA,IACzE;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,mBAAmB,YAAY,MAAM,SAAS,QAAQ,WAAW,CAAC,CAAC;AAEzE,QAAM,iBAAiB;AAAA,IACrB,MACE,MAAM,qBAAqB,OACvB,OACC,MAAM,gBAAgB;AAAA,MACrB,OAAK,WAAW,CAAC,MAAM,MAAM;AAAA,IAC/B,KAAK;AAAA,IACX,CAAC,MAAM,iBAAiB,MAAM,gBAAgB;AAAA,EAChD;AAEA,SAAO;AAAA,IACL,aAAa,MAAM;AAAA,IACnB,uBAAuB,MAAM;AAAA,IAC7B,uBAAuB,MAAM;AAAA,IAC7B,iBAAiB,MAAM;AAAA,IACvB,sBAAsB,MAAM;AAAA,IAC5B,mBAAmB,MAAM;AAAA,IACzB,kBAAkB,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
@@ -35,13 +35,31 @@ function applyStorePreview(req, cookiePath, storeRoot) {
35
35
  });
36
36
  return res;
37
37
  }
38
+ function previewTokenUnexpired(token, now = Date.now()) {
39
+ try {
40
+ const payload = token.split(".")[0] ?? "";
41
+ const json = JSON.parse(
42
+ atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
43
+ );
44
+ return typeof json.exp !== "number" || json.exp >= now;
45
+ } catch {
46
+ return true;
47
+ }
48
+ }
49
+ function firstLivePreviewToken(...candidates) {
50
+ const present = candidates.filter((c) => !!c);
51
+ return present.find((t) => previewTokenUnexpired(t)) ?? present[0] ?? null;
52
+ }
38
53
  function storePreviewTokenFrom(jar, request) {
39
54
  const stamped = request.headers.get(STORE_PREVIEW_TOKEN_HEADER);
40
- if (stamped) return stamped;
41
55
  const hostMapped = isHostMappedRequest(request);
42
56
  const storeCookie = hostMapped ? storePreviewCookieName("/") : STORE_PREVIEW_COOKIE;
43
57
  const themeCookie = hostMapped ? themePreviewCookieName("/") : THEME_PREVIEW_COOKIE;
44
- return jar.get(storeCookie)?.value || jar.get(themeCookie)?.value || null;
58
+ return firstLivePreviewToken(
59
+ stamped,
60
+ jar.get(storeCookie)?.value,
61
+ jar.get(themeCookie)?.value
62
+ );
45
63
  }
46
64
  const SKIP_STORE_PREVIEW = Object.freeze({
47
65
  skipStorePreview: true
@@ -57,6 +75,8 @@ export {
57
75
  STORE_PREVIEW_PATH,
58
76
  STORE_PREVIEW_TOKEN_HEADER,
59
77
  applyStorePreview,
78
+ firstLivePreviewToken,
79
+ previewTokenUnexpired,
60
80
  skipsStorePreview,
61
81
  storePreviewCookieName,
62
82
  storePreviewTokenFrom
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/store-preview-cookie.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport {\n hostOnlyCookieName,\n isHostMappedRequest,\n secureCookies,\n} from \"../auth/cookies\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n THEME_PREVIEW_COOKIE,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\n\n// No `next/headers` here: the browser bundle reaches this module (through\n// the API client), so readers take the jar and the request as arguments.\n\n/** Holds a coming soon store's preview token (the dashboard's preview link). */\nexport const STORE_PREVIEW_COOKIE = \"ecw_store_preview\";\n/** The preview link's route under the store's root. */\nexport const STORE_PREVIEW_PATH = \"/preview\";\n/** The preview link's query param carrying the token. */\nexport const STORE_PREVIEW_PARAM = \"token\";\n/** The API's request header (`X-Store-Preview`) that opens a coming soon store. */\nexport const STORE_PREVIEW_HEADER = \"x-store-preview\";\n/**\n * Internal request header carrying a theme preview host's (`p-<slug>`) store\n * preview token from the host lookup to the render, in place of the cookie.\n * Only the middleware sets it, and it deletes any value the client sent on\n * every request it lets through, as it does for `THEME_PREVIEW_HOST_HEADER`,\n * so a reader can trust it on any path the matcher covers. Root `/api/*` is\n * outside the matcher; the backend proxy ignores it there.\n */\nexport const STORE_PREVIEW_TOKEN_HEADER = \"x-ecomweb-store-preview-token\";\n\nconst MAX_TOKEN_LENGTH = 2048;\nconst MAX_AGE_SECONDS = 24 * 60 * 60;\n\n/** The store preview cookie's name at `cookiePath` (see hostOnlyCookieName). */\nexport function storePreviewCookieName(cookiePath: string): string {\n return hostOnlyCookieName(STORE_PREVIEW_COOKIE, cookiePath);\n}\n\n/**\n * The dashboard's preview link (`<store root>/preview?token=<t>`) becomes an\n * httpOnly cookie scoped to the store, then a 307 to the store's home, so the\n * token never stays in the address bar or in shared links. A missing, empty\n * or oversized token clears the cookie instead. The API validates the token\n * on every request. SameSite=Lax: the link is a top-level navigation and the\n * store is never framed during a store preview.\n */\nexport function applyStorePreview(\n req: NextRequest,\n cookiePath: string,\n storeRoot: string\n): NextResponse {\n const token = req.nextUrl.searchParams.get(STORE_PREVIEW_PARAM) ?? \"\";\n const url = publicNextUrl(req);\n url.pathname = storeRoot;\n url.search = \"\";\n const res = NextResponse.redirect(url, 307);\n const valid = token.length > 0 && token.length <= MAX_TOKEN_LENGTH;\n res.cookies.set(storePreviewCookieName(cookiePath), valid ? token : \"\", {\n httpOnly: true,\n secure: secureCookies(),\n sameSite: \"lax\",\n path: cookiePath,\n maxAge: valid ? MAX_AGE_SECONDS : 0,\n });\n return res;\n}\n\n/** Minimal shape shared by `cookies()` and `request.cookies`. */\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** Minimal shape shared by `headers()`-backed requests and `NextRequest`. */\ninterface HeaderReader {\n headers: { get(name: string): string | null };\n}\n\n/**\n * The token to send as `X-Store-Preview` for this request, or null. In order:\n * the preview host's token the middleware stamped (`STORE_PREVIEW_TOKEN_HEADER`),\n * the store preview cookie, then the theme preview cookie (`?preview_theme=`\n * on the store's own host), which the API accepts too. Cookies are read under\n * the name their writer used: `/` on a host-mapped request (the `__Host-` name\n * in production, never the bare one a sibling store could plant), else the\n * bare path-scoped name. An empty value counts as none at every step.\n *\n * Trusts `STORE_PREVIEW_TOKEN_HEADER`, so call it only on a request that went\n * through the middleware (server components, route handlers), never on the\n * middleware's own incoming request.\n */\nexport function storePreviewTokenFrom(\n jar: CookieReader,\n request: HeaderReader\n): string | null {\n const stamped = request.headers.get(STORE_PREVIEW_TOKEN_HEADER);\n if (stamped) return stamped;\n const hostMapped = isHostMappedRequest(request);\n const storeCookie = hostMapped\n ? storePreviewCookieName(\"/\")\n : STORE_PREVIEW_COOKIE;\n const themeCookie = hostMapped\n ? themePreviewCookieName(\"/\")\n : THEME_PREVIEW_COOKIE;\n return jar.get(storeCookie)?.value || jar.get(themeCookie)?.value || null;\n}\n\n/**\n * Request option that forbids the kit's API client from attaching the\n * request's ambient preview token (`storePreviewTokenFrom`) as\n * `X-Store-Preview`. Spread it into the SDK call's options (the SDK's\n * `RequestOptions` takes extra keys and the kit's ApiClient hands them to\n * axios unchanged). A plain `getStoreByHost(host)` sets it, because its\n * result is cached per host for every visitor and must be the public answer.\n * An explicit `X-Store-Preview` header in the same options still goes out.\n */\nexport const SKIP_STORE_PREVIEW = Object.freeze({\n skipStorePreview: true,\n} as const);\n\n/** True when request options (or an axios config) carry SKIP_STORE_PREVIEW. */\nexport function skipsStorePreview(options: object | undefined): boolean {\n return (\n (options as { skipStorePreview?: unknown } | undefined)\n ?.skipStorePreview === true\n );\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMA,MAAM,uBAAuB;AAE7B,MAAM,qBAAqB;AAE3B,MAAM,sBAAsB;AAE5B,MAAM,uBAAuB;AAS7B,MAAM,6BAA6B;AAE1C,MAAM,mBAAmB;AACzB,MAAM,kBAAkB,KAAK,KAAK;AAG3B,SAAS,uBAAuB,YAA4B;AACjE,SAAO,mBAAmB,sBAAsB,UAAU;AAC5D;AAUO,SAAS,kBACd,KACA,YACA,WACc;AACd,QAAM,QAAQ,IAAI,QAAQ,aAAa,IAAI,mBAAmB,KAAK;AACnE,QAAM,MAAM,cAAc,GAAG;AAC7B,MAAI,WAAW;AACf,MAAI,SAAS;AACb,QAAM,MAAM,aAAa,SAAS,KAAK,GAAG;AAC1C,QAAM,QAAQ,MAAM,SAAS,KAAK,MAAM,UAAU;AAClD,MAAI,QAAQ,IAAI,uBAAuB,UAAU,GAAG,QAAQ,QAAQ,IAAI;AAAA,IACtE,UAAU;AAAA,IACV,QAAQ,cAAc;AAAA,IACtB,UAAU;AAAA,IACV,MAAM;AAAA,IACN,QAAQ,QAAQ,kBAAkB;AAAA,EACpC,CAAC;AACD,SAAO;AACT;AAyBO,SAAS,sBACd,KACA,SACe;AACf,QAAM,UAAU,QAAQ,QAAQ,IAAI,0BAA0B;AAC9D,MAAI,QAAS,QAAO;AACpB,QAAM,aAAa,oBAAoB,OAAO;AAC9C,QAAM,cAAc,aAChB,uBAAuB,GAAG,IAC1B;AACJ,QAAM,cAAc,aAChB,uBAAuB,GAAG,IAC1B;AACJ,SAAO,IAAI,IAAI,WAAW,GAAG,SAAS,IAAI,IAAI,WAAW,GAAG,SAAS;AACvE;AAWO,MAAM,qBAAqB,OAAO,OAAO;AAAA,EAC9C,kBAAkB;AACpB,CAAU;AAGH,SAAS,kBAAkB,SAAsC;AACtE,SACG,SACG,qBAAqB;AAE7B;","names":[]}
1
+ {"version":3,"sources":["../../src/stores/store-preview-cookie.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport {\n hostOnlyCookieName,\n isHostMappedRequest,\n secureCookies,\n} from \"../auth/cookies\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n THEME_PREVIEW_COOKIE,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\n\n// No `next/headers` here: the browser bundle reaches this module (through\n// the API client), so readers take the jar and the request as arguments.\n\n/** Holds a coming soon store's preview token (the dashboard's preview link). */\nexport const STORE_PREVIEW_COOKIE = \"ecw_store_preview\";\n/** The preview link's route under the store's root. */\nexport const STORE_PREVIEW_PATH = \"/preview\";\n/** The preview link's query param carrying the token. */\nexport const STORE_PREVIEW_PARAM = \"token\";\n/** The API's request header (`X-Store-Preview`) that opens a coming soon store. */\nexport const STORE_PREVIEW_HEADER = \"x-store-preview\";\n/**\n * Internal request header carrying a theme preview host's (`p-<slug>`) store\n * preview token from the host lookup to the render, in place of the cookie.\n * Only the middleware sets it, and it deletes any value the client sent on\n * every request it lets through, as it does for `THEME_PREVIEW_HOST_HEADER`,\n * so a reader can trust it on any path the matcher covers. Root `/api/*` is\n * outside the matcher; the backend proxy ignores it there.\n */\nexport const STORE_PREVIEW_TOKEN_HEADER = \"x-ecomweb-store-preview-token\";\n\nconst MAX_TOKEN_LENGTH = 2048;\nconst MAX_AGE_SECONDS = 24 * 60 * 60;\n\n/** The store preview cookie's name at `cookiePath` (see hostOnlyCookieName). */\nexport function storePreviewCookieName(cookiePath: string): string {\n return hostOnlyCookieName(STORE_PREVIEW_COOKIE, cookiePath);\n}\n\n/**\n * The dashboard's preview link (`<store root>/preview?token=<t>`) becomes an\n * httpOnly cookie scoped to the store, then a 307 to the store's home, so the\n * token never stays in the address bar or in shared links. A missing, empty\n * or oversized token clears the cookie instead. The API validates the token\n * on every request. SameSite=Lax: the link is a top-level navigation and the\n * store is never framed during a store preview.\n */\nexport function applyStorePreview(\n req: NextRequest,\n cookiePath: string,\n storeRoot: string\n): NextResponse {\n const token = req.nextUrl.searchParams.get(STORE_PREVIEW_PARAM) ?? \"\";\n const url = publicNextUrl(req);\n url.pathname = storeRoot;\n url.search = \"\";\n const res = NextResponse.redirect(url, 307);\n const valid = token.length > 0 && token.length <= MAX_TOKEN_LENGTH;\n res.cookies.set(storePreviewCookieName(cookiePath), valid ? token : \"\", {\n httpOnly: true,\n secure: secureCookies(),\n sameSite: \"lax\",\n path: cookiePath,\n maxAge: valid ? MAX_AGE_SECONDS : 0,\n });\n return res;\n}\n\n/** Minimal shape shared by `cookies()` and `request.cookies`. */\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** Minimal shape shared by `headers()`-backed requests and `NextRequest`. */\ninterface HeaderReader {\n headers: { get(name: string): string | null };\n}\n\n/**\n * True unless the token's own payload says it has expired. Preview tokens are\n * `<base64url(json)>.<signature>` with `exp` (ms) in the payload; the\n * signature can only be checked by the API, so this only drops tokens that\n * are certainly dead. A token it cannot read counts as live: the API decides.\n */\nexport function previewTokenUnexpired(\n token: string,\n now: number = Date.now()\n): boolean {\n try {\n const payload = token.split(\".\")[0] ?? \"\";\n const json = JSON.parse(\n atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"))\n ) as { exp?: unknown };\n return typeof json.exp !== \"number\" || json.exp >= now;\n } catch {\n return true;\n }\n}\n\n/**\n * The first candidate that is present and not expired. When every candidate\n * is expired, the first present one: sending a dead token and getting the\n * API's refusal beats sending none.\n */\nexport function firstLivePreviewToken(\n ...candidates: Array<string | null | undefined>\n): string | null {\n const present = candidates.filter((c): c is string => !!c);\n return present.find(t => previewTokenUnexpired(t)) ?? present[0] ?? null;\n}\n\n/**\n * The token to send as `X-Store-Preview` for this request, or null. In order:\n * the preview host's token the middleware stamped (`STORE_PREVIEW_TOKEN_HEADER`),\n * the store preview cookie, then the theme preview cookie (`?preview_theme=`\n * on the store's own host), which the API accepts too. Cookies are read under\n * the name their writer used: `/` on a host-mapped request (the `__Host-` name\n * in production, never the bare one a sibling store could plant), else the\n * bare path-scoped name. An empty value counts as none at every step, and so\n * does an expired one: a stale store cookie no longer hides a valid theme\n * cookie behind it.\n *\n * Trusts `STORE_PREVIEW_TOKEN_HEADER`, so call it only on a request that went\n * through the middleware (server components, route handlers), never on the\n * middleware's own incoming request.\n */\nexport function storePreviewTokenFrom(\n jar: CookieReader,\n request: HeaderReader\n): string | null {\n const stamped = request.headers.get(STORE_PREVIEW_TOKEN_HEADER);\n const hostMapped = isHostMappedRequest(request);\n const storeCookie = hostMapped\n ? storePreviewCookieName(\"/\")\n : STORE_PREVIEW_COOKIE;\n const themeCookie = hostMapped\n ? themePreviewCookieName(\"/\")\n : THEME_PREVIEW_COOKIE;\n return firstLivePreviewToken(\n stamped,\n jar.get(storeCookie)?.value,\n jar.get(themeCookie)?.value\n );\n}\n\n/**\n * Request option that forbids the kit's API client from attaching the\n * request's ambient preview token (`storePreviewTokenFrom`) as\n * `X-Store-Preview`. Spread it into the SDK call's options (the SDK's\n * `RequestOptions` takes extra keys and the kit's ApiClient hands them to\n * axios unchanged). A plain `getStoreByHost(host)` sets it, because its\n * result is cached per host for every visitor and must be the public answer.\n * An explicit `X-Store-Preview` header in the same options still goes out.\n */\nexport const SKIP_STORE_PREVIEW = Object.freeze({\n skipStorePreview: true,\n} as const);\n\n/** True when request options (or an axios config) carry SKIP_STORE_PREVIEW. */\nexport function skipsStorePreview(options: object | undefined): boolean {\n return (\n (options as { skipStorePreview?: unknown } | undefined)\n ?.skipStorePreview === true\n );\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMA,MAAM,uBAAuB;AAE7B,MAAM,qBAAqB;AAE3B,MAAM,sBAAsB;AAE5B,MAAM,uBAAuB;AAS7B,MAAM,6BAA6B;AAE1C,MAAM,mBAAmB;AACzB,MAAM,kBAAkB,KAAK,KAAK;AAG3B,SAAS,uBAAuB,YAA4B;AACjE,SAAO,mBAAmB,sBAAsB,UAAU;AAC5D;AAUO,SAAS,kBACd,KACA,YACA,WACc;AACd,QAAM,QAAQ,IAAI,QAAQ,aAAa,IAAI,mBAAmB,KAAK;AACnE,QAAM,MAAM,cAAc,GAAG;AAC7B,MAAI,WAAW;AACf,MAAI,SAAS;AACb,QAAM,MAAM,aAAa,SAAS,KAAK,GAAG;AAC1C,QAAM,QAAQ,MAAM,SAAS,KAAK,MAAM,UAAU;AAClD,MAAI,QAAQ,IAAI,uBAAuB,UAAU,GAAG,QAAQ,QAAQ,IAAI;AAAA,IACtE,UAAU;AAAA,IACV,QAAQ,cAAc;AAAA,IACtB,UAAU;AAAA,IACV,MAAM;AAAA,IACN,QAAQ,QAAQ,kBAAkB;AAAA,EACpC,CAAC;AACD,SAAO;AACT;AAkBO,SAAS,sBACd,OACA,MAAc,KAAK,IAAI,GACd;AACT,MAAI;AACF,UAAM,UAAU,MAAM,MAAM,GAAG,EAAE,CAAC,KAAK;AACvC,UAAM,OAAO,KAAK;AAAA,MAChB,KAAK,QAAQ,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG,CAAC;AAAA,IACpD;AACA,WAAO,OAAO,KAAK,QAAQ,YAAY,KAAK,OAAO;AAAA,EACrD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOO,SAAS,yBACX,YACY;AACf,QAAM,UAAU,WAAW,OAAO,CAAC,MAAmB,CAAC,CAAC,CAAC;AACzD,SAAO,QAAQ,KAAK,OAAK,sBAAsB,CAAC,CAAC,KAAK,QAAQ,CAAC,KAAK;AACtE;AAiBO,SAAS,sBACd,KACA,SACe;AACf,QAAM,UAAU,QAAQ,QAAQ,IAAI,0BAA0B;AAC9D,QAAM,aAAa,oBAAoB,OAAO;AAC9C,QAAM,cAAc,aAChB,uBAAuB,GAAG,IAC1B;AACJ,QAAM,cAAc,aAChB,uBAAuB,GAAG,IAC1B;AACJ,SAAO;AAAA,IACL;AAAA,IACA,IAAI,IAAI,WAAW,GAAG;AAAA,IACtB,IAAI,IAAI,WAAW,GAAG;AAAA,EACxB;AACF;AAWO,MAAM,qBAAqB,OAAO,OAAO;AAAA,EAC9C,kBAAkB;AACpB,CAAU;AAGH,SAAS,kBAAkB,SAAsC;AACtE,SACG,SACG,qBAAqB;AAE7B;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecomweb/storefront-kit",
3
- "version": "0.12.1",
3
+ "version": "0.13.1",
4
4
  "description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -47,7 +47,7 @@
47
47
  "currency.js": "^2.0.4",
48
48
  "server-only": "^0.0.1",
49
49
  "zod": "^4.1.12",
50
- "@ecomweb/sdk": "^0.12.1"
50
+ "@ecomweb/sdk": "^0.13.1"
51
51
  },
52
52
  "peerDependencies": {
53
53
  "next": ">=16",