@sgflabs/storefront-core 0.1.5 → 0.1.6

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
@@ -60,3 +60,24 @@ apex's single registered callback (state cookie and nonce helpers in `src/lib/he
60
60
  `src/lib/data/finish-google-login.ts`). The flow, abuse cases and required env (`SSO_HUB_SECRET`) are in
61
61
  [`apps/opticomm-storefront/README.md`](../../apps/opticomm-storefront/README.md). Only the opticomm storefront re-exports
62
62
  `google-start` and `auth/handoff`; the other storefronts keep their own `google-callback` and are unchanged.
63
+
64
+ ### Registered return origins and hub-client apps
65
+
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
+ single callback, with no Google Console change.
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.
73
+ - The backend `vendor_domains` feature must be on: handoff mint and redeem return 404 without it, so the login fails
74
+ after Google.
75
+ - 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
+ - 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
+ variable is set.
79
+ - Re-export `auth/handoff` only: never `google-start`, and delete any `google-callback` re-export.
80
+ - Mount `<TenantHostProvider isTenantHost={false} googleSsoOrigin={ssoHubOrigin()}>`.
81
+ - `NEXT_PUBLIC_BASE_URL` must be the exact public https origin of the app, and its proxy must send
82
+ `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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgflabs/storefront-core",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
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.5",
59
- "@sgflabs/page-spec": "^0.1.5",
60
- "@sgflabs/storefront-core-common": "^0.1.5",
58
+ "@sgflabs/gstin": "^0.1.6",
59
+ "@sgflabs/page-spec": "^0.1.6",
60
+ "@sgflabs/storefront-core-common": "^0.1.6",
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.5",
77
- "@sgflabs/page-spec": "^0.1.5",
78
- "@sgflabs/storefront-core-common": "^0.1.5",
76
+ "@sgflabs/gstin": "^0.1.6",
77
+ "@sgflabs/page-spec": "^0.1.6",
78
+ "@sgflabs/storefront-core-common": "^0.1.6",
79
79
  "next": "15.5.27",
80
80
  "react": "^19.2.3",
81
81
  "react-dom": "^19.2.3"
@@ -14,8 +14,11 @@ export function isHttpsRequest(request: Request): boolean {
14
14
  return forwarded ? forwarded === "https" : new URL(request.url).protocol === "https:"
15
15
  }
16
16
 
17
- /** `nonce` is empty for an apex login (no handoff to bind); `state` is the OAuth state Google was handed. */
18
- export type SsoHubState = { host: string; locale: string; nonce: string; state: string }
17
+ /**
18
+ * `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
+ */
21
+ export type SsoHubState = { host: string; locale: string; nonce: string; state: string; registered?: boolean }
19
22
 
20
23
  const MIN_SECRET_LENGTH = 32
21
24
  const HOSTNAME_PATTERN = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/
@@ -38,7 +41,7 @@ export function sealSsoHubState(state: SsoHubState, now = Date.now()): string {
38
41
  throw new Error("SSO_HUB_SECRET is not configured")
39
42
  }
40
43
  const payload = Buffer.from(
41
- JSON.stringify({ host: state.host, locale: state.locale, nonce: state.nonce, state: state.state, exp: now + SSO_HUB_COOKIE_MAX_AGE_SECONDS * 1000 })
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 })
42
45
  ).toString("base64url")
43
46
  return `${payload}.${sign(payload)}`
44
47
  }
@@ -53,11 +56,11 @@ export function openSsoHubState(value: string | undefined, now = Date.now()): Ss
53
56
  const given = Buffer.from(signature)
54
57
  if (expected.length !== given.length || !timingSafeEqual(expected, given)) return null
55
58
  try {
56
- const { host, locale, nonce, state, exp } = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8")) as Record<string, unknown>
59
+ const { host, locale, nonce, state, exp, registered } = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8")) as Record<string, unknown>
57
60
  if (typeof host !== "string" || typeof locale !== "string" || typeof nonce !== "string" || typeof state !== "string" || typeof exp !== "number" || exp <= now) {
58
61
  return null
59
62
  }
60
- return { host, locale, nonce, state }
63
+ return registered === true ? { host, locale, nonce, state, registered } : { host, locale, nonce, state }
61
64
  } catch {
62
65
  return null
63
66
  }
