@ecomweb/storefront-kit 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -0
  3. package/dist/api/client.js +162 -0
  4. package/dist/api/client.js.map +1 -0
  5. package/dist/api/index.js +7 -0
  6. package/dist/api/index.js.map +1 -0
  7. package/dist/api/proxy.js +145 -0
  8. package/dist/api/proxy.js.map +1 -0
  9. package/dist/api/response.js +55 -0
  10. package/dist/api/response.js.map +1 -0
  11. package/dist/api/server-client.js +159 -0
  12. package/dist/api/server-client.js.map +1 -0
  13. package/dist/auth/client-ip.js +44 -0
  14. package/dist/auth/client-ip.js.map +1 -0
  15. package/dist/auth/context.js +125 -0
  16. package/dist/auth/context.js.map +1 -0
  17. package/dist/auth/cookies.js +97 -0
  18. package/dist/auth/cookies.js.map +1 -0
  19. package/dist/auth/error-copy.js +49 -0
  20. package/dist/auth/error-copy.js.map +1 -0
  21. package/dist/auth/password-policy.js +29 -0
  22. package/dist/auth/password-policy.js.map +1 -0
  23. package/dist/auth/route-handlers.js +337 -0
  24. package/dist/auth/route-handlers.js.map +1 -0
  25. package/dist/auth/safe-redirect.js +20 -0
  26. package/dist/auth/safe-redirect.js.map +1 -0
  27. package/dist/auth/sdk.js +76 -0
  28. package/dist/auth/sdk.js.map +1 -0
  29. package/dist/auth/session-refresh.js +81 -0
  30. package/dist/auth/session-refresh.js.map +1 -0
  31. package/dist/auth/session.js +26 -0
  32. package/dist/auth/session.js.map +1 -0
  33. package/dist/auth/use-public-auth-config.js +29 -0
  34. package/dist/auth/use-public-auth-config.js.map +1 -0
  35. package/dist/cart/api.js +60 -0
  36. package/dist/cart/api.js.map +1 -0
  37. package/dist/cart/server-context.js +279 -0
  38. package/dist/cart/server-context.js.map +1 -0
  39. package/dist/cart/types.js +1 -0
  40. package/dist/cart/types.js.map +1 -0
  41. package/dist/cart/utils.js +49 -0
  42. package/dist/cart/utils.js.map +1 -0
  43. package/dist/checkout/get-payment-state.js +15 -0
  44. package/dist/checkout/get-payment-state.js.map +1 -0
  45. package/dist/checkout/initiate-gateway-payment.js +13 -0
  46. package/dist/checkout/initiate-gateway-payment.js.map +1 -0
  47. package/dist/checkout/order-handoff.js +61 -0
  48. package/dist/checkout/order-handoff.js.map +1 -0
  49. package/dist/checkout/payment-redirect.js +11 -0
  50. package/dist/checkout/payment-redirect.js.map +1 -0
  51. package/dist/checkout/payment-state-poll.js +45 -0
  52. package/dist/checkout/payment-state-poll.js.map +1 -0
  53. package/dist/checkout/start-gateway-redirect.js +16 -0
  54. package/dist/checkout/start-gateway-redirect.js.map +1 -0
  55. package/dist/checkout/stock-issues.js +35 -0
  56. package/dist/checkout/stock-issues.js.map +1 -0
  57. package/dist/checkout/success-state.js +15 -0
  58. package/dist/checkout/success-state.js.map +1 -0
  59. package/dist/checkout/types.js +1 -0
  60. package/dist/checkout/types.js.map +1 -0
  61. package/dist/checkout/use-checkout.js +256 -0
  62. package/dist/checkout/use-checkout.js.map +1 -0
  63. package/dist/checkout/utils.js +7 -0
  64. package/dist/checkout/utils.js.map +1 -0
  65. package/dist/config/index.js +7 -0
  66. package/dist/config/index.js.map +1 -0
  67. package/dist/config/log-level.js +8 -0
  68. package/dist/config/log-level.js.map +1 -0
  69. package/dist/config/mode.js +18 -0
  70. package/dist/config/mode.js.map +1 -0
  71. package/dist/config/public.js +115 -0
  72. package/dist/config/public.js.map +1 -0
  73. package/dist/config/schema.js +70 -0
  74. package/dist/config/schema.js.map +1 -0
  75. package/dist/config/server.js +68 -0
  76. package/dist/config/server.js.map +1 -0
  77. package/dist/config.d.ts +16 -0
  78. package/dist/config.js +15 -0
  79. package/dist/config.js.map +1 -0
  80. package/dist/currency.js +68 -0
  81. package/dist/currency.js.map +1 -0
  82. package/dist/index.d.ts +968 -0
  83. package/dist/index.js +146 -0
  84. package/dist/index.js.map +1 -0
  85. package/dist/interfaces/api.types.js +1 -0
  86. package/dist/interfaces/api.types.js.map +1 -0
  87. package/dist/interfaces/index.js +2 -0
  88. package/dist/interfaces/index.js.map +1 -0
  89. package/dist/logging.js +42 -0
  90. package/dist/logging.js.map +1 -0
  91. package/dist/middleware/create-storefront-middleware.js +175 -0
  92. package/dist/middleware/create-storefront-middleware.js.map +1 -0
  93. package/dist/middleware.d.ts +24 -0
  94. package/dist/middleware.js +9 -0
  95. package/dist/middleware.js.map +1 -0
  96. package/dist/mode-1ZKDELPZ.d.ts +16 -0
  97. package/dist/notices.js +31 -0
  98. package/dist/notices.js.map +1 -0
  99. package/dist/orders/api-client.js +32 -0
  100. package/dist/orders/api-client.js.map +1 -0
  101. package/dist/orders/derive-progress.js +36 -0
  102. package/dist/orders/derive-progress.js.map +1 -0
  103. package/dist/orders/index.js +6 -0
  104. package/dist/orders/index.js.map +1 -0
  105. package/dist/orders/types.js +13 -0
  106. package/dist/orders/types.js.map +1 -0
  107. package/dist/orders/use-order-status.js +137 -0
  108. package/dist/orders/use-order-status.js.map +1 -0
  109. package/dist/promotions/use-promotion-validation.js +106 -0
  110. package/dist/promotions/use-promotion-validation.js.map +1 -0
  111. package/dist/promotions/utils.js +40 -0
  112. package/dist/promotions/utils.js.map +1 -0
  113. package/dist/provider.js +25 -0
  114. package/dist/provider.js.map +1 -0
  115. package/dist/redirects/index.js +2 -0
  116. package/dist/redirects/index.js.map +1 -0
  117. package/dist/redirects/lookup-redirect.js +13 -0
  118. package/dist/redirects/lookup-redirect.js.map +1 -0
  119. package/dist/request/public-url.js +20 -0
  120. package/dist/request/public-url.js.map +1 -0
  121. package/dist/schema-CEMKsCwh.d.ts +52 -0
  122. package/dist/sdk.js +33 -0
  123. package/dist/sdk.js.map +1 -0
  124. package/dist/server/routes.js +56 -0
  125. package/dist/server/routes.js.map +1 -0
  126. package/dist/server.d.ts +58 -0
  127. package/dist/server.js +19 -0
  128. package/dist/server.js.map +1 -0
  129. package/dist/shipping/format-shipping-option.js +12 -0
  130. package/dist/shipping/format-shipping-option.js.map +1 -0
  131. package/dist/shipping/location-areas.js +104 -0
  132. package/dist/shipping/location-areas.js.map +1 -0
  133. package/dist/shipping/messages.js +19 -0
  134. package/dist/shipping/messages.js.map +1 -0
  135. package/dist/shipping/shipping-calculation-reducer.js +75 -0
  136. package/dist/shipping/shipping-calculation-reducer.js.map +1 -0
  137. package/dist/shipping/use-shipping-calculation.js +84 -0
  138. package/dist/shipping/use-shipping-calculation.js.map +1 -0
  139. package/dist/shipping/utils.js +18 -0
  140. package/dist/shipping/utils.js.map +1 -0
  141. package/dist/storage.js +116 -0
  142. package/dist/storage.js.map +1 -0
  143. package/dist/store/store-context.js +72 -0
  144. package/dist/store/store-context.js.map +1 -0
  145. package/dist/store-scope/index.js +33 -0
  146. package/dist/store-scope/index.js.map +1 -0
  147. package/dist/store-scope/root.js +15 -0
  148. package/dist/store-scope/root.js.map +1 -0
  149. package/dist/store-scope/store-url.js +45 -0
  150. package/dist/store-scope/store-url.js.map +1 -0
  151. package/dist/stores/basic-settings.js +67 -0
  152. package/dist/stores/basic-settings.js.map +1 -0
  153. package/dist/stores/cached.js +20 -0
  154. package/dist/stores/cached.js.map +1 -0
  155. package/dist/stores/get-store-by-host.js +38 -0
  156. package/dist/stores/get-store-by-host.js.map +1 -0
  157. package/dist/stores/index.js +7 -0
  158. package/dist/stores/index.js.map +1 -0
  159. package/dist/stores/metadata.js +19 -0
  160. package/dist/stores/metadata.js.map +1 -0
  161. package/dist/stores/store-path.js +9 -0
  162. package/dist/stores/store-path.js.map +1 -0
  163. package/dist/stores/store-suspension.js +14 -0
  164. package/dist/stores/store-suspension.js.map +1 -0
  165. package/package.json +64 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/api/server-client.ts"],"sourcesContent":["import { ApiResponse, AuthenticatedApiClient } from \"../interfaces\";\nimport { readAuthCookies } from \"../auth/cookies\";\nimport { publicConfig } from \"../config\";\n\nconst DEFAULT_TIMEOUT = 10000; // 10 seconds\n\ninterface FetchConfig {\n headers?: Record<string, string>;\n signal?: AbortSignal;\n /**\n * Auth cookies are store-scoped (see lib/auth/cookies.ts), so a\n * `requireAuth` request needs to know which store's cookie to read. There\n * is no store context at the module level (serverApiClient is a shared\n * singleton), so callers thread it through here instead.\n */\n storeRef?: string;\n [key: string]: any;\n}\n\nclass ServerApiClient implements AuthenticatedApiClient {\n private baseUrl: string;\n private timeout: number;\n private requireAuth: boolean;\n\n constructor(\n baseUrl: string = publicConfig().apiUrl,\n options?: { requireAuth?: boolean }\n ) {\n this.requireAuth =\n options?.requireAuth !== undefined ? options.requireAuth : true;\n this.baseUrl = baseUrl.replace(/\\/$/, \"\"); // Remove trailing slash\n this.timeout = DEFAULT_TIMEOUT;\n }\n\n private async getAuthToken(storeRef?: string): Promise<string | null> {\n if (!this.requireAuth) {\n return null;\n }\n\n if (!storeRef) {\n // Auth cookies are store-scoped; without a storeRef there is no\n // cookie to read. Fail loudly rather than silently going anonymous.\n throw new Error(\n \"ServerApiClient: storeRef is required for authenticated requests\"\n );\n }\n\n // Dynamically import next/headers only when auth is needed — this\n // prevents Edge Runtime errors for non-auth requests.\n const { cookies } = await import(\"next/headers\");\n const jar = await cookies();\n const tokens = readAuthCookies(jar, storeRef);\n\n if (!tokens) {\n throw new Error(\"User not authenticated\");\n }\n\n return tokens.access_token;\n }\n\n private async makeRequest<T>(\n url: string,\n options: RequestInit = {},\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n try {\n // Set up timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Prepare headers\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...config?.headers,\n };\n\n // Add platform API key for authentication\n const platformApiKey = publicConfig().storefrontApiKey;\n if (platformApiKey) {\n headers[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n // Add auth token if required\n if (this.requireAuth) {\n const token = await this.getAuthToken(config?.storeRef);\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n }\n }\n\n // Make the fetch request\n const response = await fetch(`${this.baseUrl}${url}`, {\n ...options,\n headers,\n signal: config?.signal || controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n let data: T;\n const contentType = response.headers.get(\"content-type\");\n if (contentType && contentType.includes(\"application/json\")) {\n data = await response.json();\n } else {\n data = (await response.text()) as any;\n }\n\n // Handle non-OK responses\n if (!response.ok) {\n return {\n success: false,\n error: {\n message:\n (data as any)?.message ||\n `Request failed with status ${response.status}`,\n statusCode: response.status,\n error: (data as any)?.error || response.statusText,\n details: (data as any)?.details,\n },\n };\n }\n\n return {\n success: true,\n data,\n };\n } catch (error: any) {\n // Handle timeout\n if (error.name === \"AbortError\") {\n return {\n success: false,\n error: {\n message: \"Request timeout - please try again\",\n statusCode: 0,\n error: \"TIMEOUT\",\n },\n };\n }\n\n // Handle network errors\n if (error instanceof TypeError) {\n return {\n success: false,\n error: {\n message: \"Network error - check your connection\",\n statusCode: 0,\n error: \"NETWORK_ERROR\",\n },\n };\n }\n\n // Handle other errors\n return {\n success: false,\n error: {\n message:\n error instanceof Error ? error.message : \"Unknown error occurred\",\n statusCode: 0,\n },\n };\n }\n }\n\n async get<T>(url: string, config?: FetchConfig): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(url, { method: \"GET\" }, config);\n }\n\n async post<T>(\n url: string,\n data?: any,\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(\n url,\n {\n method: \"POST\",\n body: data ? JSON.stringify(data) : undefined,\n },\n config\n );\n }\n\n async put<T>(\n url: string,\n data?: any,\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(\n url,\n {\n method: \"PUT\",\n body: data ? JSON.stringify(data) : undefined,\n },\n config\n );\n }\n\n async patch<T>(\n url: string,\n data?: any,\n config?: FetchConfig\n ): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(\n url,\n {\n method: \"PATCH\",\n body: data ? JSON.stringify(data) : undefined,\n },\n config\n );\n }\n\n async delete<T>(url: string, config?: FetchConfig): Promise<ApiResponse<T>> {\n return this.makeRequest<T>(url, { method: \"DELETE\" }, config);\n }\n\n // Additional utility methods for server-side use\n setBaseURL(baseUrl: string): void {\n this.baseUrl = baseUrl.replace(/\\/$/, \"\");\n }\n\n setTimeout(timeout: number): void {\n this.timeout = timeout;\n }\n}\n\n// Create a default instance for server-side use\nexport const serverApiClient = new ServerApiClient();\n\n// Create a server-side public (no-auth) instance\nexport const serverPublicApiClient = new ServerApiClient(publicConfig().apiUrl, {\n requireAuth: false,\n});\n\n// Export the class for custom instances\nexport { ServerApiClient };\n"],"mappings":"AACA,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAE7B,MAAM,kBAAkB;AAexB,MAAM,gBAAkD;AAAA,EAC9C;AAAA,EACA;AAAA,EACA;AAAA,EAER,YACE,UAAkB,aAAa,EAAE,QACjC,SACA;AACA,SAAK,cACH,SAAS,gBAAgB,SAAY,QAAQ,cAAc;AAC7D,SAAK,UAAU,QAAQ,QAAQ,OAAO,EAAE;AACxC,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAc,aAAa,UAA2C;AACpE,QAAI,CAAC,KAAK,aAAa;AACrB,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,UAAU;AAGb,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAIA,UAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,cAAc;AAC/C,UAAM,MAAM,MAAM,QAAQ;AAC1B,UAAM,SAAS,gBAAgB,KAAK,QAAQ;AAE5C,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC1C;AAEA,WAAO,OAAO;AAAA,EAChB;AAAA,EAEA,MAAc,YACZ,KACA,UAAuB,CAAC,GACxB,QACyB;AACzB,QAAI;AAEF,YAAM,aAAa,IAAI,gBAAgB;AACvC,YAAM,YAAY,WAAW,MAAM,WAAW,MAAM,GAAG,KAAK,OAAO;AAGnE,YAAM,UAAkC;AAAA,Q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EAAE,QAAQ;AAAA,EAC9E,aAAa;AACf,CAAC;","names":[]}
