@sgflabs/storefront-core 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -66,18 +66,19 @@ apex's single registered callback (state cookie and nonce helpers in `src/lib/he
66
66
  A separate first-party storefront on its own host (not a subdomain of the apex) can log in with Google through the same
67
67
  single callback, with no Google Console change.
68
68
 
69
- - On the apex set `SSO_HUB_RETURN_ORIGINS=<comma separated exact origins>`, for example `https://polymers.example.org`.
70
- Each entry must be a bare origin (no path, query, userinfo, wildcard, trailing dot or uppercase), https unless the apex
71
- itself is http, and not the apex. Invalid entries are dropped. Registered hosts receive customer JWTs that are valid
72
- across the backend, so only first-party hosts belong on the list.
69
+ - On the backend, give the app's publishable key its storefront URL (`POST /admin/opticomm/publishable-keys/{id}/storefront`)
70
+ and then enable the hub for it (`POST /admin/opticomm/publishable-keys/{id}/sso-hub` with `{ "enabled": true }`). The apex
71
+ asks `GET /store/opticomm/store-domains/sso-origin?host=` and accepts only that exact hostname (no wildcard or suffix
72
+ match); the answers are cached for 30 s (10 s for "no"), so a revoked host stops within that window. Registered hosts
73
+ receive customer JWTs that are valid across the backend, so only first-party hosts belong on the list.
73
74
  - The backend `vendor_domains` feature must be on: handoff mint and redeem return 404 without it, so the login fails
74
75
  after Google.
75
76
  - Registered hosts must not log query strings on `/api/auth/handoff`: the one-time code is in the URL for up to 60 seconds.
76
77
  - On the consuming app set `NEXT_PUBLIC_SSO_HUB_ORIGIN=<apex origin>` (build time and runtime). Do NOT set
77
- `SSO_HUB_SECRET` or `SSO_HUB_RETURN_ORIGINS` there. The app's `google-callback` refuses to exchange a code when this
78
+ `SSO_HUB_SECRET` there. The app's `google-callback` refuses to exchange a code when this
78
79
  variable is set.
79
80
  - Re-export `auth/handoff` only: never `google-start`, and delete any `google-callback` re-export.
80
81
  - Mount `<TenantHostProvider isTenantHost={false} googleSsoOrigin={ssoHubOrigin()}>`.
81
82
  - `NEXT_PUBLIC_BASE_URL` must be the exact public https origin of the app, and its proxy must send
82
83
  `x-forwarded-proto: https`. In this mode the handoff redeems for that configured host, never the `Host` header, so it works only for the
