@usequeek/theme-kit 0.1.38 → 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/package.json +1 -1
- package/sdk/server-store-client.ts +34 -6
- package/sdk/storefront-proxy-auth.ts +55 -0
- package/utils/vendor-host.ts +150 -13
package/package.json
CHANGED
|
@@ -4,6 +4,7 @@ import { LOCALE_CODE_HEADER, parseLocaleCode, withLocaleQuery, withLocaleTags }
|
|
|
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
|
|
@@ -223,6 +224,30 @@ export async function readRequestMarket(vendorSlug: string, verify?: (marketId:
|
|
|
223
224
|
}
|
|
224
225
|
}
|
|
225
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
|
+
|
|
226
251
|
/** Options of {@link createServerStoreClient}. */
|
|
227
252
|
export interface ServerStoreClientOptions {
|
|
228
253
|
/**
|
|
@@ -259,25 +284,28 @@ export function createServerStoreClient(vendorSlug: string, origin?: string, opt
|
|
|
259
284
|
// leave the shared data cache. The cache is shared by every visitor, its key is the URL, and a rate moves
|
|
260
285
|
// without any revalidation tag, so a market price is never stored there. No market: today's request.
|
|
261
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);
|
|
262
291
|
return request<T>(
|
|
263
292
|
API_BASE_URL,
|
|
264
293
|
`/client/store${path}`,
|
|
265
294
|
{
|
|
266
295
|
query: withMarketQuery(withLocaleQuery(query, code), marketId),
|
|
267
296
|
timeoutMs: SSR_TIMEOUT_MS,
|
|
268
|
-
cachePolicy
|
|
269
|
-
? null
|
|
270
|
-
: withLocaleCachePolicy(resolveCachePolicy(vendorSlug, path, query), code),
|
|
297
|
+
cachePolicy,
|
|
271
298
|
},
|
|
272
|
-
|
|
299
|
+
// A cached read carries only the secret; an uncached one also names the shopper.
|
|
300
|
+
{ ...buildHeaders(), ...(await getStorefrontApiHeaders({ cached: !!cachePolicy })) },
|
|
273
301
|
);
|
|
274
302
|
},
|
|
275
|
-
post: <T>(path: string, body?: unknown) =>
|
|
303
|
+
post: async <T>(path: string, body?: unknown) =>
|
|
276
304
|
request<T>(API_BASE_URL, `/client/store${path}`, {
|
|
277
305
|
method: 'POST',
|
|
278
306
|
body: body ? JSON.stringify(body) : undefined,
|
|
279
307
|
timeoutMs: SSR_TIMEOUT_MS,
|
|
280
308
|
cachePolicy: null,
|
|
281
|
-
}, buildHeaders()),
|
|
309
|
+
}, { ...buildHeaders(), ...(await getStorefrontApiHeaders({ cached: false })) }),
|
|
282
310
|
};
|
|
283
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([
|
|
@@ -167,16 +169,64 @@ export function resolveCustomDomainVendorSlug(hostname: string): string | null {
|
|
|
167
169
|
}
|
|
168
170
|
}
|
|
169
171
|
|
|
170
|
-
|
|
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> {
|
|
171
221
|
if (!hostname) {
|
|
172
|
-
return
|
|
222
|
+
return { kind: 'unknown' };
|
|
173
223
|
}
|
|
174
224
|
|
|
175
225
|
// Middleware runs server-side — prefer the server-only absolute URL. The
|
|
176
226
|
// public var can be a same-origin relative path, which `fetch()` can't resolve without a document origin here.
|
|
177
227
|
const baseUrl = process.env.QUEEK_API_URL ?? process.env.NEXT_PUBLIC_QUEEK_API_URL;
|
|
178
228
|
if (!baseUrl) {
|
|
179
|
-
return
|
|
229
|
+
return { kind: 'unknown' };
|
|
180
230
|
}
|
|
181
231
|
|
|
182
232
|
const url = `${baseUrl.replace(/\/+$/, '')}/client/resolve-by-host?host=${encodeURIComponent(hostname)}`;
|
|
@@ -186,31 +236,54 @@ export async function resolveCustomDomainVendorSlugRemote(hostname: string): Pro
|
|
|
186
236
|
try {
|
|
187
237
|
const response = await fetch(url, {
|
|
188
238
|
method: 'GET',
|
|
189
|
-
|
|
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 } : {}) },
|
|
190
241
|
signal: controller.signal,
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
tags: [`host:${hostname}`],
|
|
194
|
-
},
|
|
242
|
+
...(options.cache === 'no-store'
|
|
243
|
+
? { cache: 'no-store' as const }
|
|
244
|
+
: { next: { revalidate: REMOTE_RESOLVE_REVALIDATE_SECONDS, tags: [`host:${hostname}`] } }),
|
|
195
245
|
});
|
|
196
246
|
|
|
197
247
|
if (!response.ok) {
|
|
198
248
|
logRemoteFailure(`status ${response.status}`);
|
|
199
|
-
|
|
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' };
|
|
200
255
|
}
|
|
201
256
|
|
|
202
|
-
const payload = (await response.json()) as { data?: { slug?: unknown } };
|
|
203
|
-
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
|
+
}
|
|
204
265
|
|
|
205
|
-
|
|
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' };
|
|
206
273
|
} catch (error) {
|
|
207
274
|
logRemoteFailure(error instanceof Error ? error.message : 'unknown');
|
|
208
|
-
return
|
|
275
|
+
return { kind: 'unknown' };
|
|
209
276
|
} finally {
|
|
210
277
|
clearTimeout(timeoutId);
|
|
211
278
|
}
|
|
212
279
|
}
|
|
213
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
|
+
|
|
214
287
|
function logRemoteFailure(reason: string): void {
|
|
215
288
|
const now = Date.now();
|
|
216
289
|
if (now - lastRemoteFailureLoggedAt < REMOTE_FAILURE_LOG_WINDOW_MS) {
|
|
@@ -254,3 +327,67 @@ export async function resolveVendorSlug(options: {
|
|
|
254
327
|
|
|
255
328
|
return options.searchVendor;
|
|
256
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
|
+
}
|