@sgflabs/storefront-core 0.1.5 → 0.1.7

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,25 @@ 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 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.
74
+ - The backend `vendor_domains` feature must be on: handoff mint and redeem return 404 without it, so the login fails
75
+ after Google.
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.
77
+ - On the consuming app set `NEXT_PUBLIC_SSO_HUB_ORIGIN=<apex origin>` (build time and runtime). Do NOT set
78
+ `SSO_HUB_SECRET` there. The app's `google-callback` refuses to exchange a code when this
79
+ variable is set.
80
+ - Re-export `auth/handoff` only: never `google-start`, and delete any `google-callback` re-export.
81
+ - Mount `<TenantHostProvider isTenantHost={false} googleSsoOrigin={ssoHubOrigin()}>`.
82
+ - `NEXT_PUBLIC_BASE_URL` must be the exact public https origin of the app, and its proxy must send
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
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.5",
3
+ "version": "0.1.7",
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.7",
59
+ "@sgflabs/page-spec": "^0.1.7",
60
+ "@sgflabs/storefront-core-common": "^0.1.7",
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.7",
77
+ "@sgflabs/page-spec": "^0.1.7",
78
+ "@sgflabs/storefront-core-common": "^0.1.7",
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 the backend sso-origin lookup (an admin-enabled publishable key); 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,104 @@ 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
+ const SSO_ORIGIN_TTL_MS = 30_000
107
+ const SSO_ORIGIN_NEGATIVE_TTL_MS = 10_000
108
+ // 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).
109
+ const SSO_ORIGIN_STALE_WINDOW_MS = 300_000
110
+ const SSO_ORIGIN_CACHE_MAX = 500
111
+ // Backstop on cold lookups per instance per minute, so random hosts cannot turn this app into an unbounded backend load.
112
+ const SSO_ORIGIN_MAX_COLD_FETCHES_PER_MINUTE = 1000
113
+ const SSO_ORIGIN_BUDGET_WINDOW_MS = 60_000
114
+ // Positives and negatives live apart: junk misses can only evict other junk, never a confirmed host.
115
+ const ssoOriginHits = new Map<string, { origin: string; expiresAt: number }>()
116
+ const ssoOriginMisses = new Map<string, number>()
117
+ let coldBudget = { count: 0, resetAt: 0 }
118
+
119
+ export const clearSsoOriginCache = () => {
120
+ ssoOriginHits.clear()
121
+ ssoOriginMisses.clear()
122
+ coldBudget = { count: 0, resetAt: 0 }
123
+ }
124
+
125
+ const remember = <V>(map: Map<string, V>, host: string, value: V) => {
126
+ map.delete(host)
127
+ map.set(host, value)
128
+ if (map.size > SSO_ORIGIN_CACHE_MAX) map.delete(map.keys().next().value as string)
129
+ }
130
+
131
+ /**
132
+ * The return origin the backend permits for exactly this host, or null. `fetchOrigin` is the backend lookup: it
133
+ * resolves an origin, or throws (a 404 error means "not enabled"; anything else is an outage). Fails closed: an
134
+ * error, a malformed origin or an origin on another hostname is null. Hits live 30 s and misses 10 s so one login
135
+ * does not ask twice; errors are never cached. ponytail: per-instance caches and cold-lookup budget, all bounded; a
136
+ * revoked flag stops within 30 s. A hit moves its entry to the end (LRU-ish). Only a cold host (no confirmation in the
137
+ * last 5 minutes) is charged to the per-minute budget and is refused (null) above it without asking the backend; a
138
+ * known host, even past its TTL, is always re-checked at the backend, so revocation is honoured and junk cannot lock it out.
139
+ */
140
+ export async function ssoOriginForHost(
141
+ host: string,
142
+ fetchOrigin: (host: string) => Promise<string>,
143
+ now = Date.now()
144
+ ): Promise<string | null> {
145
+ if (!isBareHostname(host) || host === apexHostname()) return null
146
+ const hit = ssoOriginHits.get(host)
147
+ if (hit && hit.expiresAt > now) {
148
+ remember(ssoOriginHits, host, hit)
149
+ return hit.origin
150
+ }
151
+ const missUntil = ssoOriginMisses.get(host)
152
+ if (missUntil !== undefined && missUntil > now) {
153
+ remember(ssoOriginMisses, host, missUntil)
154
+ return null
155
+ }
156
+ const known = hit !== undefined && hit.expiresAt + SSO_ORIGIN_STALE_WINDOW_MS > now
157
+ if (!known) {
158
+ if (coldBudget.resetAt <= now) coldBudget = { count: 0, resetAt: now + SSO_ORIGIN_BUDGET_WINDOW_MS }
159
+ if (++coldBudget.count > SSO_ORIGIN_MAX_COLD_FETCHES_PER_MINUTE) return null
160
+ }
161
+ try {
162
+ const raw = await fetchOrigin(host)
163
+ const url = bareOrigin(raw)
164
+ if (url && schemeAllowed(url) && url.hostname === host) {
165
+ ssoOriginMisses.delete(host)
166
+ remember(ssoOriginHits, host, { origin: raw, expiresAt: now + SSO_ORIGIN_TTL_MS })
167
+ return raw
168
+ }
169
+ } catch (error) {
170
+ const status = (error as { status?: unknown } | null)?.status
171
+ if (status !== 404) {
172
+ // Status only: neither the host nor the error text is logged.
173
+ console.warn(`sso-origin lookup failed (status ${typeof status === "number" ? status : "none"}); failing closed`)
174
+ return null
175
+ }
176
+ }
177
+ ssoOriginHits.delete(host)
178
+ remember(ssoOriginMisses, host, now + SSO_ORIGIN_NEGATIVE_TTL_MS)
179
+ return null
180
+ }
181
+
182
+ /** 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. */
183
+ export function ssoHubOrigin(): string | null {
184
+ const value = process.env.NEXT_PUBLIC_SSO_HUB_ORIGIN
185
+ if (!value) return null
186
+ const url = bareOrigin(value)
187
+ return url && schemeAllowed(url) && url.hostname !== apexHostname() ? value : null
188
+ }
189
+
89
190
  export function readCookie(request: Request, name: string): string | undefined {
90
191
  for (const part of (request.headers.get("cookie") ?? "").split(";")) {
91
192
  const index = part.indexOf("=")
@@ -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
+ })
@@ -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 = () => {
@@ -1,6 +1,7 @@
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 { lookupSsoOrigin } from "../../../lib/helpers/sso-origin-lookup"
4
5
  import { getSiteBaseUrl } from "../../../lib/helpers/get-site-base-url"
5
6
  import {
6
7
  apexHostname,
@@ -13,6 +14,7 @@ import {
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: un-flagging it in
46
+ // the backend must stop in-flight handoffs, not fall back to the tenant path.
47
+ const registeredOrigin = hub?.registered ? await lookupSsoOrigin(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()
@@ -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 { lookupSsoOrigin } from "../../../lib/helpers/sso-origin-lookup"
5
6
  import { forwardedVisitorIp } from "../../../lib/helpers/visitor-ip"
6
7
  import {
7
8
  apexHostname,
@@ -36,18 +37,21 @@ 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 the backend SSO-origin lookup; 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
+ // Resolver first on purpose: a host that is both a live tenant and an SSO-flagged origin stays a tenant (the
46
+ // flag only adds hosts the resolver does not know), so enabling the flag never changes how an existing tenant logs in.
44
47
  try {
45
48
  const sdk = await getOpticommSdk()
46
49
  const { primary_host } = await sdk.store.opticomm.retrieveStoreDomainsResolve<{ primary_host: string }>({ host })
47
- return isBareHostname(primary_host) ? primary_host : null
50
+ if (isBareHostname(primary_host)) return { host: primary_host, registered: false }
48
51
  } catch {
49
- return null
52
+ // Not a live tenant (or the resolver is down): fall through to the SSO-origin lookup, which fails closed.
50
53
  }
54
+ return (await lookupSsoOrigin(host)) ? { host, registered: true } : null
51
55
  }
52
56
 
53
57
  /**
@@ -70,8 +74,9 @@ export async function GET(request: Request) {
70
74
 
71
75
  if (!ssoHubEnabled()) return reject()
72
76
 
73
- const host = await trustedReturnHost(url.searchParams.get("return") ?? "")
74
- if (!host) return reject()
77
+ const trusted = await trustedReturnHost(url.searchParams.get("return") ?? "")
78
+ if (!trusted) return reject()
79
+ const { host, registered } = trusted
75
80
 
76
81
  // Only a tenant handoff is nonce-bound; the apex logs in on this very host.
77
82
  const isApex = host === apexHostname()
@@ -89,7 +94,7 @@ export async function GET(request: Request) {
89
94
  if (!state) return reject()
90
95
 
91
96
  const response = NextResponse.redirect(location)
92
- response.cookies.set(SSO_HUB_COOKIE, sealSsoHubState({ host, locale, nonce, state }), {
97
+ response.cookies.set(SSO_HUB_COOKIE, sealSsoHubState({ host, locale, nonce, state, registered }), {
93
98
  httpOnly: true,
94
99
  sameSite: "lax",
95
100
  secure: isHttpsRequest(request),