@@ -0,0 +1,44 @@
1
+ import "server-only";
2
+ import { serverConfig } from "../config/server.js";
3
+ const FORWARDER_SECRET_HEADER = "x-ecomweb-forwarder-secret";
4
+ const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
5
+ function isIpAddress(value) {
6
+ if (IPV4.test(value)) return true;
7
+ if (!value.includes(":") || !/^[0-9a-fA-F:.]+$/.test(value)) return false;
8
+ try {
9
+ new URL(`http://[${value}]/`);
10
+ return true;
11
+ } catch {
12
+ return false;
13
+ }
14
+ }
15
+ function validIp(value) {
16
+ const trimmed = value?.trim();
17
+ return trimmed && isIpAddress(trimmed) ? trimmed : void 0;
18
+ }
19
+ function clientIpFrom(headers) {
20
+ if (serverConfig().clientIpHeader === "cf-connecting-ip") {
21
+ return validIp(headers.get("cf-connecting-ip"));
22
+ }
23
+ return validIp(headers.get("x-forwarded-for")?.split(",")[0]) ?? validIp(headers.get("x-real-ip"));
24
+ }
25
+ function forwarderSecret() {
26
+ return serverConfig().clientIpForwarderSecret;
27
+ }
28
+ function forwardingHeaders(clientIp) {
29
+ const ip = validIp(clientIp);
30
+ if (!ip) return {};
31
+ const secret = forwarderSecret();
32
+ return secret ? { "x-forwarded-for": ip, [FORWARDER_SECRET_HEADER]: secret } : { "x-forwarded-for": ip };
33
+ }
34
+ function forwardedForHeader(headers) {
35
+ return forwardingHeaders(clientIpFrom(headers));
36
+ }
37
+ export {
38
+ FORWARDER_SECRET_HEADER,
39
+ clientIpFrom,
40
+ forwardedForHeader,
41
+ forwardingHeaders,
42
+ isIpAddress
43
+ };
44
+ //# sourceMappingURL=client-ip.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auth/client-ip.ts"],"sourcesContent":["import \"server-only\";\nimport { serverConfig } from \"../config/server\";\n\n/**\n * The shopper's IP, for forwarding to the backend, and the secret that makes\n * the backend believe it.\n *\n * Every auth call is now made server-side (`lib/auth/sdk.ts`, `lib/api/proxy.ts`,\n * the middleware's near-expiry refresh), so the backend's socket peer is this\n * Next server for every shopper of every store. Its throttler keys on\n * `storeId:clientIp` (`src/common/throttler/auth-throttler.guard.ts`), which\n * would collapse every shopper in a store into one 5-per-minute bucket unless\n * the real address travels with the request.\n *\n * The backend no longer takes `x-forwarded-for` on trust: its\n * `resolveClientIp` (`src/common/http/client-ip.ts` in the api repo) uses the\n * left-most entry ONLY when the request also carries `FORWARDER_SECRET_HEADER`\n * equal to its `CLIENT_IP_FORWARDER_SECRET`. Without the secret it falls back\n * to the peer address, i.e. this server's egress IP. So both headers travel\n * together, built in exactly one place: `forwardingHeaders()`.\n *\n * The value comes from the *incoming* request, from the header named by\n * `CLIENT_IP_HEADER` (server config): `x-forwarded-for` (default) where the\n * edge in front of this server overwrites it with the connecting address\n * (Vercel does, with `x-real-ip` too), or `cf-connecting-ip` behind\n * Cloudflare → Caddy → Kong, where proxies append to X-Forwarded-For and its\n * left end is whatever the shopper sent. Anything a browser sends\n * itself is stripped before it can reach the backend — see\n * `BLOCKED_REQUEST_HEADERS` in `lib/api/proxy.ts`, which drops these headers\n * and then re-sets them from this module. Order matters: block, then set.\n *\n * `server-only` because this module reads the secret. It must never be pulled\n * into a client bundle: the secret is what lets a caller choose the IP the\n * backend rate-limits on.\n */\n\n/** Must match `FORWARDER_SECRET_HEADER` in the api repo's client-ip.ts. */\nexport const FORWARDER_SECRET_HEADER = \"x-ecomweb-forwarder-secret\";\n\nconst IPV4 =\n /^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$/;\n\n/**\n * A syntactic IPv4/IPv6 check that works in every runtime this module is\n * bundled for (Node route handlers and the middleware), hence no `node:net`.\n * IPv6 syntax is delegated to the WHATWG URL parser, which rejects anything\n * that is not a valid IPv6 literal inside brackets.\n */\nexport function isIpAddress(value: string): boolean {\n if (IPV4.test(value)) return true;\n if (!value.includes(\":\") || !/^[0-9a-fA-F:.]+$/.test(value)) return false;\n try {\n new URL(`http://[${value}]/`);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction validIp(value: string | null | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && isIpAddress(trimmed) ? trimmed : undefined;\n}\n\n/**\n * @param headers the incoming request's headers\n * @returns with `CLIENT_IP_HEADER=cf-connecting-ip`, that header if it is a\n * well-formed IP (never a fallback to X-Forwarded-For, which the shopper\n * controls there); otherwise the first (left-most) `x-forwarded-for` entry,\n * else `x-real-ip`. `undefined` when none is a well-formed IP.\n */\nexport function clientIpFrom(headers: {\n get(name: string): string | null;\n}): string | undefined {\n if (serverConfig().clientIpHeader === \"cf-connecting-ip\") {\n return validIp(headers.get(\"cf-connecting-ip\"));\n }\n return (\n validIp(headers.get(\"x-forwarded-for\")?.split(\",\")[0]) ??\n validIp(headers.get(\"x-real-ip\"))\n );\n}\n\n/** The server-only secret, or `undefined` when unset/blank. */\nfunction forwarderSecret(): string | undefined {\n return serverConfig().clientIpForwarderSecret;\n}\n\n/**\n * Headers that carry the shopper's address to the backend:\n * `x-forwarded-for` set to the single validated IP, plus the forwarder secret\n * when `CLIENT_IP_FORWARDER_SECRET` is set. `{}` when no IP is known.\n *\n * Never sends an empty or placeholder value: the backend falls back to its own\n * view of the peer address, and a literal `\"unknown\"` would be one more shared\n * bucket rather than none. The secret is only sent alongside an IP, since on\n * its own it asserts nothing.\n *\n * @param clientIp the shopper's address, from `clientIpFrom(...)`. Re-validated\n * here so a caller can never smuggle a chain or a non-IP through.\n */\nexport function forwardingHeaders(clientIp?: string): Record<string, string> {\n const ip = validIp(clientIp);\n if (!ip) return {};\n\n const secret = forwarderSecret();\n return secret\n ? { \"x-forwarded-for\": ip, [FORWARDER_SECRET_HEADER]: secret }\n : { \"x-forwarded-for\": ip };\n}\n\n/** `forwardingHeaders(clientIpFrom(headers))`. */\nexport function forwardedForHeader(headers: {\n get(name: string): string | null;\n}): Record<string, string> {\n return forwardingHeaders(clientIpFrom(headers));\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,oBAAoB;AAoCtB,MAAM,0BAA0B;AAEvC,MAAM,OACJ;AAQK,SAAS,YAAY,OAAwB;AAClD,MAAI,KAAK,KAAK,KAAK,EAAG,QAAO;AAC7B,MAAI,CAAC,MAAM,SAAS,GAAG,KAAK,CAAC,mBAAmB,KAAK,KAAK,EAAG,QAAO;AACpE,MAAI;AACF,QAAI,IAAI,WAAW,KAAK,IAAI;AAC5B,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,QAAQ,OAAsD;AACrE,QAAM,UAAU,OAAO,KAAK;AAC5B,SAAO,WAAW,YAAY,OAAO,IAAI,UAAU;AACrD;AASO,SAAS,aAAa,SAEN;AACrB,MAAI,aAAa,EAAE,mBAAmB,oBAAoB;AACxD,WAAO,QAAQ,QAAQ,IAAI,kBAAkB,CAAC;AAAA,EAChD;AACA,SACE,QAAQ,QAAQ,IAAI,iBAAiB,GAAG,MAAM,GAAG,EAAE,CAAC,CAAC,KACrD,QAAQ,QAAQ,IAAI,WAAW,CAAC;AAEpC;AAGA,SAAS,kBAAsC;AAC7C,SAAO,aAAa,EAAE;AACxB;AAeO,SAAS,kBAAkB,UAA2C;AAC3E,QAAM,KAAK,QAAQ,QAAQ;AAC3B,MAAI,CAAC,GAAI,QAAO,CAAC;AAEjB,QAAM,SAAS,gBAAgB;AAC/B,SAAO,SACH,EAAE,mBAAmB,IAAI,CAAC,uBAAuB,GAAG,OAAO,IAC3D,EAAE,mBAAmB,GAAG;AAC9B;AAGO,SAAS,mBAAmB,SAER;AACzB,SAAO,kBAAkB,aAAa,OAAO,CAAC;AAChD;","names":[]}
@@ -0,0 +1,125 @@
1
+ "use client";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import {
4
+ createContext,
5
+ useCallback,
6
+ useContext,
7
+ useEffect,
8
+ useState
9
+ } from "react";
10
+ import { useStoreData } from "../store/store-context.js";
11
+ import { storeApiPath } from "../store-scope/index.js";
12
+ const AuthContext = createContext(void 0);
13
+ function AuthProvider({ children }) {
14
+ const store = useStoreData();
15
+ const storeRef = store.ref;
16
+ const [user, setUser] = useState(null);
17
+ const [loading, setLoading] = useState(true);
18
+ const base = storeApiPath(storeRef, "auth");
19
+ const loadUser = useCallback(async () => {
20
+ try {
21
+ const res = await fetch(storeApiPath(storeRef, "auth/session"), {
22
+ cache: "no-store"
23
+ });
24
+ setUser(res.ok ? (await res.json()).identity ?? null : null);
25
+ } catch {
26
+ setUser(null);
27
+ } finally {
28
+ setLoading(false);
29
+ }
30
+ }, [storeRef]);
31
+ useEffect(() => {
32
+ void loadUser();
33
+ }, [loadUser]);
34
+ const post = useCallback(
35
+ async (action, body) => {
36
+ const res = await fetch(`${base}/${action}`, {
37
+ method: "POST",
38
+ headers: { "Content-Type": "application/json" },
39
+ body: JSON.stringify(body ?? {})
40
+ });
41
+ if (!res.ok) {
42
+ const payload = await res.json().catch(() => null);
43
+ return { error: payload?.error ?? { message: "Request failed" } };
44
+ }
45
+ return { error: null };
46
+ },
47
+ [base]
48
+ );
49
+ const signIn = useCallback(
50
+ async (email, password) => {
51
+ const result = await post("login", { email, password });
52
+ if (!result.error) await loadUser();
53
+ return result;
54
+ },
55
+ [post, loadUser]
56
+ );
57
+ const signUp = useCallback(
58
+ async (email, password, name) => (
59
+ // Registration deliberately does not log the caller in. An anonymous
60
+ // identity being upgraded is identified server-side from the session
61
+ // cookie (lib/auth/route-handlers.ts), never from anything sent here.
62
+ post("register", { email, password, name })
63
+ ),
64
+ [post]
65
+ );
66
+ const sendLoginCode = useCallback(
67
+ async (email) => post("otp/request", { email }),
68
+ [post]
69
+ );
70
+ const verifyOtp = useCallback(
71
+ async (email, code) => {
72
+ const result = await post("otp/verify", { email, code });
73
+ if (!result.error) await loadUser();
74
+ return result;
75
+ },
76
+ [post, loadUser]
77
+ );
78
+ const signInWithGoogle = useCallback(
79
+ async (nextPath) => {
80
+ const res = await fetch(
81
+ `${base}/google/url?redirect_to=${encodeURIComponent(nextPath || "/")}`
82
+ );
83
+ if (!res.ok) return { error: { message: "Google sign-in unavailable" } };
84
+ const { url } = await res.json();
85
+ window.location.href = url;
86
+ return { error: null };
87
+ },
88
+ [base]
89
+ );
90
+ const signInAnonymously = useCallback(async () => {
91
+ const result = await post("anonymous");
92
+ if (!result.error) await loadUser();
93
+ return result;
94
+ }, [post, loadUser]);
95
+ const signOut = useCallback(async () => {
96
+ await post("logout");
97
+ setUser(null);
98
+ }, [post]);
99
+ const value = {
100
+ user,
101
+ loading,
102
+ isAnonymous: user?.is_anonymous ?? false,
103
+ signIn,
104
+ signUp,
105
+ sendLoginCode,
106
+ verifyOtp,
107
+ signInWithGoogle,
108
+ signInAnonymously,
109
+ signOut,
110
+ refresh: loadUser
111
+ };
112
+ return /* @__PURE__ */ jsx(AuthContext.Provider, { value, children });
113
+ }
114
+ function useAuth() {
115
+ const context = useContext(AuthContext);
116
+ if (context === void 0) {
117
+ throw new Error("useAuth must be used within an AuthProvider");
118
+ }
119
+ return context;
120
+ }
121
+ export {
122
+ AuthProvider,
123
+ useAuth
124
+ };
125
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auth/context.tsx"],"sourcesContent":["\"use client\";\n\nimport type React from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { useStoreData } from \"../store/store-context\";\nimport { storeApiPath } from \"../store-scope\";\n\ninterface AuthError {\n message: string;\n code?: string;\n}\n\ninterface AuthContextType {\n user: CurrentIdentity | null;\n loading: boolean;\n isAnonymous: boolean;\n signIn: (\n email: string,\n password: string\n ) => Promise<{ error: AuthError | null }>;\n signUp: (\n email: string,\n password: string,\n name?: string\n ) => Promise<{ error: AuthError | null }>;\n sendLoginCode: (email: string) => Promise<{ error: AuthError | null }>;\n verifyOtp: (\n email: string,\n code: string\n ) => Promise<{ error: AuthError | null }>;\n signInWithGoogle: (nextPath?: string) => Promise<{ error: AuthError | null }>;\n signInAnonymously: () => Promise<{ error: AuthError | null }>;\n signOut: () => Promise<void>;\n refresh: () => Promise<void>;\n}\n\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\nexport function AuthProvider({ children }: { children: React.ReactNode }) {\n const store = useStoreData();\n const storeRef = store.ref;\n const [user, setUser] = useState<CurrentIdentity | null>(null);\n const [loading, setLoading] = useState(true);\n\n const base = storeApiPath(storeRef, \"auth\");\n\n /** Tokens live in httpOnly cookies, so identity comes from the server. */\n const loadUser = useCallback(async () => {\n try {\n const res = await fetch(storeApiPath(storeRef, \"auth/session\"), {\n cache: \"no-store\",\n });\n setUser(res.ok ? ((await res.json()).identity ?? null) : null);\n } catch {\n setUser(null);\n } finally {\n setLoading(false);\n }\n }, [storeRef]);\n\n useEffect(() => {\n void loadUser();\n }, [loadUser]);\n\n const post = useCallback(\n async (\n action: string,\n body?: unknown\n ): Promise<{ error: AuthError | null }> => {\n const res = await fetch(`${base}/${action}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body ?? {}),\n });\n\n if (!res.ok) {\n const payload = await res.json().catch(() => null);\n return { error: payload?.error ?? { message: \"Request failed\" } };\n }\n\n return { error: null };\n },\n [base]\n );\n\n const signIn = useCallback(\n async (email: string, password: string) => {\n const result = await post(\"login\", { email, password });\n if (!result.error) await loadUser();\n return result;\n },\n [post, loadUser]\n );\n\n const signUp = useCallback(\n async (email: string, password: string, name?: string) =>\n // Registration deliberately does not log the caller in. An anonymous\n // identity being upgraded is identified server-side from the session\n // cookie (lib/auth/route-handlers.ts), never from anything sent here.\n post(\"register\", { email, password, name }),\n [post]\n );\n\n const sendLoginCode = useCallback(\n async (email: string) => post(\"otp/request\", { email }),\n [post]\n );\n\n const verifyOtp = useCallback(\n async (email: string, code: string) => {\n const result = await post(\"otp/verify\", { email, code });\n if (!result.error) await loadUser();\n return result;\n },\n [post, loadUser]\n );\n\n const signInWithGoogle = useCallback(\n async (nextPath?: string) => {\n const res = await fetch(\n `${base}/google/url?redirect_to=${encodeURIComponent(nextPath || \"/\")}`\n );\n\n if (!res.ok) return { error: { message: \"Google sign-in unavailable\" } };\n\n const { url } = await res.json();\n window.location.href = url;\n return { error: null };\n },\n [base]\n );\n\n const signInAnonymously = useCallback(async () => {\n const result = await post(\"anonymous\");\n if (!result.error) await loadUser();\n return result;\n }, [post, loadUser]);\n\n const signOut = useCallback(async () => {\n await post(\"logout\");\n setUser(null);\n }, [post]);\n\n const value: AuthContextType = {\n user,\n loading,\n isAnonymous: user?.is_anonymous ?? false,\n signIn,\n signUp,\n sendLoginCode,\n verifyOtp,\n signInWithGoogle,\n signInAnonymously,\n signOut,\n refresh: loadUser,\n };\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;\n}\n\nexport function useAuth() {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error(\"useAuth must be used within an AuthProvider\");\n }\n return context;\n}\n"],"mappings":";AAoKS;AAjKT;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AA+B7B,MAAM,cAAc,cAA2C,MAAS;AAEjE,SAAS,aAAa,EAAE,SAAS,GAAkC;AACxE,QAAM,QAAQ,aAAa;AAC3B,QAAM,WAAW,MAAM;AACvB,QAAM,CAAC,MAAM,OAAO,IAAI,SAAiC,IAAI;AAC7D,QAAM,CAAC,SAAS,UAAU,IAAI,SAAS,IAAI;AAE3C,QAAM,OAAO,aAAa,UAAU,MAAM;AAG1C,QAAM,WAAW,YAAY,YAAY;AACvC,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,aAAa,UAAU,cAAc,GAAG;AAAA,QAC9D,OAAO;AAAA,MACT,CAAC;AACD,cAAQ,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
1
+ function accessCookieName(storeRef) {
2
+ return `ecomweb_sf_${storeRef}_at`;
3
+ }
4
+ function refreshCookieName(storeRef) {
5
+ return `ecomweb_sf_${storeRef}_rt`;
6
+ }
7
+ const HOST_MAPPED_HEADER = "x-ecomweb-host-mapped";
8
+ function readAuthCookies(jar, storeRef) {
9
+ const access_token = jar.get(accessCookieName(storeRef))?.value;
10
+ const refresh_token = jar.get(refreshCookieName(storeRef))?.value;
11
+ if (!access_token || !refresh_token) return null;
12
+ return { access_token, refresh_token };
13
+ }
14
+ const LEGACY_PATH = "/";
15
+ function authCookiePath(storeRef, hostMapped) {
16
+ return hostMapped ? LEGACY_PATH : `/store/${encodeURIComponent(storeRef)}`;
17
+ }
18
+ function isHostMappedRequest(request) {
19
+ return request.headers.get(HOST_MAPPED_HEADER) !== "0";
20
+ }
21
+ function authCookiePathFor(request, storeRef) {
22
+ return authCookiePath(storeRef, isHostMappedRequest(request));
23
+ }
24
+ function storeBasePathFor(request, storeRef) {
25
+ return isHostMappedRequest(request) ? "" : `/store/${encodeURIComponent(storeRef)}`;
26
+ }
27
+ const BASE_OPTIONS = {
28
+ httpOnly: true,
29
+ secure: process.env.NODE_ENV === "production",
30
+ sameSite: "lax"
31
+ };
32
+ function oauthNonceCookieName(storeRef) {
33
+ return `ecomweb_sf_${storeRef}_oauth`;
34
+ }
35
+ const OAUTH_NONCE_MAX_AGE_SECONDS = 600;
36
+ function writeOAuthNonceCookie(response, storeRef, nonce, path) {
37
+ response.cookies.set(oauthNonceCookieName(storeRef), nonce, {
38
+ ...BASE_OPTIONS,
39
+ path,
40
+ maxAge: OAUTH_NONCE_MAX_AGE_SECONDS
41
+ });
42
+ }
43
+ function clearOAuthNonceCookie(response, storeRef, path) {
44
+ response.cookies.set(oauthNonceCookieName(storeRef), "", {
45
+ ...BASE_OPTIONS,
46
+ path,
47
+ maxAge: 0
48
+ });
49
+ }
50
+ function writeAuthCookies(response, storeRef, tokens, path) {
51
+ response.cookies.set(accessCookieName(storeRef), tokens.access_token, {
52
+ ...BASE_OPTIONS,
53
+ path
54
+ });
55
+ response.cookies.set(refreshCookieName(storeRef), tokens.refresh_token, {
56
+ ...BASE_OPTIONS,
57
+ path
58
+ });
59
+ }
60
+ function clearAuthCookies(response, storeRef, path) {
61
+ response.cookies.set(accessCookieName(storeRef), "", {
62
+ ...BASE_OPTIONS,
63
+ path,
64
+ maxAge: 0
65
+ });
66
+ response.cookies.set(refreshCookieName(storeRef), "", {
67
+ ...BASE_OPTIONS,
68
+ path,
69
+ maxAge: 0
70
+ });
71
+ const otherPath = path === LEGACY_PATH ? authCookiePath(storeRef, false) : LEGACY_PATH;
72
+ for (const name of [
73
+ accessCookieName(storeRef),
74
+ refreshCookieName(storeRef)
75
+ ]) {
76
+ response.headers.append(
77
+ "set-cookie",
78
+ `${name}=; Path=${otherPath}; Max-Age=0; HttpOnly; SameSite=Lax${BASE_OPTIONS.secure ? "; Secure" : ""}`
79
+ );
80
+ }
81
+ }
82
+ export {
83
+ HOST_MAPPED_HEADER,
84
+ accessCookieName,
85
+ authCookiePath,
86
+ authCookiePathFor,
87
+ clearAuthCookies,
88
+ clearOAuthNonceCookie,
89
+ isHostMappedRequest,
90
+ oauthNonceCookieName,
91
+ readAuthCookies,
92
+ refreshCookieName,
93
+ storeBasePathFor,
94
+ writeAuthCookies,
95
+ writeOAuthNonceCookie
96
+ };
97
+ //# sourceMappingURL=cookies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auth/cookies.ts"],"sourcesContent":["import type { NextResponse } from \"next/server\";\nimport type { AuthTokens } from \"@ecomweb/sdk\";\n\n/**\n * Cookie names are store-scoped because the platform serves many stores from\n * one origin (`/store/<storeRef>`). A shared name lets store B read store A's\n * session on the same domain.\n */\nexport function accessCookieName(storeRef: string): string {\n return `ecomweb_sf_${storeRef}_at`;\n}\n\nexport function refreshCookieName(storeRef: string): string {\n return `ecomweb_sf_${storeRef}_rt`;\n}\n\n/**\n * Request header the middleware (`proxy.ts`) stamps on every request it sees,\n * recording whether the **Host** identified the store — i.e. whether this is a\n * custom domain / subdomain deployment (one store per origin) or the shared\n * path-based host (`<origin>/store/<ref>/…`).\n *\n * It exists because the cookie `path` has to match the URL space the *browser*\n * is in, and the auth route handler cannot tell the two apart on its own: the\n * client calls `/store/<ref>/api/auth/*` in both cases (`lib/auth/context.tsx`).\n * The middleware is the only place that resolves Host → store.\n *\n * Always overwritten by the middleware, so a browser-supplied value cannot\n * survive on any path the middleware matches. On the paths it does not match\n * (root `/api/*`, which is reachable only on a custom domain) the value is\n * absent and the fallback is the unscoped path — the pre-existing behaviour.\n */\nexport const HOST_MAPPED_HEADER = \"x-ecomweb-host-mapped\";\n\n/** Minimal shape shared by `cookies()` and `request.cookies`. */\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** Minimal shape shared by `NextRequest` and a plain `Request`. */\ninterface HeaderReader {\n headers: { get(name: string): string | null };\n}\n\nexport function readAuthCookies(\n jar: CookieReader,\n storeRef: string\n): AuthTokens | null {\n const access_token = jar.get(accessCookieName(storeRef))?.value;\n const refresh_token = jar.get(refreshCookieName(storeRef))?.value;\n\n if (!access_token || !refresh_token) return null;\n\n return { access_token, refresh_token };\n}\n\n/**\n * The unscoped path every auth cookie used to be written with, and still is\n * on a custom domain. Also the path the migration has to clear: sessions\n * created before this change live here.\n */\nconst LEGACY_PATH = \"/\";\n\n/**\n * The `path` for this store's auth cookies.\n *\n * On the shared path-based host every store lives under `/store/<ref>/…`, so\n * scoping the cookie there keeps store B's server code from ever receiving\n * store A's token. On a custom domain the shopper's URLs are rooted at `/`\n * and the cookie must stay unscoped, or the browser would withhold it from\n * every page and the shopper would look signed out.\n */\nexport function authCookiePath(storeRef: string, hostMapped: boolean): string {\n return hostMapped ? LEGACY_PATH : `/store/${encodeURIComponent(storeRef)}`;\n}\n\n/**\n * Whether the Host identified the store for this request, per the middleware.\n *\n * Absent header → treated as host-mapped, i.e. exactly what this code did\n * before the scoping existed. Never guess \"shared host\" without evidence:\n * guessing wrong in that direction scopes the cookie to a path the shopper's\n * pages are not under, and hides their session from them.\n */\nexport function isHostMappedRequest(request: HeaderReader): boolean {\n return request.headers.get(HOST_MAPPED_HEADER) !== \"0\";\n}\n\n/** `authCookiePath` for an incoming request, using the middleware's stamp. */\nexport function authCookiePathFor(\n request: HeaderReader,\n storeRef: string\n): string {\n return authCookiePath(storeRef, isHostMappedRequest(request));\n}\n\n/**\n * The store's own root as the *browser* sees it: `\"\"` on a custom domain or\n * subdomain (the store is the origin), `/store/<ref>` on the shared\n * path-based host. Derived from the same signal as the cookie path so the two\n * can never disagree — and not from the request path, which is\n * `/store/<ref>/api/…` on both deployments.\n */\nexport function storeBasePathFor(\n request: HeaderReader,\n storeRef: string\n): string {\n return isHostMappedRequest(request)\n ? \"\"\n : `/store/${encodeURIComponent(storeRef)}`;\n}\n\nconst BASE_OPTIONS = {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\" as const,\n};\n\n/**\n * Binds an OAuth round trip to the browser that started it.\n *\n * `google/complete` has to accept GET — Google's redirect chain lands there —\n * and `sameSite: \"lax\"` sends cookies on a cross-site top-level navigation, so\n * without this a link on any site could feed a victim's browser a one-time\n * code the attacker minted from their OWN Google account and plant the\n * attacker's session in it. The signed `state` cannot help: the backend\n * consumes it before the storefront is ever reached.\n *\n * `lax` (not `strict`) is required here for the same reason it is on the\n * session cookies: the browser arrives from Google's origin.\n */\nexport function oauthNonceCookieName(storeRef: string): string {\n return `ecomweb_sf_${storeRef}_oauth`;\n}\n\n/** Long enough for a human to finish Google's consent screen, no longer. */\nconst OAUTH_NONCE_MAX_AGE_SECONDS = 600;\n\nexport function writeOAuthNonceCookie(\n response: NextResponse,\n storeRef: string,\n nonce: string,\n path: string\n): void {\n response.cookies.set(oauthNonceCookieName(storeRef), nonce, {\n ...BASE_OPTIONS,\n path,\n maxAge: OAUTH_NONCE_MAX_AGE_SECONDS,\n });\n}\n\nexport function clearOAuthNonceCookie(\n response: NextResponse,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(oauthNonceCookieName(storeRef), \"\", {\n ...BASE_OPTIONS,\n path,\n maxAge: 0,\n });\n}\n\nexport function writeAuthCookies(\n response: NextResponse,\n storeRef: string,\n tokens: AuthTokens,\n path: string\n): void {\n response.cookies.set(accessCookieName(storeRef), tokens.access_token, {\n ...BASE_OPTIONS,\n path,\n });\n response.cookies.set(refreshCookieName(storeRef), tokens.refresh_token, {\n ...BASE_OPTIONS,\n path,\n });\n}\n\n/**\n * Clearing has to name the identical path the cookie was written with — a\n * `Set-Cookie` with a different path creates a second, empty cookie and leaves\n * the real one in place. So logout clears BOTH paths, always.\n *\n * Not belt and braces: a cookie can genuinely exist at the other path. Every\n * session that predates the scoping lives at `Path=/`, and a request whose\n * Host lookup failed transiently writes the scoped path on a deployment that\n * otherwise uses the unscoped one. Either survivor would be handed straight\n * back by `readAuthCookies` — a live session the shopper believes they ended.\n */\nexport function clearAuthCookies(\n response: NextResponse,\n storeRef: string,\n path: string\n): void {\n response.cookies.set(accessCookieName(storeRef), \"\", {\n ...BASE_OPTIONS,\n path,\n maxAge: 0,\n });\n response.cookies.set(refreshCookieName(storeRef), \"\", {\n ...BASE_OPTIONS,\n path,\n maxAge: 0,\n });\n\n const otherPath =\n path === LEGACY_PATH ? authCookiePath(storeRef, false) : LEGACY_PATH;\n\n // `response.cookies` is keyed by name alone and rewrites the whole\n // Set-Cookie list on every `set()`, so a second cookie of the same name\n // cannot go through it and must be appended afterwards, never before.\n for (const name of [\n accessCookieName(storeRef),\n refreshCookieName(storeRef),\n ]) {\n response.headers.append(\n \"set-cookie\",\n `${name}=; Path=${otherPath}; Max-Age=0; HttpOnly; SameSite=Lax${\n BASE_OPTIONS.secure ? \"; Secure\" : \"\"\n }`\n );\n }\n}\n"],"mappings":"AAQO,SAAS,iBAAiB,UAA0B;AACzD,SAAO,cAAc,QAAQ;AAC/B;AAEO,SAAS,kBAAkB,UAA0B;AAC1D,SAAO,cAAc,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IACpE,GAAG;AAAA,IACH;AAAA,EACF,CAAC;AACD,WAAS,QAAQ,IAAI,kBAAkB,QAAQ,GAAG,OAAO,eAAe;AAAA,IACtE,GAAG;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAaO,SAAS,iBACd,UACA,UACA,MACM;AACN,WAAS,QAAQ,IAAI,iBAAiB,QAAQ,GAAG,IAAI;AAAA,IACnD,GAAG;AAAA,IACH;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AACD,WAAS,QAAQ,IAAI,kBAAkB,QAAQ,GAAG,IAAI;AAAA,IACpD,GAAG;AAAA,IACH;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AAED,QAAM,YACJ,SAAS,cAAc,eAAe,UAAU,KAAK,IAAI;AAK3D,aAAW,QAAQ;AAAA,IACjB,iBAAiB,QAAQ;AAAA,IACzB,kBAAkB,QAAQ;AAAA,EAC5B,GAAG;AACD,aAAS,QAAQ;AAAA,MACf;AAAA,MACA,GAAG,IAAI,WAAW,SAAS,sCACzB,aAAa,SAAS,aAAa,EACrC;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,49 @@
1
+ const GENERIC_ERROR_COPY = "\u0110\xE3 x\u1EA3y ra l\u1ED7i. Vui l\xF2ng th\u1EED l\u1EA1i.";
2
+ const ERROR_COPY = {
3
+ AUTH_INVALID_CREDENTIALS: "Email ho\u1EB7c m\u1EADt kh\u1EA9u kh\xF4ng \u0111\xFAng.",
4
+ AUTH_ACCOUNT_LOCKED: "Qu\xE1 nhi\u1EC1u l\u1EA7n th\u1EED. Vui l\xF2ng th\u1EED l\u1EA1i sau 15 ph\xFAt.",
5
+ AUTH_EMAIL_NOT_VERIFIED: "Vui l\xF2ng x\xE1c th\u1EF1c email c\u1EE7a b\u1EA1n tr\u01B0\u1EDBc.",
6
+ AUTH_METHOD_DISABLED: "Ph\u01B0\u01A1ng th\u1EE9c \u0111\u0103ng nh\u1EADp n\xE0y kh\xF4ng kh\u1EA3 d\u1EE5ng cho c\u1EEDa h\xE0ng n\xE0y.",
7
+ AUTH_TOKEN_INVALID: "M\xE3 x\xE1c th\u1EF1c kh\xF4ng h\u1EE3p l\u1EC7 ho\u1EB7c \u0111\xE3 \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng.",
8
+ AUTH_TOKEN_EXPIRED: "M\xE3 x\xE1c th\u1EF1c \u0111\xE3 h\u1EBFt h\u1EA1n. Vui l\xF2ng y\xEAu c\u1EA7u m\xE3 m\u1EDBi.",
9
+ AUTH_SESSION_EXPIRED: "Phi\xEAn \u0111\u0103ng nh\u1EADp \u0111\xE3 h\u1EBFt h\u1EA1n. Vui l\xF2ng \u0111\u0103ng nh\u1EADp l\u1EA1i.",
10
+ AUTH_WEAK_PASSWORD: "M\u1EADt kh\u1EA9u ch\u01B0a \u0111\xE1p \u1EE9ng y\xEAu c\u1EA7u c\u1EE7a c\u1EEDa h\xE0ng.",
11
+ AUTH_RATE_LIMITED: "Qu\xE1 nhi\u1EC1u y\xEAu c\u1EA7u. Vui l\xF2ng \u0111\u1EE3i m\u1ED9t ch\xFAt.",
12
+ AUTH_STORE_MISMATCH: "Phi\xEAn \u0111\u0103ng nh\u1EADp kh\xF4ng thu\u1ED9c c\u1EEDa h\xE0ng n\xE0y. Vui l\xF2ng \u0111\u0103ng nh\u1EADp l\u1EA1i.",
13
+ AUTH_EMAIL_TAKEN: "Email n\xE0y \u0111\xE3 \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng.",
14
+ ACCESS_DENIED: "B\u1EA1n kh\xF4ng c\xF3 quy\u1EC1n th\u1EF1c hi\u1EC7n thao t\xE1c n\xE0y.",
15
+ VALIDATION_FAILED: "Th\xF4ng tin ch\u01B0a h\u1EE3p l\u1EC7. Vui l\xF2ng ki\u1EC3m tra l\u1EA1i.",
16
+ ADDRESS_NOT_FOUND: "Kh\xF4ng t\xECm th\u1EA5y \u0111\u1ECBa ch\u1EC9 n\xE0y.",
17
+ ORDER_NOT_FOUND: "Kh\xF4ng t\xECm th\u1EA5y \u0111\u01A1n h\xE0ng n\xE0y.",
18
+ ORDER_NOT_CANCELLABLE: "\u0110\u01A1n h\xE0ng n\xE0y kh\xF4ng th\u1EC3 hu\u1EF7 \u0111\u01B0\u1EE3c n\u1EEFa.",
19
+ INSUFFICIENT_INVENTORY: "M\u1ED9t s\u1ED1 s\u1EA3n ph\u1EA9m kh\xF4ng \u0111\u1EE7 h\xE0ng."
20
+ };
21
+ const STATUS_COPY = {
22
+ 0: "Kh\xF4ng th\u1EC3 k\u1EBFt n\u1ED1i m\xE1y ch\u1EE7. Vui l\xF2ng ki\u1EC3m tra k\u1EBFt n\u1ED1i m\u1EA1ng.",
23
+ 401: "Phi\xEAn \u0111\u0103ng nh\u1EADp \u0111\xE3 h\u1EBFt h\u1EA1n. Vui l\xF2ng \u0111\u0103ng nh\u1EADp l\u1EA1i.",
24
+ 403: "B\u1EA1n kh\xF4ng c\xF3 quy\u1EC1n th\u1EF1c hi\u1EC7n thao t\xE1c n\xE0y.",
25
+ 404: "Kh\xF4ng t\xECm th\u1EA5y d\u1EEF li\u1EC7u y\xEAu c\u1EA7u.",
26
+ 429: "Qu\xE1 nhi\u1EC1u y\xEAu c\u1EA7u. Vui l\xF2ng \u0111\u1EE3i m\u1ED9t ch\xFAt.",
27
+ 500: "M\xE1y ch\u1EE7 \u0111ang g\u1EB7p s\u1EF1 c\u1ED1. Vui l\xF2ng th\u1EED l\u1EA1i sau.",
28
+ 502: "M\xE1y ch\u1EE7 \u0111ang g\u1EB7p s\u1EF1 c\u1ED1. Vui l\xF2ng th\u1EED l\u1EA1i sau.",
29
+ 503: "M\xE1y ch\u1EE7 \u0111ang b\u1EADn. Vui l\xF2ng th\u1EED l\u1EA1i sau.",
30
+ 504: "M\xE1y ch\u1EE7 ph\u1EA3n h\u1ED3i qu\xE1 l\xE2u. Vui l\xF2ng th\u1EED l\u1EA1i."
31
+ };
32
+ function errorCopy(code, fallback = GENERIC_ERROR_COPY) {
33
+ return code && ERROR_COPY[code] || fallback;
34
+ }
35
+ function errorCopyFor(error, fallback = GENERIC_ERROR_COPY) {
36
+ if (!error || typeof error !== "object") return fallback;
37
+ const { code, statusCode } = error;
38
+ if (typeof code === "string" && ERROR_COPY[code]) return ERROR_COPY[code];
39
+ if (typeof statusCode === "number" && STATUS_COPY[statusCode]) {
40
+ return STATUS_COPY[statusCode];
41
+ }
42
+ return fallback;
43
+ }
44
+ export {
45
+ GENERIC_ERROR_COPY,
46
+ errorCopy,
47
+ errorCopyFor
48
+ };
49
+ //# sourceMappingURL=error-copy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auth/error-copy.ts"],"sourcesContent":["/**\n * Shopper-facing copy for backend errors.\n *\n * Project rule: backend exception messages are written in English and are\n * never shown to a shopper. The backend serialises every business error as\n * `{ code, message, details, timestamp }` (see `src/common/exceptions/` in the\n * api repo) and `code` is the stable identifier — this module is the single\n * place that turns one into Vietnamese.\n *\n * The fallback is always a generic Vietnamese sentence. Never fall back to the\n * backend's `message`.\n */\n\nexport const GENERIC_ERROR_COPY = \"Đã xảy ra lỗi. Vui lòng thử lại.\";\n\n/**\n * Keyed by the backend's stable `code`. Sources, read directly rather than\n * guessed:\n * - `AUTH_*` — `src/modules/customer-auth/domain/constants/auth.constants.ts`\n * (`AUTH_ERROR`).\n * - `ACCESS_DENIED` — `AuthorizationException.accessDenied()`, thrown by\n * `customer-addresses.controller.ts` on an address the caller does not own.\n * - `<RESOURCE>_NOT_FOUND` — `ResourceNotFoundException`, whose code is\n * `${resource.toUpperCase()}_NOT_FOUND`. `Address` and `Order` are the two\n * resources the storefront's authenticated routes can produce.\n * - `VALIDATION_FAILED` — `ValidationException`.\n * - `ORDER_NOT_CANCELLABLE` — `ORDER_ERROR.NOT_CANCELLABLE`\n * (`src/modules/orders/domain/constants/order-error.constants.ts`),\n * thrown by `OrderCancelCommandHandler` when a customer tries to cancel\n * an order outside pending/confirmed/processing.\n * - `INSUFFICIENT_INVENTORY`: `InsufficientInventoryException`\n * (`src/modules/inventory/domain/exceptions/`), thrown when an order asks\n * for more of a deny-policy variant than is available.\n */\nconst ERROR_COPY: Record<string, string> = {\n AUTH_INVALID_CREDENTIALS: \"Email hoặc mật khẩu không đúng.\",\n AUTH_ACCOUNT_LOCKED: \"Quá nhiều lần thử. Vui lòng thử lại sau 15 phút.\",\n AUTH_EMAIL_NOT_VERIFIED: \"Vui lòng xác thực email của bạn trước.\",\n AUTH_METHOD_DISABLED:\n \"Phương thức đăng nhập này không khả dụng cho cửa hàng này.\",\n AUTH_TOKEN_INVALID: \"Mã xác thực không hợp lệ hoặc đã được sử dụng.\",\n AUTH_TOKEN_EXPIRED: \"Mã xác thực đã hết hạn. Vui lòng yêu cầu mã mới.\",\n AUTH_SESSION_EXPIRED: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n AUTH_WEAK_PASSWORD: \"Mật khẩu chưa đáp ứng yêu cầu của cửa hàng.\",\n AUTH_RATE_LIMITED: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n AUTH_STORE_MISMATCH:\n \"Phiên đăng nhập không thuộc cửa hàng này. Vui lòng đăng nhập lại.\",\n AUTH_EMAIL_TAKEN: \"Email này đã được sử dụng.\",\n\n ACCESS_DENIED: \"Bạn không có quyền thực hiện thao tác này.\",\n VALIDATION_FAILED: \"Thông tin chưa hợp lệ. Vui lòng kiểm tra lại.\",\n ADDRESS_NOT_FOUND: \"Không tìm thấy địa chỉ này.\",\n ORDER_NOT_FOUND: \"Không tìm thấy đơn hàng này.\",\n ORDER_NOT_CANCELLABLE: \"Đơn hàng này không thể huỷ được nữa.\",\n INSUFFICIENT_INVENTORY: \"Một số sản phẩm không đủ hàng.\",\n};\n\n/**\n * Nest's built-in `UnauthorizedException` / `ForbiddenException` (thrown by\n * `TenantUserAuthGuard`, `StorefrontApiKeyGuard` and the `@CurrentCustomer`\n * decorator) carry no `code` at all — only a status and English prose. Status\n * is the only stable signal there.\n */\nconst STATUS_COPY: Record<number, string> = {\n 0: \"Không thể kết nối máy chủ. Vui lòng kiểm tra kết nối mạng.\",\n 401: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n 403: \"Bạn không có quyền thực hiện thao tác này.\",\n 404: \"Không tìm thấy dữ liệu yêu cầu.\",\n 429: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n 500: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 502: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 503: \"Máy chủ đang bận. Vui lòng thử lại sau.\",\n 504: \"Máy chủ phản hồi quá lâu. Vui lòng thử lại.\",\n};\n\n/** Maps a backend error code to Vietnamese copy. */\nexport function errorCopy(\n code: string | null | undefined,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n return (code && ERROR_COPY[code]) || fallback;\n}\n\n/**\n * The same mapping for a caught throwable. `ApiClientError` (thrown by the\n * SDK's `unwrap`) carries `code` and `statusCode`; `lib/auth/context.tsx`\n * surfaces `{ message, code }`. Anything else falls through to `fallback`.\n *\n * The caught value's own `message` is deliberately never used: it is either\n * the backend's English prose or an axios internal string.\n */\nexport function errorCopyFor(\n error: unknown,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n if (!error || typeof error !== \"object\") return fallback;\n\n const { code, statusCode } = error as {\n code?: unknown;\n statusCode?: unknown;\n };\n\n if (typeof code === \"string\" && ERROR_COPY[code]) return ERROR_COPY[code];\n if (typeof statusCode === \"number\" && STATUS_COPY[statusCode]) {\n return STATUS_COPY[statusCode];\n }\n\n return fallback;\n}\n"],"mappings":"AAaO,MAAM,qBAAqB;AAqBlC,MAAM,aAAqC;AAAA,EACzC,0BAA0B;AAAA,EAC1B,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EACzB,sBACE;AAAA,EACF,oBAAoB;AAAA,EACpB,oBAAoB;AAAA,EACpB,sBAAsB;AAAA,EACtB,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,qBACE;AAAA,EACF,kBAAkB;AAAA,EAElB,eAAe;AAAA,EACf,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,uBAAuB;AAAA,EACvB,wBAAwB;AAC1B;AAQA,MAAM,cAAsC;AAAA,EAC1C,GAAG;AAAA,EACH,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAGO,SAAS,UACd,MACA,WAAmB,oBACX;AACR,SAAQ,QAAQ,WAAW,IAAI,KAAM;AACvC;AAUO,SAAS,aACd,OACA,WAAmB,oBACX;AACR,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,QAAM,EAAE,MAAM,WAAW,IAAI;AAK7B,MAAI,OAAO,SAAS,YAAY,WAAW,IAAI,EAAG,QAAO,WAAW,IAAI;AACxE,MAAI,OAAO,eAAe,YAAY,YAAY,UAAU,GAAG;AAC7D,WAAO,YAAY,UAAU;AAAA,EAC/B;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,29 @@
1
+ function getPasswordPolicyHints(policy) {
2
+ const hints = [`T\u1ED1i thi\u1EC3u ${policy.min_length} k\xFD t\u1EF1`];
3
+ if (policy.require_uppercase) hints.push("\xEDt nh\u1EA5t 1 ch\u1EEF hoa");
4
+ if (policy.require_number) hints.push("\xEDt nh\u1EA5t 1 ch\u1EEF s\u1ED1");
5
+ if (policy.require_symbol) hints.push("\xEDt nh\u1EA5t 1 k\xFD t\u1EF1 \u0111\u1EB7c bi\u1EC7t");
6
+ return hints;
7
+ }
8
+ function validatePasswordAgainstPolicy(password, policy) {
9
+ if (!password) return "Vui l\xF2ng nh\u1EADp m\u1EADt kh\u1EA9u";
10
+ const unmet = [];
11
+ if (password.length < policy.min_length) {
12
+ unmet.push(`t\u1ED1i thi\u1EC3u ${policy.min_length} k\xFD t\u1EF1`);
13
+ }
14
+ if (policy.require_uppercase && !/[A-Z]/.test(password)) {
15
+ unmet.push("\xEDt nh\u1EA5t 1 ch\u1EEF hoa");
16
+ }
17
+ if (policy.require_number && !/[0-9]/.test(password)) {
18
+ unmet.push("\xEDt nh\u1EA5t 1 ch\u1EEF s\u1ED1");
19
+ }
20
+ if (policy.require_symbol && !/[^A-Za-z0-9]/.test(password)) {
21
+ unmet.push("\xEDt nh\u1EA5t 1 k\xFD t\u1EF1 \u0111\u1EB7c bi\u1EC7t");
22
+ }
23
+ return unmet.length ? `M\u1EADt kh\u1EA9u c\u1EA7n: ${unmet.join(", ")}` : null;
24
+ }
25
+ export {
26
+ getPasswordPolicyHints,
27
+ validatePasswordAgainstPolicy
28
+ };
29
+ //# sourceMappingURL=password-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auth/password-policy.ts"],"sourcesContent":["import type { PasswordPolicy } from \"@ecomweb/sdk\";\n\n/**\n * The store's password rules, shared by every place a shopper can set a\n * password (the login/register form and the checkout \"create an account\"\n * option). The policy is per-store and comes from the public auth config, so\n * nothing here may hardcode a minimum length.\n *\n * The backend enforces the same rules and rejects a bad password with\n * `AUTH_WEAK_PASSWORD`; validating here only spares the shopper a round trip.\n */\n\nexport function getPasswordPolicyHints(policy: PasswordPolicy): string[] {\n const hints = [`Tối thiểu ${policy.min_length} ký tự`];\n if (policy.require_uppercase) hints.push(\"ít nhất 1 chữ hoa\");\n if (policy.require_number) hints.push(\"ít nhất 1 chữ số\");\n if (policy.require_symbol) hints.push(\"ít nhất 1 ký tự đặc biệt\");\n return hints;\n}\n\n/**\n * Returns a Vietnamese validation message, or `null` when the password\n * satisfies the store's policy.\n */\nexport function validatePasswordAgainstPolicy(\n password: string,\n policy: PasswordPolicy\n): string | null {\n if (!password) return \"Vui lòng nhập mật khẩu\";\n\n const unmet: string[] = [];\n if (password.length < policy.min_length) {\n unmet.push(`tối thiểu ${policy.min_length} ký tự`);\n }\n if (policy.require_uppercase && !/[A-Z]/.test(password)) {\n unmet.push(\"ít nhất 1 chữ hoa\");\n }\n if (policy.require_number && !/[0-9]/.test(password)) {\n unmet.push(\"ít nhất 1 chữ số\");\n }\n if (policy.require_symbol && !/[^A-Za-z0-9]/.test(password)) {\n unmet.push(\"ít nhất 1 ký tự đặc biệt\");\n }\n\n return unmet.length ? `Mật khẩu cần: ${unmet.join(\", \")}` : null;\n}\n"],"mappings":"AAYO,SAAS,uBAAuB,QAAkC;AACvE,QAAM,QAAQ,CAAC,uBAAa,OAAO,UAAU,gBAAQ;AACrD,MAAI,OAAO,kBAAmB,OAAM,KAAK,gCAAmB;AAC5D,MAAI,OAAO,eAAgB,OAAM,KAAK,oCAAkB;AACxD,MAAI,OAAO,eAAgB,OAAM,KAAK,yDAA0B;AAChE,SAAO;AACT;AAMO,SAAS,8BACd,UACA,QACe;AACf,MAAI,CAAC,SAAU,QAAO;AAEtB,QAAM,QAAkB,CAAC;AACzB,MAAI,SAAS,SAAS,OAAO,YAAY;AACvC,UAAM,KAAK,uBAAa,OAAO,UAAU,gBAAQ;AAAA,EACnD;AACA,MAAI,OAAO,qBAAqB,CAAC,QAAQ,KAAK,QAAQ,GAAG;AACvD,UAAM,KAAK,gCAAmB;AAAA,EAChC;AACA,MAAI,OAAO,kBAAkB,CAAC,QAAQ,KAAK,QAAQ,GAAG;AACpD,UAAM,KAAK,oCAAkB;AAAA,EAC/B;AACA,MAAI,OAAO,kBAAkB,CAAC,eAAe,KAAK,QAAQ,GAAG;AAC3D,UAAM,KAAK,yDAA0B;AAAA,EACvC;AAEA,SAAO,MAAM,SAAS,gCAAiB,MAAM,KAAK,IAAI,CAAC,KAAK;AAC9D;","names":[]}