@usequeek/theme-kit 0.1.37 → 0.1.39
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 +2 -1
- package/package.json +1 -1
- package/sdk/server-store-client.ts +43 -8
- package/sdk/storefront-proxy-auth.ts +55 -0
- package/utils/vendor-host.ts +242 -17
package/README.md
CHANGED
|
@@ -250,7 +250,8 @@ Themes set none of these; the storefront host does.
|
|
|
250
250
|
| --- | --- |
|
|
251
251
|
| `QUEEK_API_URL` (or `NEXT_PUBLIC_QUEEK_API_URL`) | Origin of the Queek API for server-side reads. Without it the kit falls back to `http://127.0.0.1:8000/api/v1` and warns once in production builds. |
|
|
252
252
|
| `NEXT_PUBLIC_QUEEK_AUTH_URL` | Origin of the sign-in service (default `https://auth.usequeek.com`). |
|
|
253
|
-
| `STOREFRONT_DOMAIN` |
|
|
253
|
+
| `STOREFRONT_DOMAIN` | The primary store domain: stores live at `{slug}.<domain>` and the URLs the storefront emits use it (default `queek.com.ng`). |
|
|
254
|
+
| `STOREFRONT_LEGACY_DOMAINS` | Comma list of former store domains that still resolve a store (e.g. `queek.com.ng` after a move). The host app redirects them to the primary domain; the kit names the primary one in canonical URLs. Unset = none. |
|
|
254
255
|
| `CUSTOM_DOMAIN_VENDOR_MAP` | JSON object mapping a custom domain to a store slug. |
|
|
255
256
|
|
|
256
257
|
Browser requests are always same-origin (`/api/v1/client/*`), so the host needs
|
package/package.json
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { cookies, headers } from 'next/headers';
|
|
2
|
-
import { resolveCustomDomainVendorSlug, resolveCustomDomainVendorSlugRemote, resolveSubdomainVendorSlug } from '../utils/vendor-host';
|
|
2
|
+
import { resolveCustomDomainVendorSlug, resolveCustomDomainVendorSlugRemote, resolveSubdomainVendorSlug, toPrimaryStoreHost } from '../utils/vendor-host';
|
|
3
3
|
import { LOCALE_CODE_HEADER, parseLocaleCode, withLocaleQuery, withLocaleTags } from '../utils/locale';
|
|
4
4
|
import { isMarketPricedPath, readMarketFromCookieString, withMarketQuery } from '../utils/market';
|
|
5
5
|
import { API_BASE_URL, request, type RequestCachePolicy, type RequestOptions } from './client';
|
|
6
6
|
import { getActivePlatform } from './platform';
|
|
7
|
+
import { readProxySecret, storefrontProxyHeaders } from './storefront-proxy-auth';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Origin of the incoming storefront request, forwarded to the API so it
|
|
@@ -28,6 +29,9 @@ export async function getRequestOrigin(): Promise<string | undefined> {
|
|
|
28
29
|
* storefronts serve at the bare origin; path-based access serves under
|
|
29
30
|
* `/vendor-slug`). Every canonical URL, sitemap entry, and JSON-LD `url` field
|
|
30
31
|
* must derive from this instead of re-deriving `basePath` inline.
|
|
32
|
+
*
|
|
33
|
+
* The host is the request's, except that a legacy store domain is named by the
|
|
34
|
+
* primary one (see `STOREFRONT_LEGACY_DOMAINS`).
|
|
31
35
|
*/
|
|
32
36
|
export async function resolveStoreBaseUrl(vendor: string): Promise<string | null> {
|
|
33
37
|
const origin = await getRequestOrigin();
|
|
@@ -42,7 +46,11 @@ export async function resolveStoreBaseUrl(vendor: string): Promise<string | null
|
|
|
42
46
|
);
|
|
43
47
|
const basePath = isSubdomain ? '' : `/${vendor}`;
|
|
44
48
|
|
|
45
|
-
|
|
49
|
+
// A store reached on a legacy store domain (`STOREFRONT_LEGACY_DOMAINS`) is still
|
|
50
|
+
// addressed by the primary one: the URL we emit must be the one to index and share.
|
|
51
|
+
const canonicalOrigin = origin.replace(/^([a-z][a-z0-9+.-]*:\/\/)(.+)$/i, (_match, scheme: string, authority: string) => `${scheme}${toPrimaryStoreHost(authority)}`);
|
|
52
|
+
|
|
53
|
+
return `${canonicalOrigin}${basePath}`;
|
|
46
54
|
}
|
|
47
55
|
|
|
48
56
|
/**
|
|
@@ -216,6 +224,30 @@ export async function readRequestMarket(vendorSlug: string, verify?: (marketId:
|
|
|
216
224
|
}
|
|
217
225
|
}
|
|
218
226
|
|
|
227
|
+
/**
|
|
228
|
+
* The S8-B headers for one server-side API call (see `./storefront-proxy-auth`).
|
|
229
|
+
*
|
|
230
|
+
* `cached: true` — the read goes through Next's data cache (`next.revalidate`): the secret only, never the
|
|
231
|
+
* shopper (the cache key includes request headers). `cached: false` — a `no-store` call: the secret plus the
|
|
232
|
+
* incoming request's `cf-connecting-ip` when it has one. No secret configured: `{}`.
|
|
233
|
+
*
|
|
234
|
+
* Reads `headers()` on the uncached path, so call it OUTSIDE a Next cache scope, like `getRequestOrigin`. Outside
|
|
235
|
+
* a request (build, tests) it quietly sends the secret alone.
|
|
236
|
+
*/
|
|
237
|
+
export async function getStorefrontApiHeaders(options: { cached: boolean }): Promise<Record<string, string>> {
|
|
238
|
+
if (options.cached) return storefrontProxyHeaders();
|
|
239
|
+
if (!readProxySecret()) return {};
|
|
240
|
+
|
|
241
|
+
let shopperIp: string | null = null;
|
|
242
|
+
try {
|
|
243
|
+
shopperIp = (await headers()).get('cf-connecting-ip');
|
|
244
|
+
} catch {
|
|
245
|
+
shopperIp = null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return storefrontProxyHeaders({ shopperIp });
|
|
249
|
+
}
|
|
250
|
+
|
|
219
251
|
/** Options of {@link createServerStoreClient}. */
|
|
220
252
|
export interface ServerStoreClientOptions {
|
|
221
253
|
/**
|
|
@@ -252,25 +284,28 @@ export function createServerStoreClient(vendorSlug: string, origin?: string, opt
|
|
|
252
284
|
// leave the shared data cache. The cache is shared by every visitor, its key is the URL, and a rate moves
|
|
253
285
|
// without any revalidation tag, so a market price is never stored there. No market: today's request.
|
|
254
286
|
const marketId = isMarketPricedPath(path) ? await readRequestMarket(vendorSlug, options.verifyMarket) : null;
|
|
287
|
+
const cachePolicy =
|
|
288
|
+
marketId !== null || (await isPreviewRender())
|
|
289
|
+
? null
|
|
290
|
+
: withLocaleCachePolicy(resolveCachePolicy(vendorSlug, path, query), code);
|
|
255
291
|
return request<T>(
|
|
256
292
|
API_BASE_URL,
|
|
257
293
|
`/client/store${path}`,
|
|
258
294
|
{
|
|
259
295
|
query: withMarketQuery(withLocaleQuery(query, code), marketId),
|
|
260
296
|
timeoutMs: SSR_TIMEOUT_MS,
|
|
261
|
-
cachePolicy
|
|
262
|
-
? null
|
|
263
|
-
: withLocaleCachePolicy(resolveCachePolicy(vendorSlug, path, query), code),
|
|
297
|
+
cachePolicy,
|
|
264
298
|
},
|
|
265
|
-
|
|
299
|
+
// A cached read carries only the secret; an uncached one also names the shopper.
|
|
300
|
+
{ ...buildHeaders(), ...(await getStorefrontApiHeaders({ cached: !!cachePolicy })) },
|
|
266
301
|
);
|
|
267
302
|
},
|
|
268
|
-
post: <T>(path: string, body?: unknown) =>
|
|
303
|
+
post: async <T>(path: string, body?: unknown) =>
|
|
269
304
|
request<T>(API_BASE_URL, `/client/store${path}`, {
|
|
270
305
|
method: 'POST',
|
|
271
306
|
body: body ? JSON.stringify(body) : undefined,
|
|
272
307
|
timeoutMs: SSR_TIMEOUT_MS,
|
|
273
308
|
cachePolicy: null,
|
|
274
|
-
}, buildHeaders()),
|
|
309
|
+
}, { ...buildHeaders(), ...(await getStorefrontApiHeaders({ cached: false })) }),
|
|
275
310
|
};
|
|
276
311
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two headers a storefront SERVER sends the Queek API so the API can tell its own storefront from a
|
|
3
|
+
* shopper, and which shopper a request belongs to (S8-B). Server-only: the secret is a plain env var that
|
|
4
|
+
* never reaches a browser bundle, and this module returns nothing when it runs in one.
|
|
5
|
+
*
|
|
6
|
+
* - `X-Storefront-Proxy-Secret`: the shared secret (`STOREFRONT_PROXY_SECRET`, the same value as on the API).
|
|
7
|
+
* With it the API trusts the next header; without it both are ignored.
|
|
8
|
+
* - `X-Shopper-IP`: the shopper's public address, so the API's per-address limits count that shopper and not
|
|
9
|
+
* this server. Sent only when the caller has a real one (Cloudflare's `cf-connecting-ip`); never guessed from
|
|
10
|
+
* `x-forwarded-for` or `x-real-ip`, and never empty or malformed (the API logs a warning for those).
|
|
11
|
+
*
|
|
12
|
+
* `STOREFRONT_PROXY_SECRET` empty or unset: nothing is sent, which is exactly how the storefront behaved before.
|
|
13
|
+
*
|
|
14
|
+
* Pure on purpose (no `next/headers`): the host app's proxy runs here too and reads `cf-connecting-ip` from its
|
|
15
|
+
* own request. Reads that sit in Next's data cache must pass NO shopper: the cache key includes the request
|
|
16
|
+
* headers, so a per-shopper header would give every visitor their own entry. The secret is one constant value
|
|
17
|
+
* and does not split it.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const PROXY_SECRET_HEADER = 'X-Storefront-Proxy-Secret';
|
|
21
|
+
export const SHOPPER_IP_HEADER = 'X-Shopper-IP';
|
|
22
|
+
|
|
23
|
+
/** The configured secret, or null when unset/blank (and always null in a browser). */
|
|
24
|
+
export function readProxySecret(): string | null {
|
|
25
|
+
if (typeof window !== 'undefined') return null;
|
|
26
|
+
const secret = process.env.STOREFRONT_PROXY_SECRET?.trim();
|
|
27
|
+
|
|
28
|
+
return secret ? secret : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* `value` as a shopper address worth sending, else null. A cheap shape check only (hex digits, `.` and `:`, one of
|
|
33
|
+
* the last two present, at most 45 characters, the longest IPv6 text form): the API validates for real, and ignores
|
|
34
|
+
* a private or reserved address.
|
|
35
|
+
*/
|
|
36
|
+
export function usableShopperIp(value: string | null | undefined): string | null {
|
|
37
|
+
const ip = value?.trim();
|
|
38
|
+
if (!ip || ip.length > 45) return null;
|
|
39
|
+
if (!/^[0-9a-fA-F:.]+$/.test(ip) || !/[.:]/.test(ip)) return null;
|
|
40
|
+
|
|
41
|
+
return ip;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The headers to add to one API call: `{}` without a secret, the secret alone, or the secret plus the shopper.
|
|
46
|
+
* Pass `shopperIp` only for a call that is NOT in Next's data cache.
|
|
47
|
+
*/
|
|
48
|
+
export function storefrontProxyHeaders(options: { shopperIp?: string | null } = {}): Record<string, string> {
|
|
49
|
+
const secret = readProxySecret();
|
|
50
|
+
if (!secret) return {};
|
|
51
|
+
|
|
52
|
+
const shopper = usableShopperIp(options.shopperIp);
|
|
53
|
+
|
|
54
|
+
return shopper ? { [PROXY_SECRET_HEADER]: secret, [SHOPPER_IP_HEADER]: shopper } : { [PROXY_SECRET_HEADER]: secret };
|
|
55
|
+
}
|
package/utils/vendor-host.ts
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
* server fetchers and a host app's proxy can both import it.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
import { storefrontProxyHeaders } from '../sdk/storefront-proxy-auth';
|
|
9
|
+
|
|
8
10
|
// Mirrors the API's reserved store slugs. Keep in sync.
|
|
9
11
|
// These are subdomains the storefront proxy must NOT treat as vendor slugs.
|
|
10
12
|
export const RESERVED_VENDOR_SLUGS = new Set([
|
|
@@ -44,9 +46,98 @@ export function shouldBypassVendorProxy(pathname: string): boolean {
|
|
|
44
46
|
return pathname.startsWith('/_next') || pathname.startsWith('/api') || pathname.includes('.');
|
|
45
47
|
}
|
|
46
48
|
|
|
49
|
+
/** The store domain an unset `STOREFRONT_DOMAIN` has always meant. */
|
|
50
|
+
export const DEFAULT_STOREFRONT_DOMAIN = 'queek.com.ng';
|
|
51
|
+
|
|
52
|
+
const HOST_LABEL = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
53
|
+
const DOMAIN_FORMAT = /^[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)+$/;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The primary store domain: stores live at `{slug}.<this>` and every URL the
|
|
57
|
+
* storefront emits uses it. `STOREFRONT_DOMAIN`, else `queek.com.ng` — an unset
|
|
58
|
+
* env keeps today's behaviour exactly.
|
|
59
|
+
*/
|
|
60
|
+
export function getStorefrontDomain(): string {
|
|
61
|
+
const configured = process.env.STOREFRONT_DOMAIN?.trim().toLowerCase().replace(/^\.+|\.+$/g, '');
|
|
62
|
+
|
|
63
|
+
return configured || DEFAULT_STOREFRONT_DOMAIN;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Store domains that still RESOLVE a store but are no longer the address:
|
|
68
|
+
* `STOREFRONT_LEGACY_DOMAINS`, a comma list (`queek.com.ng`). Empty when unset,
|
|
69
|
+
* so nothing is a legacy host until the new domain is switched on. The primary
|
|
70
|
+
* domain, duplicates and anything that is not a bare hostname are dropped.
|
|
71
|
+
*/
|
|
72
|
+
export function getLegacyStorefrontDomains(): string[] {
|
|
73
|
+
const raw = process.env.STOREFRONT_LEGACY_DOMAINS;
|
|
74
|
+
if (!raw) return [];
|
|
75
|
+
|
|
76
|
+
const primary = getStorefrontDomain();
|
|
77
|
+
const domains = new Set<string>();
|
|
78
|
+
for (const entry of raw.split(',')) {
|
|
79
|
+
const domain = entry.trim().toLowerCase().replace(/^\*?\.+|\.+$/g, '');
|
|
80
|
+
if (domain !== primary && DOMAIN_FORMAT.test(domain)) domains.add(domain);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return [...domains];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Primary first, then the legacy domains: every suffix a store host may end in. */
|
|
87
|
+
export function getStoreDomains(): string[] {
|
|
88
|
+
return [getStorefrontDomain(), ...getLegacyStorefrontDomains()];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The suffixes (with the leading dot) a hostname is matched against; `.localhost` is the dev host. */
|
|
92
|
+
function storeHostSuffixes(): string[] {
|
|
93
|
+
return [...getStoreDomains().map((domain) => `.${domain}`), '.localhost'];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The one label in front of a legacy domain, when `hostname` is `<label>.<legacy domain>`. */
|
|
97
|
+
function legacyHostLabel(hostname: string): string | null {
|
|
98
|
+
const host = hostname.toLowerCase();
|
|
99
|
+
for (const domain of getLegacyStorefrontDomains()) {
|
|
100
|
+
const suffix = `.${domain}`;
|
|
101
|
+
if (!host.endsWith(suffix)) continue;
|
|
102
|
+
|
|
103
|
+
const label = host.slice(0, -suffix.length);
|
|
104
|
+
|
|
105
|
+
return HOST_LABEL.test(label) ? label : null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Where a request for `{label}.<legacy domain>` belongs: the same label on the
|
|
113
|
+
* primary store domain (`acme.queek.com.ng` → `acme.queek.app`), or `null` when
|
|
114
|
+
* the host is not on a legacy domain (the primary domain, a custom domain,
|
|
115
|
+
* `localhost`, a bare apex, anything else) — so there is never a loop, and with
|
|
116
|
+
* `STOREFRONT_LEGACY_DOMAINS` unset there is never a redirect.
|
|
117
|
+
*
|
|
118
|
+
* It is every single label, not only store slugs: `preview.`, `themes.` and the
|
|
119
|
+
* reserved names move with their domain, so a link to any of them keeps working.
|
|
120
|
+
*/
|
|
121
|
+
export function legacyHostRedirectTarget(hostname: string): string | null {
|
|
122
|
+
const label = legacyHostLabel(hostname);
|
|
123
|
+
|
|
124
|
+
return label === null ? null : `${label}.${getStorefrontDomain()}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Re-points a URL's host from a legacy store domain to the primary one, so what
|
|
129
|
+
* the storefront emits (canonical, sitemap, OG, JSON-LD) never names the old
|
|
130
|
+
* address. A URL on any other host is returned unchanged.
|
|
131
|
+
*/
|
|
132
|
+
export function toPrimaryStoreHost(host: string): string {
|
|
133
|
+
const [hostname, ...port] = host.split(':');
|
|
134
|
+
const target = legacyHostRedirectTarget(hostname);
|
|
135
|
+
|
|
136
|
+
return target === null ? host : [target, ...port].join(':');
|
|
137
|
+
}
|
|
138
|
+
|
|
47
139
|
export function resolveSubdomainVendorSlug(hostname: string): string | null {
|
|
48
|
-
const
|
|
49
|
-
const domains = [`.${storefrontDomain}`, '.localhost'];
|
|
140
|
+
const domains = storeHostSuffixes();
|
|
50
141
|
|
|
51
142
|
const matchedDomain = domains.find((d) => hostname.endsWith(d));
|
|
52
143
|
if (!matchedDomain) {
|
|
@@ -78,16 +169,64 @@ export function resolveCustomDomainVendorSlug(hostname: string): string | null {
|
|
|
78
169
|
}
|
|
79
170
|
}
|
|
80
171
|
|
|
81
|
-
|
|
172
|
+
/**
|
|
173
|
+
* What `resolve-by-host` said about a host. Three answers, never two:
|
|
174
|
+
*
|
|
175
|
+
* - `store` a store lives on this host (`slug`);
|
|
176
|
+
* - `not-store` DEFINITELY no store: the API answered 200, `status: 'success'` and `data.slug: null`;
|
|
177
|
+
* - `unknown` the API did not answer usefully: 404 (the API never sends one for a host), 429, 5xx, any
|
|
178
|
+
* other status, a timeout, a
|
|
179
|
+
* network error, an unreadable body, no API URL configured.
|
|
180
|
+
*
|
|
181
|
+
* Only `not-store` may become a 404 for the visitor. `unknown` is an outage, not an answer, and
|
|
182
|
+
* must fail open (render as before) and never be remembered.
|
|
183
|
+
*/
|
|
184
|
+
export type HostLookup =
|
|
185
|
+
| { kind: 'store'; slug: string }
|
|
186
|
+
| { kind: 'not-store' }
|
|
187
|
+
| {
|
|
188
|
+
kind: 'unknown';
|
|
189
|
+
/**
|
|
190
|
+
* Set only when the API answered 429: this caller's own budget (or the server's) is spent. `retryAfterSeconds`
|
|
191
|
+
* is the API's `Retry-After`, or null when it sent none or an unreadable one. Still `unknown` for every
|
|
192
|
+
* purpose that treats an outage as one; it is here so a host app can tell a 429 from other outages, e.g. to
|
|
193
|
+
* retry once as itself (without a shopper address) when the shopper's own budget is what ran out.
|
|
194
|
+
*/
|
|
195
|
+
rateLimited?: { retryAfterSeconds: number | null };
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
export interface LookupStoreByHostOptions {
|
|
199
|
+
/**
|
|
200
|
+
* `'no-store'` keeps Next's Data Cache out of this call (no `next.revalidate`, no tags), for a caller that
|
|
201
|
+
* does its own caching and must see a fresh answer when its own entry expires (the host app's proxy).
|
|
202
|
+
* Omitted: the fetch is revalidated every 5 minutes and tagged `host:<hostname>`, as it always was.
|
|
203
|
+
*/
|
|
204
|
+
cache?: 'no-store';
|
|
205
|
+
/**
|
|
206
|
+
* The shopper this lookup is made for (the request's `cf-connecting-ip`), sent as `X-Shopper-IP` so a scanner
|
|
207
|
+
* rotating random hosts spends its own per-address budget, not the storefront server's. Only used with
|
|
208
|
+
* `cache: 'no-store'`: a cached read must not carry a per-shopper header (it would split the data cache).
|
|
209
|
+
*/
|
|
210
|
+
shopperIp?: string | null;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Asks `resolve-by-host` about one host and reports which of the three answers came back. Never throws.
|
|
215
|
+
*
|
|
216
|
+
* The API ALWAYS answers a known or unknown host with 200 `{ status: 'success', data: { slug: <slug|null> } }`.
|
|
217
|
+
* So `not-store` is exactly that: HTTP 200, `status === 'success'`, `data.slug === null`. A 404 (a wrong API URL,
|
|
218
|
+
* a gateway answering during a deploy) or anything else off-contract is `unknown`.
|
|
219
|
+
*/
|
|
220
|
+
export async function lookupStoreByHost(hostname: string, options: LookupStoreByHostOptions = {}): Promise<HostLookup> {
|
|
82
221
|
if (!hostname) {
|
|
83
|
-
return
|
|
222
|
+
return { kind: 'unknown' };
|
|
84
223
|
}
|
|
85
224
|
|
|
86
225
|
// Middleware runs server-side — prefer the server-only absolute URL. The
|
|
87
226
|
// public var can be a same-origin relative path, which `fetch()` can't resolve without a document origin here.
|
|
88
227
|
const baseUrl = process.env.QUEEK_API_URL ?? process.env.NEXT_PUBLIC_QUEEK_API_URL;
|
|
89
228
|
if (!baseUrl) {
|
|
90
|
-
return
|
|
229
|
+
return { kind: 'unknown' };
|
|
91
230
|
}
|
|
92
231
|
|
|
93
232
|
const url = `${baseUrl.replace(/\/+$/, '')}/client/resolve-by-host?host=${encodeURIComponent(hostname)}`;
|
|
@@ -97,31 +236,54 @@ export async function resolveCustomDomainVendorSlugRemote(hostname: string): Pro
|
|
|
97
236
|
try {
|
|
98
237
|
const response = await fetch(url, {
|
|
99
238
|
method: 'GET',
|
|
100
|
-
|
|
239
|
+
// The S8-B secret rides every lookup (when configured); the shopper only the uncached one.
|
|
240
|
+
headers: { Accept: 'application/json', ...storefrontProxyHeaders(options.cache === 'no-store' ? { shopperIp: options.shopperIp } : {}) },
|
|
101
241
|
signal: controller.signal,
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
tags: [`host:${hostname}`],
|
|
105
|
-
},
|
|
242
|
+
...(options.cache === 'no-store'
|
|
243
|
+
? { cache: 'no-store' as const }
|
|
244
|
+
: { next: { revalidate: REMOTE_RESOLVE_REVALIDATE_SECONDS, tags: [`host:${hostname}`] } }),
|
|
106
245
|
});
|
|
107
246
|
|
|
108
247
|
if (!response.ok) {
|
|
109
248
|
logRemoteFailure(`status ${response.status}`);
|
|
110
|
-
|
|
249
|
+
if (response.status === 429) {
|
|
250
|
+
const raw = response.headers.get('retry-after');
|
|
251
|
+
const seconds = raw === null || raw.trim() === '' ? NaN : Number(raw);
|
|
252
|
+
return { kind: 'unknown', rateLimited: { retryAfterSeconds: Number.isFinite(seconds) && seconds >= 0 ? Math.ceil(seconds) : null } };
|
|
253
|
+
}
|
|
254
|
+
return { kind: 'unknown' };
|
|
111
255
|
}
|
|
112
256
|
|
|
113
|
-
const payload = (await response.json()) as { data?: { slug?: unknown } };
|
|
114
|
-
const
|
|
257
|
+
const payload = (await response.json()) as { status?: unknown; data?: { slug?: unknown } } | null;
|
|
258
|
+
const data = payload?.data;
|
|
259
|
+
if (!data || typeof data !== 'object' || !('slug' in data)) {
|
|
260
|
+
// 200 without the field the API always sends (a CDN or captive page in front of it):
|
|
261
|
+
// not an answer about this host.
|
|
262
|
+
logRemoteFailure('unexpected body');
|
|
263
|
+
return { kind: 'unknown' };
|
|
264
|
+
}
|
|
115
265
|
|
|
116
|
-
|
|
266
|
+
const { slug } = data;
|
|
267
|
+
if (typeof slug === 'string' && slug !== '') {
|
|
268
|
+
return { kind: 'store', slug };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// The one definite "no": the API's own success envelope carrying a null slug.
|
|
272
|
+
return slug === null && payload?.status === 'success' ? { kind: 'not-store' } : { kind: 'unknown' };
|
|
117
273
|
} catch (error) {
|
|
118
274
|
logRemoteFailure(error instanceof Error ? error.message : 'unknown');
|
|
119
|
-
return
|
|
275
|
+
return { kind: 'unknown' };
|
|
120
276
|
} finally {
|
|
121
277
|
clearTimeout(timeoutId);
|
|
122
278
|
}
|
|
123
279
|
}
|
|
124
280
|
|
|
281
|
+
export async function resolveCustomDomainVendorSlugRemote(hostname: string): Promise<string | null> {
|
|
282
|
+
const lookup = await lookupStoreByHost(hostname);
|
|
283
|
+
|
|
284
|
+
return lookup.kind === 'store' ? lookup.slug : null;
|
|
285
|
+
}
|
|
286
|
+
|
|
125
287
|
function logRemoteFailure(reason: string): void {
|
|
126
288
|
const now = Date.now();
|
|
127
289
|
if (now - lastRemoteFailureLoggedAt < REMOTE_FAILURE_LOG_WINDOW_MS) {
|
|
@@ -132,8 +294,7 @@ function logRemoteFailure(reason: string): void {
|
|
|
132
294
|
}
|
|
133
295
|
|
|
134
296
|
export function isPreviewSubdomain(hostname: string): boolean {
|
|
135
|
-
const
|
|
136
|
-
const domains = [`.${storefrontDomain}`, '.localhost'];
|
|
297
|
+
const domains = storeHostSuffixes();
|
|
137
298
|
|
|
138
299
|
return domains.some((d) => {
|
|
139
300
|
if (!hostname.endsWith(d)) return false;
|
|
@@ -166,3 +327,67 @@ export async function resolveVendorSlug(options: {
|
|
|
166
327
|
|
|
167
328
|
return options.searchVendor;
|
|
168
329
|
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* The host without its port or one trailing root dot (`acme.queek.app.:443` is `acme.queek.app`: a fully
|
|
333
|
+
* qualified name is the same host); keeps a bracketed IPv6 literal whole (`[::1]:3001` → `[::1]`).
|
|
334
|
+
*/
|
|
335
|
+
function hostnameOf(host: string | null): string {
|
|
336
|
+
return (host ?? '').trim().toLowerCase().replace(/:\d+$/, '').replace(/\.$/, '');
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export interface VendorHostResolution {
|
|
340
|
+
/**
|
|
341
|
+
* The store this request is for, or null. Set from the host when the lookup says `store`; from the
|
|
342
|
+
* subdomain label while the lookup is `unknown` (fail open, as before); from `?vendor=` otherwise.
|
|
343
|
+
*/
|
|
344
|
+
slug: string | null;
|
|
345
|
+
/**
|
|
346
|
+
* What the host lookup concluded. `not-store` is a definite answer; `unknown` covers an outage AND
|
|
347
|
+
* every case where no lookup was made (no host, no API URL).
|
|
348
|
+
*/
|
|
349
|
+
outcome: HostLookup['kind'];
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* `resolveVendorSlug`, but it says WHY there is no slug — so the host app can answer 404 for a host
|
|
354
|
+
* that is definitely not a store without ever mistaking an outage for one — and it checks that a
|
|
355
|
+
* subdomain store actually exists (the older function trusts any `{label}.<store domain>`).
|
|
356
|
+
*
|
|
357
|
+
* `lookup` replaces the API call; a host app passes a cached one. It must behave like
|
|
358
|
+
* `lookupStoreByHost`: never throw, `unknown` for anything that is not a definite answer.
|
|
359
|
+
*
|
|
360
|
+
* Order, as in `resolveVendorSlug`: subdomain, static custom-domain map, remote lookup, `?vendor=`.
|
|
361
|
+
*/
|
|
362
|
+
export async function resolveVendorHost(options: {
|
|
363
|
+
host: string | null;
|
|
364
|
+
searchVendor: string | null;
|
|
365
|
+
lookup?: (hostname: string) => Promise<HostLookup>;
|
|
366
|
+
}): Promise<VendorHostResolution> {
|
|
367
|
+
const hostname = hostnameOf(options.host);
|
|
368
|
+
const lookup = options.lookup ?? lookupStoreByHost;
|
|
369
|
+
const subdomainSlug = resolveSubdomainVendorSlug(hostname);
|
|
370
|
+
|
|
371
|
+
if (subdomainSlug) {
|
|
372
|
+
const found = await lookup(hostname);
|
|
373
|
+
if (found.kind === 'store') return { slug: found.slug, outcome: 'store' };
|
|
374
|
+
// Unknown: the label is trusted, exactly as before the check existed.
|
|
375
|
+
if (found.kind === 'unknown') return { slug: subdomainSlug, outcome: 'unknown' };
|
|
376
|
+
|
|
377
|
+
return { slug: options.searchVendor, outcome: 'not-store' };
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const staticCustomDomainSlug = resolveCustomDomainVendorSlug(hostname);
|
|
381
|
+
if (staticCustomDomainSlug) {
|
|
382
|
+
return { slug: staticCustomDomainSlug, outcome: 'store' };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (!hostname) {
|
|
386
|
+
return { slug: options.searchVendor, outcome: 'unknown' };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const found = await lookup(hostname);
|
|
390
|
+
if (found.kind === 'store') return { slug: found.slug, outcome: 'store' };
|
|
391
|
+
|
|
392
|
+
return { slug: options.searchVendor, outcome: found.kind };
|
|
393
|
+
}
|