@@ -86,6 +89,46 @@ export function originForHost(host: string): string {
86
89
  return `${base.protocol}//${host}${base.port ? `:${base.port}` : ""}`
87
90
  }
88
91
 
92
+ /** A bare origin (`scheme://host[:port]`, nothing else) whose hostname is a plain DNS name; `new URL` round-trip rejects every extra part. */
93
+ function bareOrigin(value: string): URL | null {
94
+ try {
95
+ const url = new URL(value)
96
+ return url.origin === value && isBareHostname(url.hostname) ? url : null
97
+ } catch {
98
+ return null
99
+ }
100
+ }
101
+
102
+ /** https, or http only when this app's own base URL is http. */
103
+ const schemeAllowed = (url: URL): boolean =>
104
+ url.protocol === "https:" || (url.protocol === "http:" && new URL(getSiteBaseUrl()).protocol === "http:")
105
+
106
+ /**
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.
110
+ */
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
118
+ }
119
+ if (url.hostname === host) return entry
120
+ }
121
+ return null
122
+ }
123
+
124
+ /** Hub-client mode: the apex origin this app logs in through (NEXT_PUBLIC_SSO_HUB_ORIGIN), or null when unset, invalid or this app's own host. */
125
+ export function ssoHubOrigin(): string | null {
126
+ const value = process.env.NEXT_PUBLIC_SSO_HUB_ORIGIN
127
+ if (!value) return null
128
+ const url = bareOrigin(value)
129
+ return url && schemeAllowed(url) && url.hostname !== apexHostname() ? value : null
130
+ }
131
+
89
132
  export function readCookie(request: Request, name: string): string | undefined {
90
133
  for (const part of (request.headers.get("cookie") ?? "").split(";")) {
91
134
  const index = part.indexOf("=")
@@ -13,6 +13,7 @@ import {
13
13
  resolveLocale,
14
14
  sameSecret,
15
15
  ssoHubNonceCookie,
16
+ ssoHubOrigin,
16
17
  } from "../../../../lib/helpers/sso-hub"
17
18
  import { getSiteBaseUrl } from "../../../../lib/helpers/get-site-base-url"
18
19
 
@@ -30,14 +31,16 @@ const CODE_PATTERN = /^[A-Za-z0-9_-]{43}$/
30
31
  export async function GET(request: Request) {
31
32
  const url = new URL(request.url)
32
33
  const locale = resolveLocale(url.searchParams.get("locale"))
33
- const host = hostnameOf(request.headers.get("host") ?? "")
34
+ // A hub client redeems for its own configured host, never the Host header.
35
+ const hubOrigin = ssoHubOrigin()
36
+ const host = hubOrigin ? apexHostname() : hostnameOf(request.headers.get("host") ?? "")
34
37
 
35
38
  // The apex has no tenant to hand off to; an unusable Host never builds an origin.
36
- if (!isBareHostname(host) || host === apexHostname()) {
39
+ if (!isBareHostname(host) || (!hubOrigin && host === apexHostname())) {
37
40
  return NextResponse.redirect(new URL(`/${locale}/login?error=google_auth_failed`, getSiteBaseUrl()))
38
41
  }
39
42
 
40
- const origin = originForHost(host)
43
+ const origin = hubOrigin ? getSiteBaseUrl() : originForHost(host)
41
44
  const secure = isHttpsRequest(request)
42
45
  const nonceCookie = ssoHubNonceCookie(secure)
43
46
  const fail = () => {
@@ -9,10 +9,12 @@ import {
9
9
  originForHost,
10
10
  isHttpsRequest,
11
11
  readCookie,
12
+ registeredReturnOrigin,
12
13
  resolveLocale,
13
14
  sameSecret,
14
15
  SSO_HUB_COOKIE,
15
16
  ssoHubEnabled,
17
+ ssoHubOrigin,
16
18
  } from "../../../lib/helpers/sso-hub"
17
19
 
18
20
  /**
@@ -40,13 +42,23 @@ export async function GET(request: Request) {
40
42
  // missing, tampered or expired one is a failed login: the code could be anyone's (login CSRF). Unset, no cookie is
41
43
  // today's apex flow.
42
44
  const locale = resolveLocale(hub ? hub.locale : url.searchParams.get("locale"))
43
- const tenantOrigin = hub && hub.host !== apexHostname() ? originForHost(hub.host) : null
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
48
+ const revoked = Boolean(hub?.registered) && !registeredOrigin
49
+ const tenantOrigin = hub && !revoked && hub.host !== apexHostname() ? (registeredOrigin ?? originForHost(hub.host)) : null
44
50
  const fail = () =>
45
51
  withHubCookieCleared(
46
52
  NextResponse.redirect(new URL(`/${locale}/login?error=google_auth_failed`, tenantOrigin ?? origin))
47
53
  )
48
54
 
55
+ // A hub client never exchanges a Google code itself: without the hub secret it could not tell whose code this is.
56
+ if (ssoHubOrigin()) {
57
+ if (ssoHubEnabled()) console.error("google-callback: NEXT_PUBLIC_SSO_HUB_ORIGIN and SSO_HUB_SECRET are both set; Google login is refused")
58
+ return fail()
59
+ }
49
60
  if ((rawHub !== undefined || ssoHubEnabled()) && !hub) return fail()
61
+ if (revoked) return fail()
50
62
  if (url.searchParams.get("error")) return fail()
51
63
  // The OAuth state must be the one google-start put in this browser's cookie, or the code is someone else's login.
52
64
  if (hub && !sameSecret(url.searchParams.get("state") ?? "", hub.state)) return fail()
@@ -8,6 +8,7 @@ import {
8
8
  isBareHostname,
9
9
  isHttpsRequest,
10
10
  isNonce,
11
+ registeredReturnOrigin,
11
12
  resolveLocale,
12
13
  sealSsoHubState,
13
14
  SSO_HUB_COOKIE,
@@ -36,15 +37,16 @@ function throttled(request: Request, now = Date.now()): boolean {
36
37
  return entry.count > MAX_STARTS_PER_WINDOW
37
38
  }
38
39
 
39
- /** The primary host of a live tenant (or the apex itself); null for anything else. No open redirect: only this answer ever reaches the cookie. */
40
- async function trustedReturnHost(raw: string): Promise<string | null> {
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
+ async function trustedReturnHost(raw: string): Promise<{ host: string; registered: boolean } | null> {
41
42
  const host = raw.trim().toLowerCase()
42
43
  if (!isBareHostname(host)) return null
43
- if (host === apexHostname()) return host
44
+ if (host === apexHostname()) return { host, registered: false }
45
+ if (registeredReturnOrigin(host)) return { host, registered: true }
44
46
  try {
45
47
  const sdk = await getOpticommSdk()
46
48
  const { primary_host } = await sdk.store.opticomm.retrieveStoreDomainsResolve<{ primary_host: string }>({ host })
47
- return isBareHostname(primary_host) ? primary_host : null
49
+ return isBareHostname(primary_host) ? { host: primary_host, registered: false } : null
48
50
  } catch {
49
51
  return null
50
52
  }
@@ -70,8 +72,9 @@ export async function GET(request: Request) {
70
72
 
71
73
  if (!ssoHubEnabled()) return reject()
72
74
 
73
- const host = await trustedReturnHost(url.searchParams.get("return") ?? "")
74
- if (!host) return reject()
75
+ const trusted = await trustedReturnHost(url.searchParams.get("return") ?? "")
76
+ if (!trusted) return reject()
77
+ const { host, registered } = trusted
75
78
 
76
79
  // Only a tenant handoff is nonce-bound; the apex logs in on this very host.
77
80
  const isApex = host === apexHostname()
@@ -89,7 +92,7 @@ export async function GET(request: Request) {
89
92
  if (!state) return reject()
90
93
 
91
94
  const response = NextResponse.redirect(location)
92
- response.cookies.set(SSO_HUB_COOKIE, sealSsoHubState({ host, locale, nonce, state }), {
95
+ response.cookies.set(SSO_HUB_COOKIE, sealSsoHubState({ host, locale, nonce, state, registered }), {
93
96
  httpOnly: true,
94
97
  sameSite: "lax",
95
98
  secure: isHttpsRequest(request),