@ecomweb/storefront-kit 0.13.0 → 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/auth/cookies.js +35 -0
- package/dist/auth/cookies.js.map +1 -1
- package/dist/auth/error-copy.js +1 -0
- package/dist/auth/error-copy.js.map +1 -1
- package/dist/auth/route-handlers.js +44 -6
- package/dist/auth/route-handlers.js.map +1 -1
- package/dist/checkout/use-checkout.js +3 -0
- package/dist/checkout/use-checkout.js.map +1 -1
- package/package.json +2 -2
package/dist/auth/cookies.js
CHANGED
|
@@ -51,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
|
package/dist/auth/cookies.js.map
CHANGED
|
@@ -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,UAAkB,MAAsB;AACvE,SAAO,mBAAmB,cAAc,QAAQ,OAAO,IAAI;AAC7D;AAEO,SAAS,kBAAkB,UAAkB,MAAsB;AACxE,SAAO,mBAAmB,cAAc,QAAQ,OAAO,IAAI;AAC7D;AAkBO,MAAM,qBAAqB;AAa3B,SAAS,gBACd,KACA,UACA,MACmB;AACnB,QAAM,eAAe,IAAI,IAAI,iBAAiB,UAAU,IAAI,CAAC,GAAG;AAChE,QAAM,gBAAgB,IAAI,IAAI,kBAAkB,UAAU,IAAI,CAAC,GAAG;AAElE,MAAI,CAAC,gBAAgB,CAAC,cAAe,QAAO;AAE5C,SAAO,EAAE,cAAc,cAAc;AACvC;AAOA,MAAM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AAI,iBAAiB,UAAU,IAAI,GAAG,IAAI;AAAA,IACzD,GAAG,YAAY;AAAA,IACf;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AACD,WAAS,QAAQ,IAAI,kBAAkB,UAAU,IAAI,GAAG,IAAI;AAAA,IAC1D,GAAG,YAAY;AAAA,IACf;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AAKD,QAAM,YACJ,SAAS,cAAc,eAAe,UAAU,KAAK,IAAI;AAC3D,QAAM,QAA6C;AAAA,IACjD,CAAC,iBAAiB,UAAU,SAAS,GAAG,SAAS;AAAA,IACjD,CAAC,kBAAkB,UAAU,SAAS,GAAG,SAAS;AAAA,EACpD;AACA,MAAI,cAAc,GAAG;AACnB,UAAM;AAAA,MACJ,CAAC,cAAc,QAAQ,OAAO,WAAW;AAAA,MACzC,CAAC,cAAc,QAAQ,OAAO,WAAW;AAAA,IAC3C;AAAA,EACF;AAKA,QAAM,SAAS,cAAc,IAAI,aAAa;AAC9C,aAAW,CAAC,MAAM,SAAS,KAAK,OAAO;AACrC,aAAS,QAAQ;AAAA,MACf;AAAA,MACA,GAAG,IAAI,WAAW,SAAS,sCAAsC,MAAM;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
|
|
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\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;AACnB,QAAM,eAAe,IAAI,IAAI,iBAAiB,UAAU,IAAI,CAAC,GAAG;AAChE,QAAM,gBAAgB,IAAI,IAAI,kBAAkB,UAAU,IAAI,CAAC,GAAG;AAElE,MAAI,CAAC,gBAAgB,CAAC,cAAe,QAAO;AAE5C,SAAO,EAAE,cAAc,cAAc;AACvC;AAOA,MAAM,cAAc;AAWb,SAAS,eAAe,UAAkB,YAA6B;AAC5E,SAAO,aAAa,cAAc,UAAU,mBAAmB,QAAQ,CAAC;AAC1E;AAUO,SAAS,oBAAoB,SAAgC;AAClE,SAAO,QAAQ,QAAQ,IAAI,kBAAkB,MAAM;AACrD;AAGO,SAAS,kBACd,SACA,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ANGED
|
@@ -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;
|
|
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":[]}
|
|
@@ -7,12 +7,15 @@ import { publicNextUrl } from "../request/public-url.js";
|
|
|
7
7
|
import {
|
|
8
8
|
authCookiePath,
|
|
9
9
|
clearAuthCookies,
|
|
10
|
+
clearEmailBindingCookie,
|
|
10
11
|
clearOAuthNonceCookie,
|
|
12
|
+
emailBindingCookieName,
|
|
11
13
|
isHostMappedRequest,
|
|
12
14
|
oauthNonceCookieName,
|
|
13
15
|
readAuthCookies,
|
|
14
16
|
writeAuthCookies,
|
|
15
17
|
storeBasePathFor,
|
|
18
|
+
writeEmailBindingCookie,
|
|
16
19
|
writeOAuthNonceCookie
|
|
17
20
|
} from "./cookies.js";
|
|
18
21
|
function fail(status, message, code) {
|
|
@@ -114,7 +117,18 @@ async function handleAuthRoute(request, storeRef, segments) {
|
|
|
114
117
|
res.error.message,
|
|
115
118
|
res.error.error
|
|
116
119
|
);
|
|
117
|
-
|
|
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;
|
|
118
132
|
}
|
|
119
133
|
case "login": {
|
|
120
134
|
const res = await auth.login(body);
|
|
@@ -184,14 +198,19 @@ async function handleAuthRoute(request, storeRef, segments) {
|
|
|
184
198
|
return response;
|
|
185
199
|
}
|
|
186
200
|
case "verify-email": {
|
|
187
|
-
const
|
|
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);
|
|
188
205
|
if (!res.success)
|
|
189
206
|
return fail(
|
|
190
207
|
res.error.statusCode,
|
|
191
208
|
res.error.message,
|
|
192
209
|
res.error.error
|
|
193
210
|
);
|
|
194
|
-
|
|
211
|
+
const verified = NextResponse.json(res.data);
|
|
212
|
+
clearEmailBindingCookie(verified, "verify-email", storeRef, cookiePath);
|
|
213
|
+
return verified;
|
|
195
214
|
}
|
|
196
215
|
case "resend-verification": {
|
|
197
216
|
const res = await auth.resendVerification(body.email);
|
|
@@ -251,17 +270,36 @@ async function handleAuthRoute(request, storeRef, segments) {
|
|
|
251
270
|
res.error.message,
|
|
252
271
|
res.error.error
|
|
253
272
|
);
|
|
254
|
-
|
|
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;
|
|
255
285
|
}
|
|
256
286
|
case "change-email/confirm": {
|
|
257
|
-
const
|
|
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
|
+
);
|
|
258
294
|
if (!res.success)
|
|
259
295
|
return fail(
|
|
260
296
|
res.error.statusCode,
|
|
261
297
|
res.error.message,
|
|
262
298
|
res.error.error
|
|
263
299
|
);
|
|
264
|
-
|
|
300
|
+
const confirmed = NextResponse.json(res.data);
|
|
301
|
+
clearEmailBindingCookie(confirmed, "change-email", storeRef, cookiePath);
|
|
302
|
+
return confirmed;
|
|
265
303
|
}
|
|
266
304
|
case "google/url": {
|
|
267
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 { storePreviewTokenFor } from \"../api/proxy\";\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(\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.\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,4BAA4B;AACrC,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP,SAAS,KAAK,QAAgB,SAAiB,MAAe;AAC5D,SAAO,aAAa;AAAA,IAClB,EAAE,OAAO,EAAE,SAAS,KAAK,EAAE;AAAA,IAC3B,EAAE,QAAQ,UAAU,IAAI;AAAA,EAC1B;AACF;AAkBA,MAAM,qBAAqB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AAM,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;AAAA,EACA;AAAA,EACA;AAAA,EACA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AAA,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"]}
|
|
@@ -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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,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,oBAA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"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.13.
|
|
50
|
+
"@ecomweb/sdk": "^0.13.1"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"next": ">=16",
|