@snowcone-app/mockup-resolver 1.0.7 → 1.0.9
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/CHANGELOG.md +14 -0
- package/package.json +2 -2
- package/src/edge-record-cache.ts +61 -0
- package/src/index.ts +225 -31
- package/src/loadtest-exempt.ts +6 -0
- package/src/resolve.ts +95 -20
- package/src/signing.ts +60 -0
- package/test/loadtest-exempt.test.ts +11 -0
- package/test/render-limits.test.ts +73 -0
- package/test/resolve.test.ts +59 -0
- package/test/seal-v2.test.ts +84 -0
- package/wrangler.jsonc +2 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @snowcone-app/mockup-resolver
|
|
2
2
|
|
|
3
|
+
## 1.0.9
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [[`b2eb755`](https://github.com/snowcone-app/snowcone-monorepo/commit/b2eb755023a99cf0b68b45485b33b9e187a93d2e)]:
|
|
8
|
+
- @snowcone-app/mockup-url@0.4.0
|
|
9
|
+
|
|
10
|
+
## 1.0.8
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- Updated dependencies [[`a1a9095`](https://github.com/snowcone-app/snowcone-monorepo/commit/a1a909566506c63bcdc322fbd8de10b51043b9e0)]:
|
|
15
|
+
- @snowcone-app/mockup-url@0.3.4
|
|
16
|
+
|
|
3
17
|
## 1.0.7
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@snowcone-app/mockup-resolver",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.9",
|
|
4
4
|
"description": "URL signing and verification Cloudflare Worker",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"author": "",
|
|
7
7
|
"license": "ISC",
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@snowcone-app/mockup-url": "0.
|
|
9
|
+
"@snowcone-app/mockup-url": "0.4.0"
|
|
10
10
|
},
|
|
11
11
|
"devDependencies": {
|
|
12
12
|
"@cloudflare/workers-types": "^4.20250303.0",
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-POP record cache with explicit invalidation (ADR-0097, completed).
|
|
3
|
+
*
|
|
4
|
+
* KV is the source of truth for resolver records (product + account) and is
|
|
5
|
+
* overwritten on every publish — but KV is a CENTRAL store: each edge server
|
|
6
|
+
* keeps a read-through memo for only 60 s, so with ~10k products nearly every
|
|
7
|
+
* read went to the central store (rsv_product 129-160 ms cold vs 3-8 warm,
|
|
8
|
+
* measured 2026-09-02). This layer puts each record in the POP's Cache API
|
|
9
|
+
* under a synthetic URL and keeps it for a year; the backend's publish step
|
|
10
|
+
* purges that URL globally the moment the record changes (Cache Purge by URL,
|
|
11
|
+
* seconds). Hot reads become a local cache hit; after an edit each POP refills
|
|
12
|
+
* once from KV. "Cache forever, invalidate on change" — no TTL policy anywhere.
|
|
13
|
+
*
|
|
14
|
+
* The synthetic URL MUST be on a hostname in the snowcone.app zone so the
|
|
15
|
+
* zone purge API can name it. Keep `EDGE_RECORD_URL` byte-identical to
|
|
16
|
+
* apps/backend/catalog/src/edge-purge.ts.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export type EdgeRecordKind = "product" | "account";
|
|
20
|
+
|
|
21
|
+
export const EDGE_RECORD_HOST = "https://img.snowcone.app";
|
|
22
|
+
export function edgeRecordUrl(kind: EdgeRecordKind, id: string): string {
|
|
23
|
+
return `${EDGE_RECORD_HOST}/_edge/${kind}/${encodeURIComponent(id)}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const YEAR = 31_536_000;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Read `kind:id` from the POP cache; on a miss run `load` (the KV read) and
|
|
30
|
+
* store a non-null result. Null results are NOT cached: a product that gets
|
|
31
|
+
* published must be visible immediately, and a hot 404 is cheap anyway.
|
|
32
|
+
* `ctx.waitUntil` keeps the put off the response path; without a ctx the put
|
|
33
|
+
* is fired and forgotten (still correct, may be cancelled).
|
|
34
|
+
*/
|
|
35
|
+
export async function edgeCachedRecord<T>(
|
|
36
|
+
kind: EdgeRecordKind,
|
|
37
|
+
id: string,
|
|
38
|
+
load: () => Promise<T | null>,
|
|
39
|
+
ctx?: { waitUntil(p: Promise<unknown>): void },
|
|
40
|
+
): Promise<{ value: T | null; source: "edge" | "kv" }> {
|
|
41
|
+
const url = edgeRecordUrl(kind, id);
|
|
42
|
+
let cache: Cache | null = null;
|
|
43
|
+
try {
|
|
44
|
+
cache = caches.default;
|
|
45
|
+
const hit = await cache.match(url);
|
|
46
|
+
if (hit) return { value: (await hit.json()) as T, source: "edge" };
|
|
47
|
+
} catch {
|
|
48
|
+
// Cache API unavailable (local dev / tests): fall through to KV.
|
|
49
|
+
}
|
|
50
|
+
const value = await load();
|
|
51
|
+
if (value !== null && cache) {
|
|
52
|
+
const put = cache.put(
|
|
53
|
+
url,
|
|
54
|
+
new Response(JSON.stringify(value), {
|
|
55
|
+
headers: { "content-type": "application/json", "cache-control": `public, max-age=${YEAR}` },
|
|
56
|
+
}),
|
|
57
|
+
).catch(() => {});
|
|
58
|
+
if (ctx) ctx.waitUntil(put);
|
|
59
|
+
}
|
|
60
|
+
return { value, source: "kv" };
|
|
61
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
// Web Crypto API is available globally in Cloudflare Workers
|
|
3
3
|
|
|
4
4
|
// Import Cloudflare-specific modules
|
|
5
|
+
import { isLoadtestExempt } from "./loadtest-exempt";
|
|
6
|
+
import { edgeCachedRecord } from "./edge-record-cache";
|
|
5
7
|
import { DurableObject } from "cloudflare:workers";
|
|
6
8
|
|
|
7
9
|
// Add Cloudflare Workers types
|
|
@@ -46,6 +48,15 @@ interface RateLimiterStub extends DurableObjectStub {
|
|
|
46
48
|
// Interface for environment bindings
|
|
47
49
|
interface Env {
|
|
48
50
|
URL_SIGNING_SECRET: string;
|
|
51
|
+
/** Comma-separated client IPs exempt from the per-IP public caps (our 9 metro relays running the load generator). Exact match only; change via PR. */
|
|
52
|
+
LOADTEST_EXEMPT_IPS?: string;
|
|
53
|
+
/**
|
|
54
|
+
* rc#262 — Ed25519 seal signing key (PKCS#8 DER, base64). When SET, every
|
|
55
|
+
* seal this worker mints is a v2 Ed25519 signature instead of a shared-secret
|
|
56
|
+
* HMAC. Presence IS the intent; there is no separate toggle to forget.
|
|
57
|
+
* Distribute RENDER_SEAL_PUBKEY to every box BEFORE setting this.
|
|
58
|
+
*/
|
|
59
|
+
RENDER_SEAL_PRIVATE_KEY?: string;
|
|
49
60
|
/** ADR-0096: service binding to the render edge (mockup-edge-cache) — the
|
|
50
61
|
* resolver calls it in-process after sealing and streams bytes back.
|
|
51
62
|
* One client leg; the 302 hop is retired. */
|
|
@@ -355,6 +366,11 @@ function addCorsHeaders(response: Response, request: Request): Response {
|
|
|
355
366
|
|
|
356
367
|
// Clone the response and add CORS headers
|
|
357
368
|
const corsResponse = new Response(response.body, response);
|
|
369
|
+
// AI-use opt-out on every render response: noai/noimageai crawler
|
|
370
|
+
// convention + EU DSM Art.4 TDM reservation. Render output is the
|
|
371
|
+
// platform's crown-jewel training data (AUP bars AI training/reference use).
|
|
372
|
+
corsResponse.headers.set("X-Robots-Tag", "noai, noimageai");
|
|
373
|
+
corsResponse.headers.set("tdm-reservation", "1");
|
|
358
374
|
corsResponse.headers.set("Access-Control-Allow-Origin", origin);
|
|
359
375
|
corsResponse.headers.set(
|
|
360
376
|
"Access-Control-Allow-Methods",
|
|
@@ -362,7 +378,7 @@ function addCorsHeaders(response: Response, request: Request): Response {
|
|
|
362
378
|
);
|
|
363
379
|
corsResponse.headers.set(
|
|
364
380
|
"Access-Control-Allow-Headers",
|
|
365
|
-
"Content-Type, X-API-Key, X-Client-ID"
|
|
381
|
+
"Content-Type, X-API-Key, X-Client-ID, X-Render-Pin"
|
|
366
382
|
);
|
|
367
383
|
// This reflects the request Origin into ACAO, so shared caches MUST key on
|
|
368
384
|
// Origin — otherwise a cached entry for origin A (or a no-Origin request) is
|
|
@@ -408,6 +424,66 @@ async function hashApiKey(apiKey: string): Promise<string> {
|
|
|
408
424
|
* invisible at a 20rps limit — while burst latency drops to ~0. A DENIED
|
|
409
425
|
* verdict is cached for its window too, so hammering stays cheap.
|
|
410
426
|
*/
|
|
427
|
+
/**
|
|
428
|
+
* In-isolate TTL caches for the resolver's two remaining lookups (ADR-0096
|
|
429
|
+
* "rest of rsv to ~0"): account config (KV, changes rarely — revocation and
|
|
430
|
+
* limit edits lag <=60s on public renders) and product data (catalog fetch —
|
|
431
|
+
* edits lag <=30s; the render boxes' own product cache has explicit
|
|
432
|
+
* invalidation, this only delays the resolver's view). Both flatten the
|
|
433
|
+
* per-isolate warm path to ~0ms; a cold isolate still pays first-fetch.
|
|
434
|
+
*/
|
|
435
|
+
// Kevin-approved (2026-08-15): long TTL + EXPLICIT invalidation, mirroring the
|
|
436
|
+
// render fleet's product cache (rc#167 — "explicit invalidation, no age
|
|
437
|
+
// expiry"; the 60s-bound version there caused staleness bugs). Isolate memory
|
|
438
|
+
// can't be cleared remotely, so the clear mechanism is a GENERATION STAMP in
|
|
439
|
+
// the ACCOUNTS KV: each isolate refreshes its view of the stamp at most every
|
|
440
|
+
// 30s (async — never awaited on the hot path), and entries written under an
|
|
441
|
+
// older generation read as misses. CLEAR TOOLING: bump the stamp —
|
|
442
|
+
// wrangler kv key put resolver:cache-gen "$(date +%s)" --namespace-id <ACCOUNTS>
|
|
443
|
+
// (or any backend write to that key, e.g. from account-config saves / the
|
|
444
|
+
// catalog-edit fan-out) — and every isolate drops its cache within ~30s. No
|
|
445
|
+
// HTTP bump endpoint on purpose: a public cache-clear lever is a cheap DoS.
|
|
446
|
+
const ACCT_CACHE_TTL_MS = 24 * 3600_000;
|
|
447
|
+
const GEN_KEY = "resolver:cache-gen";
|
|
448
|
+
const GEN_CHECK_INTERVAL_MS = 30_000;
|
|
449
|
+
let cacheGen = "";
|
|
450
|
+
let cacheGenCheckedAt = 0;
|
|
451
|
+
let cacheGenRefreshing = false;
|
|
452
|
+
|
|
453
|
+
function refreshCacheGen(env: { ACCOUNTS: KVNamespace }): void {
|
|
454
|
+
const now = Date.now();
|
|
455
|
+
if (cacheGenRefreshing || now - cacheGenCheckedAt < GEN_CHECK_INTERVAL_MS) return;
|
|
456
|
+
cacheGenRefreshing = true;
|
|
457
|
+
void env.ACCOUNTS.get(GEN_KEY)
|
|
458
|
+
.then((g) => {
|
|
459
|
+
cacheGenCheckedAt = Date.now();
|
|
460
|
+
const next = g ?? "";
|
|
461
|
+
if (next !== cacheGen) {
|
|
462
|
+
cacheGen = next;
|
|
463
|
+
ttlCache.clear();
|
|
464
|
+
}
|
|
465
|
+
})
|
|
466
|
+
.catch(() => {
|
|
467
|
+
cacheGenCheckedAt = Date.now();
|
|
468
|
+
})
|
|
469
|
+
.finally(() => {
|
|
470
|
+
cacheGenRefreshing = false;
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
const ttlCache = new Map<string, { until: number; gen: string; value: unknown }>();
|
|
475
|
+
|
|
476
|
+
function ttlGet<T>(key: string): T | undefined {
|
|
477
|
+
const e = ttlCache.get(key);
|
|
478
|
+
if (!e || Date.now() >= e.until || e.gen !== cacheGen) return undefined;
|
|
479
|
+
return e.value as T;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function ttlSet(key: string, value: unknown, ttlMs: number): void {
|
|
483
|
+
if (ttlCache.size > 5_000) ttlCache.clear();
|
|
484
|
+
ttlCache.set(key, { until: Date.now() + ttlMs, gen: cacheGen, value });
|
|
485
|
+
}
|
|
486
|
+
|
|
411
487
|
const publicLimitBurstCache = new Map<
|
|
412
488
|
string,
|
|
413
489
|
{ windowEnd: number; used: number; allowed: boolean }
|
|
@@ -917,8 +993,8 @@ async function authenticate(
|
|
|
917
993
|
// in the default test glob) along with the L2 check; the asset-source
|
|
918
994
|
// allowlist (L2) still uses it.
|
|
919
995
|
|
|
920
|
-
export { signUrl, verifyUrl } from "./signing";
|
|
921
|
-
import {
|
|
996
|
+
export { signUrl, verifyUrl, signUrlV2, mintSeal } from "./signing";
|
|
997
|
+
import { verifyUrl, mintSeal } from "./signing";
|
|
922
998
|
import { checkAssetUrls } from "./asset-allowlist";
|
|
923
999
|
import { fetchDesign } from "./design-ref";
|
|
924
1000
|
import {
|
|
@@ -927,6 +1003,9 @@ import {
|
|
|
927
1003
|
normalizeBgColor,
|
|
928
1004
|
signDevSig,
|
|
929
1005
|
parsePublicUrl,
|
|
1006
|
+
renderUrlLengthError,
|
|
1007
|
+
E_RENDER_URL_TOO_LONG,
|
|
1008
|
+
MAX_DESIGN_ELEMENTS,
|
|
930
1009
|
PARAMS,
|
|
931
1010
|
type DesignElement,
|
|
932
1011
|
} from "@snowcone-app/mockup-url";
|
|
@@ -937,6 +1016,7 @@ import {
|
|
|
937
1016
|
resolveAlbumPagePlacement,
|
|
938
1017
|
resolveDefaults,
|
|
939
1018
|
resolveVariant,
|
|
1019
|
+
unknownOptionPick,
|
|
940
1020
|
type ResolvedPlacement,
|
|
941
1021
|
} from "./resolve";
|
|
942
1022
|
import { rejectUnknownPublicParams } from "./public-params";
|
|
@@ -1026,11 +1106,7 @@ async function handleMockupUrl(request: Request, env: Env): Promise<Response> {
|
|
|
1026
1106
|
}
|
|
1027
1107
|
|
|
1028
1108
|
// Resolve catalog defaults (Meilisearch, KV-cached).
|
|
1029
|
-
const product = await fetchProduct(productCode,
|
|
1030
|
-
host: meiliHost,
|
|
1031
|
-
apiKey: meiliKey,
|
|
1032
|
-
index: meiliIndex,
|
|
1033
|
-
}, env.ACCOUNTS);
|
|
1109
|
+
const product = await fetchProduct(productCode, env.ACCOUNTS);
|
|
1034
1110
|
if (!product) {
|
|
1035
1111
|
return err(404, "product_not_found", `Product not found: ${productCode}`);
|
|
1036
1112
|
}
|
|
@@ -1082,7 +1158,11 @@ async function handleMockupUrl(request: Request, env: Env): Promise<Response> {
|
|
|
1082
1158
|
// signature" at the box.
|
|
1083
1159
|
sigParams.delete("debug");
|
|
1084
1160
|
const relative = `${urlObj.pathname}?${sigParams.toString()}`;
|
|
1085
|
-
const
|
|
1161
|
+
const tooLong = renderUrlLengthError(relative, 1);
|
|
1162
|
+
if (tooLong) {
|
|
1163
|
+
return err(414, "render_url_too_long", tooLong);
|
|
1164
|
+
}
|
|
1165
|
+
const sig = await mintSeal(relative, signingSecret, env.RENDER_SEAL_PRIVATE_KEY);
|
|
1086
1166
|
urlObj.searchParams.append("seal", sig);
|
|
1087
1167
|
|
|
1088
1168
|
return json({ url: urlObj.toString() });
|
|
@@ -1109,9 +1189,13 @@ async function handleMockupUrl(request: Request, env: Env): Promise<Response> {
|
|
|
1109
1189
|
*/
|
|
1110
1190
|
async function loadAccountByKey(
|
|
1111
1191
|
key: string,
|
|
1112
|
-
env: Env
|
|
1192
|
+
env: Env,
|
|
1193
|
+
ctx?: { waitUntil(p: Promise<unknown>): void }
|
|
1113
1194
|
): Promise<AccountData | null> {
|
|
1114
|
-
|
|
1195
|
+
// POP cache first (edge-record-cache.ts); the backend purges
|
|
1196
|
+
// /_edge/account/<shopId> on every account config write.
|
|
1197
|
+
const cached = await edgeCachedRecord<string>("account", key, () => env.ACCOUNTS.get(key), ctx);
|
|
1198
|
+
let accountDataStr = cached.value;
|
|
1115
1199
|
if (accountDataStr) {
|
|
1116
1200
|
try {
|
|
1117
1201
|
const parsed = JSON.parse(accountDataStr) as AccountData;
|
|
@@ -1232,7 +1316,9 @@ function houseAssetUrl(request: Request): string {
|
|
|
1232
1316
|
async function handlePublicResolve(
|
|
1233
1317
|
request: Request,
|
|
1234
1318
|
env: Env,
|
|
1235
|
-
productCode: string
|
|
1319
|
+
productCode: string,
|
|
1320
|
+
ctx?: { waitUntil(p: Promise<unknown>): void },
|
|
1321
|
+
tEntry?: number
|
|
1236
1322
|
): Promise<Response> {
|
|
1237
1323
|
// All resolver responses are uncacheable — the resolver must stay in the loop
|
|
1238
1324
|
// for invalidation + per-request auth/rate (ADR-0076 §7). 4xx must never be
|
|
@@ -1251,6 +1337,8 @@ async function handlePublicResolve(
|
|
|
1251
1337
|
);
|
|
1252
1338
|
|
|
1253
1339
|
const t0 = Date.now(); // Server-Timing base — emitted on the success 302
|
|
1340
|
+
let sigMs = 0; // L3 developer-signature check (HMAC), when required
|
|
1341
|
+
let sealMs = 0; // Ed25519 seal mint
|
|
1254
1342
|
const reqUrl = new URL(request.url);
|
|
1255
1343
|
const q = reqUrl.searchParams;
|
|
1256
1344
|
|
|
@@ -1342,7 +1430,12 @@ async function handlePublicResolve(
|
|
|
1342
1430
|
|
|
1343
1431
|
// 1. Shop ID lookup → AccountData (404 unknown, 403 revoked).
|
|
1344
1432
|
const tAcct = Date.now();
|
|
1345
|
-
|
|
1433
|
+
refreshCacheGen(env);
|
|
1434
|
+
let account = ttlGet<AccountData | null>(`acct:${key}`);
|
|
1435
|
+
if (account === undefined) {
|
|
1436
|
+
account = await loadAccountByKey(key, env, ctx);
|
|
1437
|
+
ttlSet(`acct:${key}`, account, ACCT_CACHE_TTL_MS);
|
|
1438
|
+
}
|
|
1346
1439
|
const acctMs = Date.now() - tAcct;
|
|
1347
1440
|
if (!account) return errResp(404, "Unknown shop");
|
|
1348
1441
|
if (account.revoked) return errResp(403, "Shop revoked");
|
|
@@ -1390,7 +1483,9 @@ async function handlePublicResolve(
|
|
|
1390
1483
|
if (!provided) return errResp(403, "Missing required signature");
|
|
1391
1484
|
// canonicalForSig reads the RAW query verbatim — use the original URL string.
|
|
1392
1485
|
const canonical = canonicalForSig(request.url);
|
|
1486
|
+
const tSig = Date.now();
|
|
1393
1487
|
const expected = await signDevSig(canonical, account.l3Secret);
|
|
1488
|
+
sigMs = Date.now() - tSig;
|
|
1394
1489
|
let ok = expected.length === provided.length;
|
|
1395
1490
|
if (ok) {
|
|
1396
1491
|
let r = 0;
|
|
@@ -1424,12 +1519,11 @@ async function handlePublicResolve(
|
|
|
1424
1519
|
return errResp(500, "Resolver not configured");
|
|
1425
1520
|
}
|
|
1426
1521
|
|
|
1522
|
+
const limitsExempt = isLoadtestExempt(clientIp, env.LOADTEST_EXEMPT_IPS);
|
|
1427
1523
|
const tLimits = Date.now();
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
env.ACCOUNTS
|
|
1432
|
-
);
|
|
1524
|
+
// ADR-0097: one KV read of the PUBLISHED record — no in-isolate product
|
|
1525
|
+
// cache, no TTL. The only staleness on this path is KV's own propagation.
|
|
1526
|
+
const productPromise = fetchProduct(productCode, env.ACCOUNTS, ctx);
|
|
1433
1527
|
// Detached guard: when a limit blocks below, this promise is never awaited —
|
|
1434
1528
|
// without a no-op catch, a fetch failure there would surface as an unhandled
|
|
1435
1529
|
// rejection. The real `await productPromise` further down still rethrows.
|
|
@@ -1441,6 +1535,7 @@ async function handlePublicResolve(
|
|
|
1441
1535
|
retryAfter?: number;
|
|
1442
1536
|
};
|
|
1443
1537
|
const globalCheck: Promise<LimitVerdict> = (async () => {
|
|
1538
|
+
if (limitsExempt) return { allowed: true };
|
|
1444
1539
|
try {
|
|
1445
1540
|
// Kevin-approved optimistic limiting (2026-08-15): a cold per-IP DO
|
|
1446
1541
|
// wake measured 565ms synchronously on a visitor's first render, and
|
|
@@ -1471,7 +1566,7 @@ async function handlePublicResolve(
|
|
|
1471
1566
|
}
|
|
1472
1567
|
})();
|
|
1473
1568
|
const acctCheck: Promise<LimitVerdict> = (async () => {
|
|
1474
|
-
if (!account.public?.rateLimit) return { allowed: true };
|
|
1569
|
+
if (limitsExempt || !account.public?.rateLimit) return { allowed: true };
|
|
1475
1570
|
try {
|
|
1476
1571
|
// Same optimistic pattern as the global check above.
|
|
1477
1572
|
const burstKey = `${accountId}:${clientIp}`;
|
|
@@ -1591,6 +1686,29 @@ async function handlePublicResolve(
|
|
|
1591
1686
|
// 4a. Resolve the variant from option picks (both catalog shapes) + the
|
|
1592
1687
|
// render-only optionSelections rendercenter needs. resolveDefaults then supplies
|
|
1593
1688
|
// the mockup scene and a default placement (for the bare-asset case).
|
|
1689
|
+
// Strict: every `opt.<attr>=<choice>` must name a catalog attribute and one
|
|
1690
|
+
// of its choices. An unknown render-only choice used to ride through to the
|
|
1691
|
+
// box and render with no underlay; an unknown combination choice fell back
|
|
1692
|
+
// to the default variant — both silently (ADR-0099 lab product probe,
|
|
1693
|
+
// 2026-09-06). Named, with the valid values, like unknown placement keys.
|
|
1694
|
+
const badPick = unknownOptionPick(product, optionPicks);
|
|
1695
|
+
if (badPick) {
|
|
1696
|
+
return badPick.validChoices
|
|
1697
|
+
? errResp(
|
|
1698
|
+
400,
|
|
1699
|
+
`Unknown choice "${badPick.choice}" for option "${badPick.attribute}" on ${productCode}. ` +
|
|
1700
|
+
`Valid choices: ${badPick.validChoices.join(", ")}.`,
|
|
1701
|
+
"E_OPTION_CHOICE_NOT_FOUND"
|
|
1702
|
+
)
|
|
1703
|
+
: errResp(
|
|
1704
|
+
400,
|
|
1705
|
+
`Unknown option "${badPick.attribute}" on ${productCode}. ` +
|
|
1706
|
+
(badPick.validAttributes.length
|
|
1707
|
+
? `Valid options: ${badPick.validAttributes.join(", ")}.`
|
|
1708
|
+
: `This product has no options.`),
|
|
1709
|
+
"E_OPTION_NOT_FOUND"
|
|
1710
|
+
);
|
|
1711
|
+
}
|
|
1594
1712
|
const vr = resolveVariant(product, optionPicks, variantOverride);
|
|
1595
1713
|
if (!vr) {
|
|
1596
1714
|
return errResp(422, `Product ${productCode} has no renderable combination`);
|
|
@@ -1674,9 +1792,15 @@ async function handlePublicResolve(
|
|
|
1674
1792
|
if (designElements.length === 0) {
|
|
1675
1793
|
return errResp(400, "Missing artwork: provide asset= or asset.<placement>=");
|
|
1676
1794
|
}
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1795
|
+
// One cap, three enforcers (resolver, buy worker, render box) — the number
|
|
1796
|
+
// lives in @snowcone-app/mockup-url; the box pins the same literal.
|
|
1797
|
+
if (designElements.length > MAX_DESIGN_ELEMENTS) {
|
|
1798
|
+
return errResp(
|
|
1799
|
+
400,
|
|
1800
|
+
`Too many placements: ${designElements.length} (max ${MAX_DESIGN_ELEMENTS}). ` +
|
|
1801
|
+
`Reference a saved design with design=<reference> for more surfaces.`,
|
|
1802
|
+
"E_TOO_MANY_PLACEMENTS"
|
|
1803
|
+
);
|
|
1680
1804
|
}
|
|
1681
1805
|
|
|
1682
1806
|
// 5. Build the render URL FRESH — never forward the incoming query string, so
|
|
@@ -1712,6 +1836,15 @@ async function handlePublicResolve(
|
|
|
1712
1836
|
if (catalogDesign) {
|
|
1713
1837
|
urlObj.searchParams.append("catalog", catalogDesign.pairingId);
|
|
1714
1838
|
}
|
|
1839
|
+
// Catalog render version (resolve.ts renderVersion), UNDER the seal: keys
|
|
1840
|
+
// the box Redis cache, the edge R2/POP cache and the browser ETag, so a
|
|
1841
|
+
// catalog fix re-keys every tier at once — the public URL stays the same
|
|
1842
|
+
// and the next revalidation (private, max-age=300) fetches the fixed
|
|
1843
|
+
// pixels instead of a 304. Empty only for records published before the
|
|
1844
|
+
// field existed; those keep legacy keys until their next publish.
|
|
1845
|
+
if (product.renderVersion) {
|
|
1846
|
+
urlObj.searchParams.append("pv", product.renderVersion);
|
|
1847
|
+
}
|
|
1715
1848
|
// Operator debug passthrough (ADR-0096): with the 302 retired, the client
|
|
1716
1849
|
// never learns the sealed URL, so the lab's full-waterfall replay re-fetches
|
|
1717
1850
|
// the PUBLIC url with debug=<RENDER_DEBUG_SECRET>. Forward it onto the
|
|
@@ -1731,7 +1864,16 @@ async function handlePublicResolve(
|
|
|
1731
1864
|
// signature" at the box.
|
|
1732
1865
|
sigParams.delete("debug");
|
|
1733
1866
|
const relative = `${urlObj.pathname}?${sigParams.toString()}`;
|
|
1734
|
-
|
|
1867
|
+
// Whole-URL ceiling, checked BEFORE the seal: past ~16 KiB the render box's
|
|
1868
|
+
// HTTP parser answers a bare 431 with no code and no hint (prod probe
|
|
1869
|
+
// 2026-09-06, 7 placements × 1.9 KB asset URLs). Typed here, with the fix.
|
|
1870
|
+
const tooLong = renderUrlLengthError(relative, designElements.length);
|
|
1871
|
+
if (tooLong) {
|
|
1872
|
+
return errResp(414, tooLong, E_RENDER_URL_TOO_LONG);
|
|
1873
|
+
}
|
|
1874
|
+
const tSeal = Date.now();
|
|
1875
|
+
const sig = await mintSeal(relative, signingSecret, env.RENDER_SEAL_PRIVATE_KEY);
|
|
1876
|
+
sealMs = Date.now() - tSeal;
|
|
1735
1877
|
urlObj.searchParams.append("seal", sig);
|
|
1736
1878
|
|
|
1737
1879
|
// 7. Single-leg render (ADR-0096, retired the 302): call the render edge
|
|
@@ -1754,31 +1896,79 @@ async function handlePublicResolve(
|
|
|
1754
1896
|
// overlapping totals make waterfalls unreadable (browser wait then reads:
|
|
1755
1897
|
// transit + rsv_total + edge_total, no envelope arithmetic needed).
|
|
1756
1898
|
const resolverMs = Date.now() - t0;
|
|
1899
|
+
// Forward the CLIENT's cf blob through the service binding: a fresh
|
|
1900
|
+
// Request has NO cf, so without this the render router downstream sees a
|
|
1901
|
+
// geo-less request and can't do proximity routing — which, on the
|
|
1902
|
+
// single-leg path, is EVERY public render (pre-fix they all landed on
|
|
1903
|
+
// whatever box sat first in the RENDER_BOXES KV array; observed as a US
|
|
1904
|
+
// user's renders consistently served from the EU box). The redirect-era
|
|
1905
|
+
// flow never had this problem because the browser hit the edge directly.
|
|
1906
|
+
const tEdge = Date.now();
|
|
1757
1907
|
const edgeRes = await env.RENDER_EDGE.fetch(
|
|
1758
1908
|
new Request(urlObj.toString(), {
|
|
1759
1909
|
method: "GET",
|
|
1760
1910
|
headers: request.headers,
|
|
1761
|
-
|
|
1911
|
+
cf: (request as unknown as { cf?: RequestInitCfProperties }).cf,
|
|
1912
|
+
} as RequestInit)
|
|
1762
1913
|
);
|
|
1914
|
+
// rsv_hop = the service-binding round trip minus the edge's own edge_total:
|
|
1915
|
+
// pure worker-to-worker cost. Measured ~10-15 ms (2026-09-02); merging the
|
|
1916
|
+
// two workers did not remove it (reverted, #2063).
|
|
1917
|
+
const edgeWallMs = Date.now() - tEdge;
|
|
1918
|
+
const edgeTotalMs = Number((/(?:^|[ ,])edge_total;dur=([0-9.]+)/.exec(edgeRes.headers.get("Server-Timing") || "") || [])[1] ?? NaN);
|
|
1919
|
+
const hopMs = Number.isFinite(edgeTotalMs) ? Math.max(0, Math.round(edgeWallMs - edgeTotalMs)) : edgeWallMs;
|
|
1763
1920
|
const headers = new Headers(edgeRes.headers);
|
|
1764
|
-
|
|
1921
|
+
// Revalidation (ADR-0096 amendment, 2026-09-04): the edge stamps the render
|
|
1922
|
+
// key as a strong ETag and answers If-None-Match with a 304 — the browser's
|
|
1923
|
+
// header rides through on `request.headers` above. A 304 is a SUCCESS here:
|
|
1924
|
+
// it must carry the same `private, max-age=300` so the browser extends its
|
|
1925
|
+
// copy's freshness for another five minutes (a `no-store` on a 304 would
|
|
1926
|
+
// poison the stored entry instead). So after the window a page refresh
|
|
1927
|
+
// costs one header-only round trip per image, not a re-download — while
|
|
1928
|
+
// every control point (auth, limits, catalog, DMCA at the edge) still ran.
|
|
1929
|
+
// stale-while-revalidate: past the 5-minute window the browser paints its
|
|
1930
|
+
// cached copy immediately and revalidates in the background, so a
|
|
1931
|
+
// returning visitor never waits on our round trip. The trade, stated: a
|
|
1932
|
+
// catalog fix reaches that visitor on the load AFTER the revalidation, not
|
|
1933
|
+
// the one that triggered it (Kevin 2026-09-04, accepted for instant paint).
|
|
1934
|
+
const edgeOk = edgeRes.ok || edgeRes.status === 304;
|
|
1935
|
+
headers.set("Cache-Control", edgeOk ? "private, max-age=300, stale-while-revalidate=86400" : "no-store");
|
|
1765
1936
|
headers.set("Access-Control-Allow-Origin", "*");
|
|
1766
1937
|
headers.set("Timing-Allow-Origin", "*");
|
|
1938
|
+
// Let browser tooling (the render-speed lab) read box attribution + the
|
|
1939
|
+
// encoder choice off cross-origin responses.
|
|
1940
|
+
headers.set(
|
|
1941
|
+
"Access-Control-Expose-Headers",
|
|
1942
|
+
"ETag, Server-Timing, X-Render-Box, X-Render-Pinned, X-Render-Overflow, X-Encoder"
|
|
1943
|
+
);
|
|
1767
1944
|
headers.append(
|
|
1768
1945
|
"Server-Timing",
|
|
1769
|
-
`rsv_acct;dur=${acctMs}, rsv_limits;dur=${limitsMs}, ` +
|
|
1770
|
-
`rsv_product;dur=${productMs}, rsv_total;dur=${resolverMs}`
|
|
1946
|
+
`rsv_pre;dur=${tEntry ? t0 - tEntry : 0}, rsv_acct;dur=${acctMs}, rsv_sig;dur=${sigMs}, rsv_limits;dur=${limitsMs}${limitsExempt ? ';desc="exempt"' : ""}, ` +
|
|
1947
|
+
`rsv_product;dur=${productMs}, rsv_seal;dur=${sealMs}, rsv_total;dur=${resolverMs}, rsv_hop;dur=${hopMs}, ` +
|
|
1948
|
+
// desc-only: the isolate AGE is not a duration of this request (a dur= here drew a 30-minute bar in the lab)
|
|
1949
|
+
`rsv_iso;desc="${(rsvIsoBorn || (rsvIsoBorn = tEdge, rsvIsoId = crypto.randomUUID().slice(0, 8)), rsvIsoId)} age=${((tEdge - rsvIsoBorn) / 1000).toFixed(1)}s n=${++rsvIsoReqCount}"`
|
|
1771
1950
|
);
|
|
1772
|
-
|
|
1951
|
+
// A 304 has no body by definition; the Response constructor rejects a
|
|
1952
|
+
// stream on a null-body status, so pass null explicitly.
|
|
1953
|
+
return new Response(edgeRes.status === 304 ? null : edgeRes.body, {
|
|
1773
1954
|
status: edgeRes.status,
|
|
1774
1955
|
statusText: edgeRes.statusText,
|
|
1775
1956
|
headers,
|
|
1776
1957
|
});
|
|
1777
1958
|
}
|
|
1778
1959
|
|
|
1960
|
+
// Per-isolate identity for rsv_iso (pairs with the edge's edge_iso: a hop
|
|
1961
|
+
// spike on a young edge isolate is a cold start; on an old one it is the
|
|
1962
|
+
// service-binding dispatch itself).
|
|
1963
|
+
// Initialised on first use: random values/clocks are disallowed in the global scope.
|
|
1964
|
+
let rsvIsoId = ''
|
|
1965
|
+
let rsvIsoBorn = 0
|
|
1966
|
+
let rsvIsoReqCount = 0
|
|
1967
|
+
|
|
1779
1968
|
// Cloudflare Worker entry point
|
|
1780
1969
|
export default {
|
|
1781
1970
|
async fetch(request: Request, env: Env, ctx: any): Promise<Response> {
|
|
1971
|
+
const tEntry = Date.now(); // Server-Timing rsv_pre = worker entry → resolve handler
|
|
1782
1972
|
// SECURITY: the former unauthenticated `/test-kv` debug endpoint was removed.
|
|
1783
1973
|
// It dumped/enumerated/wrote the ACCOUNTS KV (account configs, key hashes,
|
|
1784
1974
|
// L3 secrets) with no auth, live in production. Nothing depends on it; do
|
|
@@ -1791,7 +1981,11 @@ export default {
|
|
|
1791
1981
|
"Access-Control-Allow-Origin": request.headers.get("Origin") || "*",
|
|
1792
1982
|
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
1793
1983
|
"Access-Control-Allow-Headers":
|
|
1794
|
-
"Content-Type, X-API-Key, X-Client-ID",
|
|
1984
|
+
"Content-Type, X-API-Key, X-Client-ID, X-Render-Pin",
|
|
1985
|
+
// Let the browser reuse this preflight verdict for a day: a client
|
|
1986
|
+
// that sends custom headers (X-Client-ID, X-Render-Pin) otherwise
|
|
1987
|
+
// pays an OPTIONS round trip through this worker per render.
|
|
1988
|
+
"Access-Control-Max-Age": "86400",
|
|
1795
1989
|
// Reflected Origin → cache must vary by Origin (see CORS notes above).
|
|
1796
1990
|
Vary: "Origin",
|
|
1797
1991
|
},
|
|
@@ -1843,7 +2037,7 @@ export default {
|
|
|
1843
2037
|
url.pathname.split("/").filter(Boolean)[0]
|
|
1844
2038
|
);
|
|
1845
2039
|
return addCorsHeaders(
|
|
1846
|
-
await handlePublicResolve(request, env, productCode),
|
|
2040
|
+
await handlePublicResolve(request, env, productCode, ctx, tEntry),
|
|
1847
2041
|
request
|
|
1848
2042
|
);
|
|
1849
2043
|
}
|
|
@@ -1983,7 +2177,7 @@ export default {
|
|
|
1983
2177
|
? urlObj.pathname + urlObj.search
|
|
1984
2178
|
: urlObj.toString();
|
|
1985
2179
|
|
|
1986
|
-
const signature = await
|
|
2180
|
+
const signature = await mintSeal(finalUrlToSign, secretKey, env.RENDER_SEAL_PRIVATE_KEY);
|
|
1987
2181
|
|
|
1988
2182
|
// Construct the signed URL by adding the signature parameter
|
|
1989
2183
|
urlObj.searchParams.append("seal", signature);
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Per-IP public rate-limit exemption for our own load generators (the metro relays).
|
|
2
|
+
* Exact-IP match only: no CIDR, no wildcards. The list is a plain wrangler var. */
|
|
3
|
+
export function isLoadtestExempt(clientIp: string, list: string | undefined): boolean {
|
|
4
|
+
if (!list || !clientIp || clientIp === "unknown-ip") return false;
|
|
5
|
+
return list.split(",").map((s) => s.trim()).filter(Boolean).includes(clientIp);
|
|
6
|
+
}
|
package/src/resolve.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// logic in `apps/www/app/api/harness/mockup/route.ts` (the prototype) and the
|
|
5
5
|
// SDK's `getProduct`. Edge-safe: plain fetch + JSON. (ADR-0073 §10.)
|
|
6
6
|
|
|
7
|
+
import { edgeCachedRecord } from "./edge-record-cache";
|
|
7
8
|
import {
|
|
8
9
|
PARAMS,
|
|
9
10
|
type DesignElement,
|
|
@@ -35,7 +36,12 @@ export function looksLikeResolveRequest(
|
|
|
35
36
|
host: string,
|
|
36
37
|
url: URL
|
|
37
38
|
): boolean {
|
|
38
|
-
|
|
39
|
+
// HEAD mirrors GET: uptime checks and agents that verify a mockup URL with
|
|
40
|
+
// `curl -I` used to fall through to the "Mockup Resolver API" JSON default
|
|
41
|
+
// route (200 + application/json) and conclude the image was broken
|
|
42
|
+
// (growth/0013 F3, eng/0049). The runtime drops the body on HEAD, so the
|
|
43
|
+
// same 302 → image redirect is returned with the real headers.
|
|
44
|
+
if (method !== "GET" && method !== "HEAD") return false;
|
|
39
45
|
|
|
40
46
|
const segments = url.pathname.split("/").filter(Boolean);
|
|
41
47
|
if (segments.length !== 1) return false;
|
|
@@ -108,6 +114,15 @@ export interface ResolvedPlacement {
|
|
|
108
114
|
}
|
|
109
115
|
|
|
110
116
|
export interface ResolvedProduct {
|
|
117
|
+
/** Content version of the published record (ADR-0097). */
|
|
118
|
+
version: string;
|
|
119
|
+
/** Render version: hash of the product's pixel-affecting config (full
|
|
120
|
+
* mockups/masks, placements, variants, options), minted by the backend
|
|
121
|
+
* (catalog/src/resolver-record.ts). Sealed onto every render URL as
|
|
122
|
+
* `pv=` so box, edge and browser caches all key on it — a catalog fix
|
|
123
|
+
* changes it and pre-fix pixels stop being served everywhere at once.
|
|
124
|
+
* Falls back to `version` for records published before it existed. */
|
|
125
|
+
renderVersion: string;
|
|
111
126
|
id: string;
|
|
112
127
|
variants: { gvid: string }[];
|
|
113
128
|
mockups: { id: string; gvids: string[] }[];
|
|
@@ -135,9 +150,15 @@ export interface VariantResolution {
|
|
|
135
150
|
optionSelections: Record<string, string>;
|
|
136
151
|
}
|
|
137
152
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
153
|
+
/**
|
|
154
|
+
* ADR-0097: the product record is PUBLISHED to KV by the backend in the same
|
|
155
|
+
* step that writes Meilisearch — no TTL, no Meili fetch here. `prod:<code>`
|
|
156
|
+
* holds `{ version, publishedAt, raw }`; a missing key means "not published"
|
|
157
|
+
* and resolves to 404 exactly as a Meili miss did. Concurrent requests for
|
|
158
|
+
* the same product share one in-flight read.
|
|
159
|
+
*/
|
|
160
|
+
const RESOLVER_PRODUCT_KEY = (code: string) => `prod:${code}`;
|
|
161
|
+
const inflightProducts = new Map<string, Promise<ResolvedProduct | null>>();
|
|
141
162
|
|
|
142
163
|
/** Lowercase + collapse non-alphanumerics to `_` — the fallback slug for a
|
|
143
164
|
* placement that has no catalog `key` yet (pre-P1). */
|
|
@@ -342,23 +363,38 @@ export function assembleArtwork(
|
|
|
342
363
|
return { ok: true, elements: [...byKey.values()] };
|
|
343
364
|
}
|
|
344
365
|
|
|
345
|
-
/**
|
|
366
|
+
/** Read a product's published record from KV (ADR-0097). Returns null if not published. */
|
|
346
367
|
export async function fetchProduct(
|
|
347
368
|
productCode: string,
|
|
348
|
-
|
|
349
|
-
|
|
369
|
+
kv: KVNamespace,
|
|
370
|
+
ctx?: { waitUntil(p: Promise<unknown>): void }
|
|
350
371
|
): Promise<ResolvedProduct | null> {
|
|
351
|
-
const
|
|
352
|
-
const
|
|
353
|
-
if (
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
372
|
+
const key = RESOLVER_PRODUCT_KEY(productCode);
|
|
373
|
+
const pending = inflightProducts.get(key);
|
|
374
|
+
if (pending) return pending;
|
|
375
|
+
const p = (async () => {
|
|
376
|
+
// POP cache first (edge-record-cache.ts): a year-long entry the backend
|
|
377
|
+
// purges by URL on every publish. Miss → the KV read, then fill.
|
|
378
|
+
const { value: rec } = await edgeCachedRecord<{ version?: string; renderVersion?: string; raw?: RawProduct }>(
|
|
379
|
+
"product",
|
|
380
|
+
productCode,
|
|
381
|
+
async () => (await kv.get(key, "json")) as { version?: string; renderVersion?: string; raw?: RawProduct } | null,
|
|
382
|
+
ctx,
|
|
383
|
+
);
|
|
384
|
+
if (!rec || !rec.raw) return null;
|
|
385
|
+
const version = typeof rec.version === "string" ? rec.version : "";
|
|
386
|
+
const renderVersion = typeof rec.renderVersion === "string" && rec.renderVersion ? rec.renderVersion : version;
|
|
387
|
+
return toResolvedProduct(rec.raw, version, renderVersion);
|
|
388
|
+
})();
|
|
389
|
+
inflightProducts.set(key, p);
|
|
390
|
+
try {
|
|
391
|
+
return await p;
|
|
392
|
+
} finally {
|
|
393
|
+
inflightProducts.delete(key);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
360
396
|
|
|
361
|
-
|
|
397
|
+
function toResolvedProduct(raw: RawProduct, version: string, renderVersion: string = version): ResolvedProduct {
|
|
362
398
|
|
|
363
399
|
const rawAttrs = raw.options?.attributes ?? {};
|
|
364
400
|
const attributes: ResolvedProduct["attributes"] = {};
|
|
@@ -386,6 +422,8 @@ export async function fetchProduct(
|
|
|
386
422
|
}
|
|
387
423
|
|
|
388
424
|
const resolved: ResolvedProduct = {
|
|
425
|
+
version,
|
|
426
|
+
renderVersion,
|
|
389
427
|
id: raw.id,
|
|
390
428
|
variants: (raw.variants ?? [])
|
|
391
429
|
.map((v) => ({ gvid: v.gvid ?? v.id ?? "" }))
|
|
@@ -404,9 +442,6 @@ export async function fetchProduct(
|
|
|
404
442
|
album: normalizeAlbum(raw.album),
|
|
405
443
|
};
|
|
406
444
|
|
|
407
|
-
await kv.put(cacheKey, JSON.stringify(resolved), {
|
|
408
|
-
expirationTtl: CACHE_TTL_SECONDS,
|
|
409
|
-
});
|
|
410
445
|
return resolved;
|
|
411
446
|
}
|
|
412
447
|
|
|
@@ -440,6 +475,46 @@ export function resolveDefaults(
|
|
|
440
475
|
return { variantId, mockupId: mockup.id, placement };
|
|
441
476
|
}
|
|
442
477
|
|
|
478
|
+
export interface UnknownOptionPick {
|
|
479
|
+
/** The attribute as the caller wrote it (unknown attribute) or the catalog's name (unknown choice). */
|
|
480
|
+
attribute: string;
|
|
481
|
+
choice: string;
|
|
482
|
+
validAttributes: string[];
|
|
483
|
+
/** null when the ATTRIBUTE is unknown; the attribute's choices when the CHOICE is. */
|
|
484
|
+
validChoices: string[] | null;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* The first `opt.<attr>=<choice>` pick that names no catalog attribute, or a
|
|
489
|
+
* choice the attribute does not list (both case-insensitive), or null when
|
|
490
|
+
* every pick is valid. An attribute with no listed choices accepts any value
|
|
491
|
+
* (nothing to validate against).
|
|
492
|
+
*
|
|
493
|
+
* Without this, a wrong pick was SILENT: an unknown render-only choice rode
|
|
494
|
+
* `optionSelections` to the render box, which found no choice and rendered
|
|
495
|
+
* the product with no underlay; an unknown combination choice matched no
|
|
496
|
+
* SKU row and fell through to the default variant. Same policy as placement
|
|
497
|
+
* keys — fail loudly, name the valid values (ADR-0089 house style).
|
|
498
|
+
*/
|
|
499
|
+
export function unknownOptionPick(
|
|
500
|
+
product: ResolvedProduct,
|
|
501
|
+
picks: Record<string, string>
|
|
502
|
+
): UnknownOptionPick | null {
|
|
503
|
+
const attrs = product.attributes ?? {};
|
|
504
|
+
const validAttributes = Object.keys(attrs);
|
|
505
|
+
const byLower = new Map(validAttributes.map((n) => [n.toLowerCase(), n]));
|
|
506
|
+
for (const [rawAttr, rawChoice] of Object.entries(picks)) {
|
|
507
|
+
const name = byLower.get(rawAttr.toLowerCase());
|
|
508
|
+
if (!name) return { attribute: rawAttr, choice: rawChoice, validAttributes, validChoices: null };
|
|
509
|
+
const choices = attrs[name]?.choices ?? [];
|
|
510
|
+
if (choices.length === 0) continue;
|
|
511
|
+
if (!choices.some((c) => c.toLowerCase() === rawChoice.toLowerCase())) {
|
|
512
|
+
return { attribute: name, choice: rawChoice, validAttributes, validChoices: choices };
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
return null;
|
|
516
|
+
}
|
|
517
|
+
|
|
443
518
|
/**
|
|
444
519
|
* Resolve public option picks (`opt.<attr>=<choice>`, matched case-insensitively)
|
|
445
520
|
* to a variant gvid + the render-only `optionSelections` rendercenter consumes.
|
package/src/signing.ts
CHANGED
|
@@ -40,3 +40,63 @@ export async function verifyUrl(
|
|
|
40
40
|
}
|
|
41
41
|
return result === 0;
|
|
42
42
|
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* rc#262 — Ed25519 (v2) seal minting.
|
|
46
|
+
*
|
|
47
|
+
* The private key never leaves the edge/backend. Boxes hold only the 32-byte
|
|
48
|
+
* public half, so a compromised box can no longer forge seals for itself OR
|
|
49
|
+
* the fleet — which is the whole point of the migration away from the shared
|
|
50
|
+
* `URL_SIGNING_SECRET`.
|
|
51
|
+
*
|
|
52
|
+
* Wire format: `v2.<base64url(64-byte signature)>`. The signed canonical
|
|
53
|
+
* string is IDENTICAL to the v1 HMAC one, so callers need no other change.
|
|
54
|
+
*/
|
|
55
|
+
export const SEAL_V2_PREFIX = "v2.";
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @param url Canonical string to sign (`path?query`, seal+debug removed)
|
|
59
|
+
* @param pkcs8B64 Ed25519 private key, PKCS#8 DER, base64 (NOT base64url)
|
|
60
|
+
*/
|
|
61
|
+
export async function signUrlV2(url: string, pkcs8B64: string): Promise<string> {
|
|
62
|
+
const der = Uint8Array.from(atob(pkcs8B64), (c) => c.charCodeAt(0));
|
|
63
|
+
|
|
64
|
+
let key: CryptoKey;
|
|
65
|
+
try {
|
|
66
|
+
key = await crypto.subtle.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
|
|
67
|
+
} catch (cause) {
|
|
68
|
+
// An unusable signing key is an operator error, not a request error. Throw
|
|
69
|
+
// with the fix named rather than silently falling back to a v1 HMAC seal —
|
|
70
|
+
// a silent downgrade would quietly un-do the security migration.
|
|
71
|
+
throw new Error(
|
|
72
|
+
"E_SEAL_PRIVATE_KEY_INVALID: RENDER_SEAL_PRIVATE_KEY is not an importable " +
|
|
73
|
+
"Ed25519 PKCS#8 key. Expect base64 of the PKCS#8 DER (64 chars for Ed25519). " +
|
|
74
|
+
"Regenerate with `openssl genpkey -algorithm ed25519` and re-set the secret.",
|
|
75
|
+
{ cause },
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const sig = new Uint8Array(await crypto.subtle.sign("Ed25519", key, new TextEncoder().encode(url)));
|
|
80
|
+
|
|
81
|
+
// base64url, no padding — safe to drop straight into a query string.
|
|
82
|
+
let bin = "";
|
|
83
|
+
for (const b of sig) bin += String.fromCharCode(b);
|
|
84
|
+
return SEAL_V2_PREFIX + btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Mint the correct seal for the current rollout stage.
|
|
89
|
+
*
|
|
90
|
+
* Presence of the Ed25519 key IS the intent — there is no separate boolean to
|
|
91
|
+
* forget. Distribute the public key to every box FIRST; the box throws
|
|
92
|
+
* E_SEAL_PUBKEY_MISSING (loudly, never a silent 401) if that order is broken.
|
|
93
|
+
*/
|
|
94
|
+
export async function mintSeal(
|
|
95
|
+
url: string,
|
|
96
|
+
hmacSecret: string,
|
|
97
|
+
ed25519PrivateKeyB64?: string,
|
|
98
|
+
): Promise<string> {
|
|
99
|
+
return ed25519PrivateKeyB64
|
|
100
|
+
? signUrlV2(url, ed25519PrivateKeyB64)
|
|
101
|
+
: signUrl(url, hmacSecret);
|
|
102
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { isLoadtestExempt } from "../src/loadtest-exempt";
|
|
3
|
+
describe("isLoadtestExempt", () => {
|
|
4
|
+
const list = "172.236.245.89, 50.116.2.79";
|
|
5
|
+
it("exact listed IPs only", () => {
|
|
6
|
+
expect(isLoadtestExempt("50.116.2.79", list)).toBe(true);
|
|
7
|
+
expect(isLoadtestExempt("50.116.2.7", list)).toBe(false);
|
|
8
|
+
expect(isLoadtestExempt("unknown-ip", "unknown-ip")).toBe(false);
|
|
9
|
+
expect(isLoadtestExempt("172.236.245.89", undefined)).toBe(false);
|
|
10
|
+
});
|
|
11
|
+
});
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
2
|
+
import { resolve } from 'node:path'
|
|
3
|
+
import { describe, expect, it } from 'vitest'
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
E_RENDER_URL_TOO_LONG,
|
|
7
|
+
MAX_DESIGN_ELEMENTS,
|
|
8
|
+
MAX_RENDER_URL_LENGTH,
|
|
9
|
+
renderUrlLengthError,
|
|
10
|
+
} from '@snowcone-app/mockup-url'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The design-element cap is ONE number enforced in three places: this
|
|
14
|
+
* resolver, the buy worker (both import MAX_DESIGN_ELEMENTS) and the render
|
|
15
|
+
* box (`services/rendercenter/shared/src/types.ts` CACHE_LIMITS.MAX_ELEMENTS,
|
|
16
|
+
* a separate repo that cannot import this package). Each side pins the
|
|
17
|
+
* literal and names the other; when the submodule is checked out (local dev)
|
|
18
|
+
* the two files are ALSO compared directly. CI checks out the monorepo
|
|
19
|
+
* without the submodule, so there the literal pin is the whole assertion —
|
|
20
|
+
* stated here so nobody reads a green run as "cross-checked".
|
|
21
|
+
*/
|
|
22
|
+
describe('MAX_DESIGN_ELEMENTS drift pin (resolver ↔ buy ↔ render box)', () => {
|
|
23
|
+
it('pins the literal the render box enforces (rendercenter shared CACHE_LIMITS.MAX_ELEMENTS = 10)', () => {
|
|
24
|
+
expect(MAX_DESIGN_ELEMENTS).toBe(10)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('matches the submodule copy when services/rendercenter is checked out (literal-only in CI)', () => {
|
|
28
|
+
const typesTs = resolve(__dirname, '../../../services/rendercenter/shared/src/types.ts')
|
|
29
|
+
if (!existsSync(typesTs)) {
|
|
30
|
+
// Submodule absent (CI): the literal pin above is the assertion.
|
|
31
|
+
expect(MAX_DESIGN_ELEMENTS).toBe(10)
|
|
32
|
+
return
|
|
33
|
+
}
|
|
34
|
+
const m = /MAX_ELEMENTS:\s*(\d+)/.exec(readFileSync(typesTs, 'utf8'))
|
|
35
|
+
expect(m, 'CACHE_LIMITS.MAX_ELEMENTS not found in rendercenter shared/src/types.ts').not.toBeNull()
|
|
36
|
+
expect(Number(m![1])).toBe(MAX_DESIGN_ELEMENTS)
|
|
37
|
+
})
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
describe('renderUrlLengthError (E_RENDER_URL_TOO_LONG)', () => {
|
|
41
|
+
const path = '/5J6AQA?shop=dqMwU8Jct3&width=800&assets='
|
|
42
|
+
it('accepts a URL at the ceiling and refuses one character past it', () => {
|
|
43
|
+
expect(MAX_RENDER_URL_LENGTH).toBe(12 * 1024)
|
|
44
|
+
expect(renderUrlLengthError(path + 'a'.repeat(MAX_RENDER_URL_LENGTH - path.length))).toBeNull()
|
|
45
|
+
const msg = renderUrlLengthError(path + 'a'.repeat(MAX_RENDER_URL_LENGTH - path.length + 1), 7)
|
|
46
|
+
expect(msg).not.toBeNull()
|
|
47
|
+
expect(msg).toContain(`${MAX_RENDER_URL_LENGTH + 1} characters`)
|
|
48
|
+
expect(msg).toContain('7 placements')
|
|
49
|
+
expect(msg).toContain(String(MAX_RENDER_URL_LENGTH))
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('names the fix: design=<reference> or fewer/shorter asset URLs', () => {
|
|
53
|
+
const msg = renderUrlLengthError('x'.repeat(MAX_RENDER_URL_LENGTH * 2), 10)!
|
|
54
|
+
expect(msg).toContain('design=<reference>')
|
|
55
|
+
expect(msg).toMatch(/fewer placements \/ shorter asset URLs/)
|
|
56
|
+
expect(E_RENDER_URL_TOO_LONG).toBe('E_RENDER_URL_TOO_LONG')
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it('a realistic oversize request (7 placements × 1.9 KB asset URLs, the prod 431 repro) is refused before the seal', () => {
|
|
60
|
+
// The resolver base64-encodes the design array into `assets=`: 7 × ~1.9 KB
|
|
61
|
+
// → ~18 KB, which the render box's 16 KiB header limit answered with a
|
|
62
|
+
// bare 431 (2026-09-06). Model the expansion the way buildMockupUrl does.
|
|
63
|
+
const asset = 'https://dqMwU8Jct3.storage.snowcone.app/demo/demo-001.jpg?pad=' + 'x'.repeat(1850)
|
|
64
|
+
const design = ['front', 'placket', 'back', 'left_sleeve', 'right_sleeve', 'inner_collar', 'outer_collar'].map(
|
|
65
|
+
(placement) => ({ imageUrl: asset, placement }),
|
|
66
|
+
)
|
|
67
|
+
const assets = Buffer.from(JSON.stringify(design)).toString('base64')
|
|
68
|
+
expect(renderUrlLengthError(path + encodeURIComponent(assets), design.length)).not.toBeNull()
|
|
69
|
+
// …while the single-placement shape of the same asset URL fits comfortably.
|
|
70
|
+
const one = Buffer.from(JSON.stringify(design.slice(0, 1))).toString('base64')
|
|
71
|
+
expect(renderUrlLengthError(path + encodeURIComponent(one), 1)).toBeNull()
|
|
72
|
+
})
|
|
73
|
+
})
|
package/test/resolve.test.ts
CHANGED
|
@@ -5,9 +5,11 @@ import {
|
|
|
5
5
|
normalizeAlbum,
|
|
6
6
|
resolveAlbumPagePlacement,
|
|
7
7
|
resolveVariant,
|
|
8
|
+
unknownOptionPick,
|
|
8
9
|
slugify,
|
|
9
10
|
type ResolvedPlacement,
|
|
10
11
|
type ResolvedProduct,
|
|
12
|
+
fetchProduct,
|
|
11
13
|
} from "../src/resolve";
|
|
12
14
|
|
|
13
15
|
// A size×color-style product WITH combinations (picks select the SKU).
|
|
@@ -83,6 +85,13 @@ describe("looksLikeResolveRequest", () => {
|
|
|
83
85
|
const u = (path: string, host = "img.snowcone.app") =>
|
|
84
86
|
new URL(`https://${host}${path}`);
|
|
85
87
|
|
|
88
|
+
// eng/0049 F3: HEAD must take the same path as GET so `curl -I` on an
|
|
89
|
+
// img.snowcone.app URL never lands on the JSON default route.
|
|
90
|
+
it("treats HEAD like GET on the img host (F3)", () => {
|
|
91
|
+
expect(looksLikeResolveRequest("HEAD", "img.snowcone.app", u("/JFBH0Q"))).toBe(true);
|
|
92
|
+
expect(looksLikeResolveRequest("POST", "img.snowcone.app", u("/JFBH0Q"))).toBe(false);
|
|
93
|
+
});
|
|
94
|
+
|
|
86
95
|
it("resolves on the prod img host (leading label)", () => {
|
|
87
96
|
expect(
|
|
88
97
|
looksLikeResolveRequest("GET", "img.snowcone.app", u("/JFBH0Q"))
|
|
@@ -436,3 +445,53 @@ describe("assembleArtwork (base + override, ADR-0089)", () => {
|
|
|
436
445
|
expect(r.elements).toHaveLength(0);
|
|
437
446
|
});
|
|
438
447
|
});
|
|
448
|
+
|
|
449
|
+
describe("fetchProduct render version (pv=)", () => {
|
|
450
|
+
const rawTee = {
|
|
451
|
+
id: "T",
|
|
452
|
+
variants: [{ gvid: "g1" }],
|
|
453
|
+
mockups: [{ id: "m1", gvids: ["g1"] }],
|
|
454
|
+
placements: [{ key: "front", label: "Front", type: "image", width: 12, height: 16 }],
|
|
455
|
+
defaultGvid: "g1",
|
|
456
|
+
options: { attributes: {}, combinations: [] },
|
|
457
|
+
album: null,
|
|
458
|
+
};
|
|
459
|
+
const kvWith = (record: unknown) =>
|
|
460
|
+
({ get: async () => record }) as unknown as KVNamespace;
|
|
461
|
+
|
|
462
|
+
it("surfaces the backend's renderVersion", async () => {
|
|
463
|
+
const p = await fetchProduct("T", kvWith({ version: "v1", renderVersion: "r1", raw: rawTee }));
|
|
464
|
+
expect(p?.version).toBe("v1");
|
|
465
|
+
expect(p?.renderVersion).toBe("r1");
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
it("falls back to version for records published before renderVersion existed", async () => {
|
|
469
|
+
const p = await fetchProduct("T", kvWith({ version: "v1", raw: rawTee }));
|
|
470
|
+
expect(p?.renderVersion).toBe("v1");
|
|
471
|
+
});
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
describe("unknownOptionPick (E_OPTION_NOT_FOUND / E_OPTION_CHOICE_NOT_FOUND)", () => {
|
|
475
|
+
it("accepts valid picks case-insensitively and no picks at all", () => {
|
|
476
|
+
expect(unknownOptionPick(tee, {})).toBeNull();
|
|
477
|
+
expect(unknownOptionPick(tee, { size: "m" })).toBeNull();
|
|
478
|
+
expect(unknownOptionPick(cap, { pocket: "left chest" })).toBeNull();
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
it("names an unknown attribute with the valid ones", () => {
|
|
482
|
+
expect(unknownOptionPick(tee, { Colour: "Red" })).toEqual({
|
|
483
|
+
attribute: "Colour", choice: "Red", validAttributes: ["Size"], validChoices: null,
|
|
484
|
+
});
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
it("names an unknown choice with the attribute's choices (a render-only underlay pick that would otherwise render with no underlay)", () => {
|
|
488
|
+
expect(unknownOptionPick(cap, { Pocket: "Right chest" })).toEqual({
|
|
489
|
+
attribute: "Pocket", choice: "Right chest", validAttributes: ["Crown", "Pocket"], validChoices: ["None", "Left chest"],
|
|
490
|
+
});
|
|
491
|
+
expect(unknownOptionPick(tee, { Size: "XXL" })?.validChoices).toEqual(["S", "M", "L"]);
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
it("an attribute with no listed choices accepts any value (nothing to validate against)", () => {
|
|
495
|
+
expect(unknownOptionPick(cap, { Crown: "anything" })).toBeNull();
|
|
496
|
+
});
|
|
497
|
+
});
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import { describe, expect, it } from "vitest";
|
|
4
|
+
|
|
5
|
+
import { signUrl, signUrlV2, mintSeal, SEAL_V2_PREFIX } from "../src/signing";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* rc#262 — the edge signs, the box only verifies.
|
|
9
|
+
*
|
|
10
|
+
* These tests pin the exact contract the rendercenter verifier
|
|
11
|
+
* (api/src/utils/seal-ed25519.ts) implements, using an INDEPENDENT
|
|
12
|
+
* implementation (node:crypto) to verify what WebCrypto produced. If the two
|
|
13
|
+
* runtimes ever disagree, that is precisely the failure this catches — a
|
|
14
|
+
* seal that mints fine at the edge and 401s on every box.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const kp = crypto.generateKeyPairSync("ed25519");
|
|
18
|
+
const PKCS8_B64 = kp.privateKey.export({ type: "pkcs8", format: "der" }).toString("base64");
|
|
19
|
+
const RAW_PUB = kp.publicKey.export({ type: "spki", format: "der" }).subarray(12);
|
|
20
|
+
|
|
21
|
+
/** Verify exactly the way a box does: raw 32-byte pubkey, SPKI-wrapped. */
|
|
22
|
+
function boxVerifies(canonical: string, seal: string): boolean {
|
|
23
|
+
const sig = Buffer.from(seal.slice(SEAL_V2_PREFIX.length), "base64url");
|
|
24
|
+
const pub = crypto.createPublicKey({
|
|
25
|
+
key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), RAW_PUB]),
|
|
26
|
+
format: "der",
|
|
27
|
+
type: "spki",
|
|
28
|
+
});
|
|
29
|
+
return crypto.verify(null, Buffer.from(canonical), pub, sig);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe("signUrlV2", () => {
|
|
33
|
+
const canonical = "/mockup?product=tee&width=800";
|
|
34
|
+
|
|
35
|
+
it("mints a seal a box can verify with only the public key", async () => {
|
|
36
|
+
const seal = await signUrlV2(canonical, PKCS8_B64);
|
|
37
|
+
expect(seal.startsWith(SEAL_V2_PREFIX)).toBe(true);
|
|
38
|
+
expect(boxVerifies(canonical, seal)).toBe(true);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("produces a 64-byte signature (86 base64url chars)", async () => {
|
|
42
|
+
const seal = await signUrlV2(canonical, PKCS8_B64);
|
|
43
|
+
expect(seal.slice(SEAL_V2_PREFIX.length)).toHaveLength(86);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("is URL-safe — no +, / or = to escape", async () => {
|
|
47
|
+
const seal = await signUrlV2(canonical, PKCS8_B64);
|
|
48
|
+
expect(seal).toMatch(/^v2\.[A-Za-z0-9_-]+$/);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("does not verify against a different canonical string", async () => {
|
|
52
|
+
const seal = await signUrlV2(canonical, PKCS8_B64);
|
|
53
|
+
expect(boxVerifies("/mockup?product=tee&width=4000", seal)).toBe(false);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("throws a named error on an unusable key rather than downgrading", async () => {
|
|
57
|
+
// A silent fall back to a v1 HMAC seal would quietly undo the migration.
|
|
58
|
+
await expect(signUrlV2(canonical, "bm90LWEta2V5")).rejects.toThrow(
|
|
59
|
+
/E_SEAL_PRIVATE_KEY_INVALID/,
|
|
60
|
+
);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
describe("mintSeal rollout gate", () => {
|
|
65
|
+
const canonical = "/mockup?product=tee&width=800";
|
|
66
|
+
|
|
67
|
+
it("mints a legacy HMAC seal when no Ed25519 key is configured", async () => {
|
|
68
|
+
const seal = await mintSeal(canonical, "hmac-secret", undefined);
|
|
69
|
+
expect(seal).toBe(await signUrl(canonical, "hmac-secret"));
|
|
70
|
+
expect(seal).toMatch(/^[0-9a-f]{16}$/);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("mints v2 as soon as the Ed25519 key is present — presence IS the intent", async () => {
|
|
74
|
+
const seal = await mintSeal(canonical, "hmac-secret", PKCS8_B64);
|
|
75
|
+
expect(boxVerifies(canonical, seal)).toBe(true);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("v1 and v2 seals are never confusable", async () => {
|
|
79
|
+
const v1 = await mintSeal(canonical, "hmac-secret", undefined);
|
|
80
|
+
const v2 = await mintSeal(canonical, "hmac-secret", PKCS8_B64);
|
|
81
|
+
expect(v1.includes(".")).toBe(false);
|
|
82
|
+
expect(v2.startsWith("v2.")).toBe(true);
|
|
83
|
+
});
|
|
84
|
+
});
|
package/wrangler.jsonc
CHANGED
|
@@ -30,6 +30,8 @@
|
|
|
30
30
|
// to override these prod defaults. For standalone `pnpm dev`, copy
|
|
31
31
|
// .dev.vars.example -> .dev.vars.
|
|
32
32
|
"vars": {
|
|
33
|
+
// Our nine metro relays (relay-<metro>-1): the production-shape load generator. Exact IPs; change via PR.
|
|
34
|
+
"LOADTEST_EXEMPT_IPS": "172.236.245.89,139.144.31.189,45.79.3.111,172.104.24.94,172.234.136.102,172.235.133.146,172.237.142.112,172.234.252.106,50.116.2.79",
|
|
33
35
|
"TTL_DEFAULT": "86400",
|
|
34
36
|
"LOG_LEVEL": "info",
|
|
35
37
|
// MEILISEARCH_API_KEY is the public read-only search key (same as apps/www);
|