@sgflabs/storefront-core 0.1.7 → 0.1.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgflabs/storefront-core",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Shared storefront library consumed as raw TypeScript source by the brand apps.",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "sideEffects": [
@@ -55,9 +55,9 @@
55
55
  "devDependencies": {
56
56
  "@sentry/nextjs": "^10.63.0",
57
57
  "@sgflabs/artha-go-sdk": "^0.2.0",
58
- "@sgflabs/gstin": "^0.1.7",
59
- "@sgflabs/page-spec": "^0.1.7",
60
- "@sgflabs/storefront-core-common": "^0.1.7",
58
+ "@sgflabs/gstin": "^0.1.9",
59
+ "@sgflabs/page-spec": "^0.1.9",
60
+ "@sgflabs/storefront-core-common": "^0.1.9",
61
61
  "@testing-library/dom": "^10.4.1",
62
62
  "@testing-library/jest-dom": "^7.0.0",
63
63
  "@testing-library/react": "^16.3.2",
@@ -73,9 +73,9 @@
73
73
  "peerDependencies": {
74
74
  "@sentry/nextjs": "^10.63.0",
75
75
  "@sgflabs/artha-go-sdk": "^0.2.0",
76
- "@sgflabs/gstin": "^0.1.7",
77
- "@sgflabs/page-spec": "^0.1.7",
78
- "@sgflabs/storefront-core-common": "^0.1.7",
76
+ "@sgflabs/gstin": "^0.1.9",
77
+ "@sgflabs/page-spec": "^0.1.9",
78
+ "@sgflabs/storefront-core-common": "^0.1.9",
79
79
  "next": "15.5.27",
80
80
  "react": "^19.2.3",
81
81
  "react-dom": "^19.2.3"
@@ -60,7 +60,7 @@ export const LoginForm = ({ embedded = false, onSuccess, returnTo }: LoginFormPr
60
60
  * is server-only; `__Host-` and Secure follow the page protocol, since browsers drop them over plain http).
61
61
  * The apex logs in on its own host and needs no nonce.
62
62
  */
63
- const startSsoHubGoogleLogin = (ssoOrigin: string, locale: string) => {
63
+ const startSsoHubGoogleLogin = (ssoOrigin: string, locale: string, next?: string | null) => {
64
64
  const params = new URLSearchParams({ return: window.location.hostname, locale });
65
65
  if (window.location.hostname !== new URL(ssoOrigin).hostname) {
66
66
  const nonce = Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) =>
@@ -70,6 +70,8 @@ const startSsoHubGoogleLogin = (ssoOrigin: string, locale: string) => {
70
70
  document.cookie = `${https ? '__Host-sso_hub_nonce' : 'sso_hub_nonce'}=${nonce}; Path=/; Max-Age=600; SameSite=Lax${https ? '; Secure' : ''}`;
71
71
  params.set('n', nonce);
72
72
  }
73
+ // Page to land on after sign-in; google-start validates it and drops anything unsafe.
74
+ if (next) params.set('next', next.split(/[?#]/, 1)[0]);
73
75
  window.location.href = `${ssoOrigin}/api/google-start?${params.toString()}`;
74
76
  };
75
77
 
@@ -94,7 +96,7 @@ const GoogleButton = ({
94
96
  await setLoginReturnToAction(path)
95
97
  }
96
98
  if (ssoOrigin) {
97
- startSsoHubGoogleLogin(ssoOrigin, locale);
99
+ startSsoHubGoogleLogin(ssoOrigin, locale, path);
98
100
  return;
99
101
  }
100
102
  const callbackUrl = `${window.location.origin}/api/google-callback?locale=${locale}`;
@@ -12,7 +12,7 @@ import { isNotFoundError } from "../../../lib/helpers/medusa-error"
12
12
  import { SellerProps } from "../../../types/seller"
13
13
 
14
14
  const CAROUSEL_SLIDE =
15
- "shrink-0 pr-4 last:pr-0 w-[min(100%,280px)] max-w-[300px] sm:w-[270px]"
15
+ "shrink-0 mr-4 last:mr-0 w-[min(100%,280px)] max-w-[300px] sm:w-[270px]"
16
16
 
17
17
  /**
18
18
  * Cap on how many hydrated cards the carousel actually renders. The typeId
@@ -7,9 +7,9 @@ import { decodeTokenClaims } from "./token-claims"
7
7
  /**
8
8
  * Post-Google-login steps shared by the apex callback and the tenant handoff:
9
9
  * session cookie on the current host, customer cache refresh, then registration
10
- * completion for a new Google identity or cart transfer + account page.
10
+ * completion for a new Google identity or cart transfer + `next` (an already-validated page path) or the account page.
11
11
  */
12
- export async function finishGoogleLogin(token: string, locale: string, origin: string) {
12
+ export async function finishGoogleLogin(token: string, locale: string, origin: string, next: string | null = null) {
13
13
  await setAuthToken(token)
14
14
  const customerCacheTag = await getCacheTag("customers")
15
15
  revalidateTag(customerCacheTag)
@@ -26,5 +26,5 @@ export async function finishGoogleLogin(token: string, locale: string, origin: s
26
26
  }
27
27
 
28
28
  await transferCart()
29
- return NextResponse.redirect(new URL(`/${locale}/user`, origin))
29
+ return NextResponse.redirect(new URL(next ?? `/${locale}/user`, origin))
30
30
  }
@@ -0,0 +1,39 @@
1
+ import { normalizeLoginReturnPath } from "./login-return-to"
2
+
3
+ const LOCALE_PREFIX = /^\/[a-z]{2}(\/|$)/i
4
+ // Encoded slash/backslash: browsers keep them literal, but a downstream decode would turn `/%2F/x` into `//x`.
5
+ const ENCODED_SEPARATOR = /%(2f|5c)/i
6
+ const ENCODED_DOT = /%2e/gi
7
+ const PLACEHOLDER_ORIGIN = "https://placeholder.invalid"
8
+
9
+ /** True for the post-login hop itself and the auth routes, judged on the path the browser will actually request. */
10
+ function isAuthPath(resolved: string): boolean {
11
+ const lower = resolved.toLowerCase()
12
+ const withoutLocale = LOCALE_PREFIX.test(lower) ? lower.replace(/^\/[a-z]{2}/, "") || "/" : lower
13
+ const trimmed = withoutLocale.length > 1 ? withoutLocale.replace(/\/+$/, "") : withoutLocale
14
+ return trimmed === "/login" || trimmed === "/register" || trimmed === "/user" || trimmed === "/api" || trimmed.startsWith("/api/")
15
+ }
16
+
17
+ /**
18
+ * The page-only `next` path to return a Google login to, or null (callers then fall back to the account page).
19
+ * Same-origin relative path via the login-return rules (isSafeRelativePath, length cap, never /login, /register,
20
+ * /api/*, /user); the query and fragment are dropped so no token-like param can ride along, dot-segments are
21
+ * resolved the way the browser will (so `/in/x/../login` is judged as `/in/login`), and a path without a locale
22
+ * prefix gets `locale`. Validate at every hop: the URL and cookie are not trusted on arrival.
23
+ */
24
+ export function sanitizePostLoginNext(raw: unknown, locale: string): string | null {
25
+ if (typeof raw !== "string") return null
26
+ const pathOnly = raw.split(/[?#]/, 1)[0]
27
+ if (ENCODED_SEPARATOR.test(pathOnly)) return null
28
+ if (!normalizeLoginReturnPath(pathOnly)) return null
29
+ let resolved: string
30
+ try {
31
+ resolved = new URL(pathOnly.replace(ENCODED_DOT, "."), PLACEHOLDER_ORIGIN).pathname
32
+ } catch {
33
+ return null
34
+ }
35
+ if (resolved.startsWith("//")) return null
36
+ const localized = LOCALE_PREFIX.test(resolved) ? resolved : `/${locale}${resolved}`
37
+ if (isAuthPath(localized)) return null
38
+ return normalizeLoginReturnPath(localized)
39
+ }
@@ -1,6 +1,7 @@
1
1
  import { createHmac, timingSafeEqual } from "node:crypto"
2
2
 
3
3
  import { getSiteBaseUrl } from "./get-site-base-url"
4
+ import { sanitizePostLoginNext } from "./post-login-next"
4
5
 
5
6
  export const SSO_HUB_COOKIE = "_sso_hub"
6
7
  export const SSO_HUB_COOKIE_MAX_AGE_SECONDS = 600
@@ -16,9 +17,9 @@ export function isHttpsRequest(request: Request): boolean {
16
17
 
17
18
  /**
18
19
  * `nonce` is empty for an apex login (no handoff to bind); `state` is the OAuth state Google was handed.
19
- * `registered` is true when google-start accepted the host via the backend sso-origin lookup (an admin-enabled publishable key); cookies without it read as not registered.
20
+ * `next` is the validated page to return to after login (re-validated wherever it is used). `registered` is true when google-start accepted the host via the backend sso-origin lookup (an admin-enabled publishable key); cookies without it read as not registered.
20
21
  */
21
- export type SsoHubState = { host: string; locale: string; nonce: string; state: string; registered?: boolean }
22
+ export type SsoHubState = { host: string; locale: string; nonce: string; state: string; registered?: boolean; next?: string }
22
23
 
23
24
  const MIN_SECRET_LENGTH = 32
24
25
  const HOSTNAME_PATTERN = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/
@@ -41,7 +42,7 @@ export function sealSsoHubState(state: SsoHubState, now = Date.now()): string {
41
42
  throw new Error("SSO_HUB_SECRET is not configured")
42
43
  }
43
44
  const payload = Buffer.from(
44
- JSON.stringify({ host: state.host, locale: state.locale, nonce: state.nonce, state: state.state, ...(state.registered ? { registered: true } : {}), exp: now + SSO_HUB_COOKIE_MAX_AGE_SECONDS * 1000 })
45
+ JSON.stringify({ host: state.host, locale: state.locale, nonce: state.nonce, state: state.state, ...(state.registered ? { registered: true } : {}), ...(state.next ? { next: state.next } : {}), exp: now + SSO_HUB_COOKIE_MAX_AGE_SECONDS * 1000 })
45
46
  ).toString("base64url")
46
47
  return `${payload}.${sign(payload)}`
47
48
  }
@@ -56,11 +57,19 @@ export function openSsoHubState(value: string | undefined, now = Date.now()): Ss
56
57
  const given = Buffer.from(signature)
57
58
  if (expected.length !== given.length || !timingSafeEqual(expected, given)) return null
58
59
  try {
59
- const { host, locale, nonce, state, exp, registered } = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8")) as Record<string, unknown>
60
+ const { host, locale, nonce, state, exp, registered, next } = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8")) as Record<string, unknown>
60
61
  if (typeof host !== "string" || typeof locale !== "string" || typeof nonce !== "string" || typeof state !== "string" || typeof exp !== "number" || exp <= now) {
61
62
  return null
62
63
  }
63
- return registered === true ? { host, locale, nonce, state, registered } : { host, locale, nonce, state }
64
+ const safeNext = sanitizePostLoginNext(next, locale)
65
+ return {
66
+ host,
67
+ locale,
68
+ nonce,
69
+ state,
70
+ ...(registered === true ? { registered } : {}),
71
+ ...(safeNext ? { next: safeNext } : {}),
72
+ }
64
73
  } catch {
65
74
  return null
66
75
  }
@@ -15,12 +15,14 @@ import {
15
15
  ssoHubNonceCookie,
16
16
  ssoHubOrigin,
17
17
  } from "../../../../lib/helpers/sso-hub"
18
+ import { clearLoginReturnCookie } from "../../../../lib/helpers/apply-login-return-cookie"
19
+ import { sanitizePostLoginNext } from "../../../../lib/helpers/post-login-next"
18
20
  import { getSiteBaseUrl } from "../../../../lib/helpers/get-site-base-url"
19
21
 
20
22
  const CODE_PATTERN = /^[A-Za-z0-9_-]{43}$/
21
23
 
22
24
  /**
23
- * GET /api/auth/handoff?code=...&locale=xx&n=<nonce>
25
+ * GET /api/auth/handoff?code=...&locale=xx&n=<nonce>&next=<path>
24
26
  *
25
27
  * Tenant half of the Google SSO hub. The apex redirects here with a one-time code; this host
26
28
  * redeems it server-side for its own host (taken from the Host header, never the URL) and sets
@@ -66,7 +68,10 @@ export async function GET(request: Request) {
66
68
  return fail()
67
69
  }
68
70
 
69
- const response = await finishGoogleLogin(token, locale, origin)
71
+ const next = sanitizePostLoginNext(url.searchParams.get("next"), locale)
72
+ const response = await finishGoogleLogin(token, locale, origin, next)
73
+ // Landing on `next` skips the /user hop that normally clears the stored return path.
74
+ if (next) clearLoginReturnCookie(response.cookies)
70
75
  response.cookies.set(clearedCookie(nonceCookie, "/", secure))
71
76
  return response
72
77
  }
@@ -1,6 +1,8 @@
1
1
  import { NextResponse } from "next/server"
2
2
  import { getOpticommSdk, getSdk } from "../../../lib/config"
3
3
  import { finishGoogleLogin } from "../../../lib/data/finish-google-login"
4
+ import { clearLoginReturnCookie } from "../../../lib/helpers/apply-login-return-cookie"
5
+ import { sanitizePostLoginNext } from "../../../lib/helpers/post-login-next"
4
6
  import { lookupSsoOrigin } from "../../../lib/helpers/sso-origin-lookup"
5
7
  import { getSiteBaseUrl } from "../../../lib/helpers/get-site-base-url"
6
8
  import {
@@ -44,6 +46,8 @@ export async function GET(request: Request) {
44
46
  const locale = resolveLocale(hub ? hub.locale : url.searchParams.get("locale"))
45
47
  // A cookie issued for a registered host stays valid only while that host is still registered: un-flagging it in
46
48
  // the backend must stop in-flight handoffs, not fall back to the tenant path.
49
+ // Re-validated here: the sealed value is signed, but this is the hop that builds the redirect.
50
+ const next = sanitizePostLoginNext(hub?.next, locale)
47
51
  const registeredOrigin = hub?.registered ? await lookupSsoOrigin(hub.host) : null
48
52
  const revoked = Boolean(hub?.registered) && !registeredOrigin
49
53
  const tenantOrigin = hub && !revoked && hub.host !== apexHostname() ? (registeredOrigin ?? originForHost(hub.host)) : null
@@ -93,11 +97,15 @@ export async function GET(request: Request) {
93
97
  handoff.searchParams.set("code", code)
94
98
  handoff.searchParams.set("locale", locale)
95
99
  handoff.searchParams.set("n", hub.nonce)
100
+ if (next) handoff.searchParams.set("next", next)
96
101
  return withHubCookieCleared(NextResponse.redirect(handoff))
97
102
  } catch {
98
103
  return fail()
99
104
  }
100
105
  }
101
106
 
102
- return withHubCookieCleared(await finishGoogleLogin(token, locale, origin))
107
+ const response = withHubCookieCleared(await finishGoogleLogin(token, locale, origin, next))
108
+ // Landing on `next` skips the /user hop that normally clears the stored return path.
109
+ if (next) clearLoginReturnCookie(response.cookies)
110
+ return response
103
111
  }
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server"
2
2
  import { getOpticommSdk } from "../../../lib/config"
3
3
  import { getGoogleLoginUrl } from "../../../lib/data/customer"
4
4
  import { getSiteBaseUrl } from "../../../lib/helpers/get-site-base-url"
5
+ import { sanitizePostLoginNext } from "../../../lib/helpers/post-login-next"
5
6
  import { lookupSsoOrigin } from "../../../lib/helpers/sso-origin-lookup"
6
7
  import { forwardedVisitorIp } from "../../../lib/helpers/visitor-ip"
7
8
  import {
@@ -55,7 +56,7 @@ async function trustedReturnHost(raw: string): Promise<{ host: string; registere
55
56
  }
56
57
 
57
58
  /**
58
- * GET /api/google-start?return=<host>&locale=xx&n=<nonce> (`n` only for a tenant host, not the apex)
59
+ * GET /api/google-start?return=<host>&locale=xx&n=<nonce>&next=<path> (`next` optional; `n` only for a tenant host, not the apex)
59
60
  *
60
61
  * Begins Google login for any storefront host on the apex, so Google only ever sees the one
61
62
  * registered callback. `return` is honoured only when it is the apex or a live tenant host per the
@@ -83,6 +84,9 @@ export async function GET(request: Request) {
83
84
  const nonce = isApex ? "" : (url.searchParams.get("n") ?? "")
84
85
  if (!isApex && !isNonce(nonce)) return reject()
85
86
 
87
+ // An invalid `next` is dropped, never a reason to refuse the login.
88
+ const next = sanitizePostLoginNext(url.searchParams.get("next"), locale)
89
+
86
90
  let location: string
87
91
  try {
88
92
  location = await getGoogleLoginUrl(`${origin}/api/google-callback`)
@@ -94,7 +98,7 @@ export async function GET(request: Request) {
94
98
  if (!state) return reject()
95
99
 
96
100
  const response = NextResponse.redirect(location)
97
- response.cookies.set(SSO_HUB_COOKIE, sealSsoHubState({ host, locale, nonce, state, registered }), {
101
+ response.cookies.set(SSO_HUB_COOKIE, sealSsoHubState({ host, locale, nonce, state, registered, ...(next ? { next } : {}) }), {
98
102
  httpOnly: true,
99
103
  sameSite: "lax",
100
104
  secure: isHttpsRequest(request),