83
- exact host of `NEXT_PUBLIC_BASE_URL`: an alternate hostname that is also listed in `SSO_HUB_RETURN_ORIGINS` will not work.
84
+ exact host of `NEXT_PUBLIC_BASE_URL`: an alternate hostname that is also enabled as an SSO hub return origin will not work.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgflabs/storefront-core",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
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.6",
59
- "@sgflabs/page-spec": "^0.1.6",
60
- "@sgflabs/storefront-core-common": "^0.1.6",
58
+ "@sgflabs/gstin": "^0.1.8",
59
+ "@sgflabs/page-spec": "^0.1.8",
60
+ "@sgflabs/storefront-core-common": "^0.1.8",
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.6",
77
- "@sgflabs/page-spec": "^0.1.6",
78
- "@sgflabs/storefront-core-common": "^0.1.6",
76
+ "@sgflabs/gstin": "^0.1.8",
77
+ "@sgflabs/page-spec": "^0.1.8",
78
+ "@sgflabs/storefront-core-common": "^0.1.8",
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}`;
@@ -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 SSO_HUB_RETURN_ORIGINS; 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
  }
@@ -103,21 +112,79 @@ function bareOrigin(value: string): URL | null {
103
112
  const schemeAllowed = (url: URL): boolean =>
104
113
  url.protocol === "https:" || (url.protocol === "http:" && new URL(getSiteBaseUrl()).protocol === "http:")
105
114
 
115
+ const SSO_ORIGIN_TTL_MS = 30_000
116
+ const SSO_ORIGIN_NEGATIVE_TTL_MS = 10_000
117
+ // A host confirmed within this long past its TTL is "known": it skips the cold-lookup budget (it is still re-asked at the backend).
118
+ const SSO_ORIGIN_STALE_WINDOW_MS = 300_000
119
+ const SSO_ORIGIN_CACHE_MAX = 500
120
+ // Backstop on cold lookups per instance per minute, so random hosts cannot turn this app into an unbounded backend load.
121
+ const SSO_ORIGIN_MAX_COLD_FETCHES_PER_MINUTE = 1000
122
+ const SSO_ORIGIN_BUDGET_WINDOW_MS = 60_000
123
+ // Positives and negatives live apart: junk misses can only evict other junk, never a confirmed host.
124
+ const ssoOriginHits = new Map<string, { origin: string; expiresAt: number }>()
125
+ const ssoOriginMisses = new Map<string, number>()
126
+ let coldBudget = { count: 0, resetAt: 0 }
127
+
128
+ export const clearSsoOriginCache = () => {
129
+ ssoOriginHits.clear()
130
+ ssoOriginMisses.clear()
131
+ coldBudget = { count: 0, resetAt: 0 }
132
+ }
133
+
134
+ const remember = <V>(map: Map<string, V>, host: string, value: V) => {
135
+ map.delete(host)
136
+ map.set(host, value)
137
+ if (map.size > SSO_ORIGIN_CACHE_MAX) map.delete(map.keys().next().value as string)
138
+ }
139
+
106
140
  /**
107
- * The origin configured in SSO_HUB_RETURN_ORIGINS (comma separated, apex env) for this exact hostname, else null.
108
- * Re-read on every call; an entry that is not a bare https origin (http only under an http apex) on a hostname other
109
- * than the apex is dropped.
141
+ * The return origin the backend permits for exactly this host, or null. `fetchOrigin` is the backend lookup: it
142
+ * resolves an origin, or throws (a 404 error means "not enabled"; anything else is an outage). Fails closed: an
143
+ * error, a malformed origin or an origin on another hostname is null. Hits live 30 s and misses 10 s so one login
144
+ * does not ask twice; errors are never cached. ponytail: per-instance caches and cold-lookup budget, all bounded; a
145
+ * revoked flag stops within 30 s. A hit moves its entry to the end (LRU-ish). Only a cold host (no confirmation in the
146
+ * last 5 minutes) is charged to the per-minute budget and is refused (null) above it without asking the backend; a
147
+ * known host, even past its TTL, is always re-checked at the backend, so revocation is honoured and junk cannot lock it out.
110
148
  */
111
- export function registeredReturnOrigin(host: string): string | null {
112
- const apexUrl = new URL(getSiteBaseUrl())
113
- for (const entry of (process.env.SSO_HUB_RETURN_ORIGINS ?? "").split(",").map((e) => e.trim()).filter(Boolean)) {
114
- const url = bareOrigin(entry)
115
- if (!url || !schemeAllowed(url) || url.hostname === apexUrl.hostname.toLowerCase()) {
116
- console.warn("SSO_HUB_RETURN_ORIGINS: ignored an invalid entry")
117
- continue
149
+ export async function ssoOriginForHost(
150
+ host: string,
151
+ fetchOrigin: (host: string) => Promise<string>,
152
+ now = Date.now()
153
+ ): Promise<string | null> {
154
+ if (!isBareHostname(host) || host === apexHostname()) return null
155
+ const hit = ssoOriginHits.get(host)
156
+ if (hit && hit.expiresAt > now) {
157
+ remember(ssoOriginHits, host, hit)
158
+ return hit.origin
159
+ }
160
+ const missUntil = ssoOriginMisses.get(host)
161
+ if (missUntil !== undefined && missUntil > now) {
162
+ remember(ssoOriginMisses, host, missUntil)
163
+ return null
164
+ }
165
+ const known = hit !== undefined && hit.expiresAt + SSO_ORIGIN_STALE_WINDOW_MS > now
166
+ if (!known) {
167
+ if (coldBudget.resetAt <= now) coldBudget = { count: 0, resetAt: now + SSO_ORIGIN_BUDGET_WINDOW_MS }
168
+ if (++coldBudget.count > SSO_ORIGIN_MAX_COLD_FETCHES_PER_MINUTE) return null
169
+ }
170
+ try {
171
+ const raw = await fetchOrigin(host)
172
+ const url = bareOrigin(raw)
173
+ if (url && schemeAllowed(url) && url.hostname === host) {
174
+ ssoOriginMisses.delete(host)
175
+ remember(ssoOriginHits, host, { origin: raw, expiresAt: now + SSO_ORIGIN_TTL_MS })
176
+ return raw
177
+ }
178
+ } catch (error) {
179
+ const status = (error as { status?: unknown } | null)?.status
180
+ if (status !== 404) {
181
+ // Status only: neither the host nor the error text is logged.
182
+ console.warn(`sso-origin lookup failed (status ${typeof status === "number" ? status : "none"}); failing closed`)
183
+ return null
118
184
  }
119
- if (url.hostname === host) return entry
120
185
  }
186
+ ssoOriginHits.delete(host)
187
+ remember(ssoOriginMisses, host, now + SSO_ORIGIN_NEGATIVE_TTL_MS)
121
188
  return null
122
189
  }
123
190
 
@@ -0,0 +1,11 @@
1
+ import { getOpticommSdk } from "../config"
2
+ import { getClientIpHeaders } from "./client-ip-headers"
3
+ import { ssoOriginForHost } from "./sso-hub"
4
+
5
+ /** The Google SSO hub return origin the backend permits for `host` (null when not enabled or on any failure). */
6
+ export const lookupSsoOrigin = (host: string) =>
7
+ ssoOriginForHost(host, async (h) => {
8
+ const sdk = await getOpticommSdk()
9
+ // Forward the visitor IP so the backend budgets per visitor, not per storefront server.
10
+ return (await sdk.store.opticomm.retrieveStoreDomainsSsoOrigin<{ origin: string }>({ host: h }, await getClientIpHeaders())).origin
11
+ })
@@ -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,9 @@
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"
6
+ import { lookupSsoOrigin } from "../../../lib/helpers/sso-origin-lookup"
4
7
  import { getSiteBaseUrl } from "../../../lib/helpers/get-site-base-url"
5
8
  import {
6
9
  apexHostname,
@@ -9,7 +12,6 @@ import {
9
12
  originForHost,
10
13
  isHttpsRequest,
11
14
  readCookie,
12
- registeredReturnOrigin,
13
15
  resolveLocale,
14
16
  sameSecret,
15
17
  SSO_HUB_COOKIE,
@@ -42,9 +44,11 @@ export async function GET(request: Request) {
42
44
  // missing, tampered or expired one is a failed login: the code could be anyone's (login CSRF). Unset, no cookie is
43
45
  // today's apex flow.
44
46
  const locale = resolveLocale(hub ? hub.locale : url.searchParams.get("locale"))
45
- // A cookie issued for a registered host stays valid only while that host is still registered: removing it from
46
- // SSO_HUB_RETURN_ORIGINS must stop in-flight handoffs, not fall back to the tenant path.
47
- const registeredOrigin = hub ? registeredReturnOrigin(hub.host) : null
47
+ // A cookie issued for a registered host stays valid only while that host is still registered: un-flagging it in
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)
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
50
54
  const fail = () =>
@@ -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,13 +2,14 @@ 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"
6
+ import { lookupSsoOrigin } from "../../../lib/helpers/sso-origin-lookup"
5
7
  import { forwardedVisitorIp } from "../../../lib/helpers/visitor-ip"
6
8
  import {
7
9
  apexHostname,
8
10
  isBareHostname,
9
11
  isHttpsRequest,
10
12
  isNonce,
11
- registeredReturnOrigin,
12
13
  resolveLocale,
13
14
  sealSsoHubState,
14
15
  SSO_HUB_COOKIE,
@@ -37,23 +38,25 @@ function throttled(request: Request, now = Date.now()): boolean {
37
38
  return entry.count > MAX_STARTS_PER_WINDOW
38
39
  }
39
40
 
40
- /** The primary host of a live tenant (or the apex itself), flagged when it was accepted via SSO_HUB_RETURN_ORIGINS; null for anything else. No open redirect: only this answer ever reaches the cookie. */
41
+ /** The primary host of a live tenant (or the apex itself), flagged when it was accepted via the backend SSO-origin lookup; null for anything else. No open redirect: only this answer ever reaches the cookie. */
41
42
  async function trustedReturnHost(raw: string): Promise<{ host: string; registered: boolean } | null> {
42
43
  const host = raw.trim().toLowerCase()
43
44
  if (!isBareHostname(host)) return null
44
45
  if (host === apexHostname()) return { host, registered: false }
45
- if (registeredReturnOrigin(host)) return { host, registered: true }
46
+ // Resolver first on purpose: a host that is both a live tenant and an SSO-flagged origin stays a tenant (the
47
+ // flag only adds hosts the resolver does not know), so enabling the flag never changes how an existing tenant logs in.
46
48
  try {
47
49
  const sdk = await getOpticommSdk()
48
50
  const { primary_host } = await sdk.store.opticomm.retrieveStoreDomainsResolve<{ primary_host: string }>({ host })
49
- return isBareHostname(primary_host) ? { host: primary_host, registered: false } : null
51
+ if (isBareHostname(primary_host)) return { host: primary_host, registered: false }
50
52
  } catch {
51
- return null
53
+ // Not a live tenant (or the resolver is down): fall through to the SSO-origin lookup, which fails closed.
52
54
  }
55
+ return (await lookupSsoOrigin(host)) ? { host, registered: true } : null
53
56
  }
54
57
 
55
58
  /**
56
- * 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)
57
60
  *
58
61
  * Begins Google login for any storefront host on the apex, so Google only ever sees the one
59
62
  * registered callback. `return` is honoured only when it is the apex or a live tenant host per the
@@ -81,6 +84,9 @@ export async function GET(request: Request) {
81
84
  const nonce = isApex ? "" : (url.searchParams.get("n") ?? "")
82
85
  if (!isApex && !isNonce(nonce)) return reject()
83
86
 
87
+ // An invalid `next` is dropped, never a reason to refuse the login.
88
+ const next = sanitizePostLoginNext(url.searchParams.get("next"), locale)
89
+
84
90
  let location: string
85
91
  try {
86
92
  location = await getGoogleLoginUrl(`${origin}/api/google-callback`)
@@ -92,7 +98,7 @@ export async function GET(request: Request) {
92
98
  if (!state) return reject()
93
99
 
94
100
  const response = NextResponse.redirect(location)
95
- 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 } : {}) }), {
96
102
  httpOnly: true,
97
103
  sameSite: "lax",
98
104
  secure: isHttpsRequest(request),