@snowcone-app/mockup-resolver 1.0.8 → 1.0.10
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 +279 -59
- package/src/loadtest-exempt.ts +6 -0
- package/src/resolve.ts +440 -47
- package/src/signing.ts +60 -0
- package/test/loadtest-exempt.test.ts +11 -0
- package/test/public-params.test.ts +15 -0
- package/test/render-limits.test.ts +73 -0
- package/test/resolve.test.ts +236 -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.10
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [[`45c7428`](https://github.com/snowcone-app/snowcone-monorepo/commit/45c7428ae50fda88af2c26daff5d169156e7a141)]:
|
|
8
|
+
- @snowcone-app/mockup-url@0.5.0
|
|
9
|
+
|
|
10
|
+
## 1.0.9
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- Updated dependencies [[`b2eb755`](https://github.com/snowcone-app/snowcone-monorepo/commit/b2eb755023a99cf0b68b45485b33b9e187a93d2e)]:
|
|
15
|
+
- @snowcone-app/mockup-url@0.4.0
|
|
16
|
+
|
|
3
17
|
## 1.0.8
|
|
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.10",
|
|
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.5.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
|
|
@@ -416,19 +432,56 @@ async function hashApiKey(apiKey: string): Promise<string> {
|
|
|
416
432
|
* invalidation, this only delays the resolver's view). Both flatten the
|
|
417
433
|
* per-isolate warm path to ~0ms; a cold isolate still pays first-fetch.
|
|
418
434
|
*/
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
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 }>();
|
|
422
475
|
|
|
423
476
|
function ttlGet<T>(key: string): T | undefined {
|
|
424
477
|
const e = ttlCache.get(key);
|
|
425
|
-
if (!e || Date.now() >= e.until) return undefined;
|
|
478
|
+
if (!e || Date.now() >= e.until || e.gen !== cacheGen) return undefined;
|
|
426
479
|
return e.value as T;
|
|
427
480
|
}
|
|
428
481
|
|
|
429
482
|
function ttlSet(key: string, value: unknown, ttlMs: number): void {
|
|
430
483
|
if (ttlCache.size > 5_000) ttlCache.clear();
|
|
431
|
-
ttlCache.set(key, { until: Date.now() + ttlMs, value });
|
|
484
|
+
ttlCache.set(key, { until: Date.now() + ttlMs, gen: cacheGen, value });
|
|
432
485
|
}
|
|
433
486
|
|
|
434
487
|
const publicLimitBurstCache = new Map<
|
|
@@ -940,8 +993,8 @@ async function authenticate(
|
|
|
940
993
|
// in the default test glob) along with the L2 check; the asset-source
|
|
941
994
|
// allowlist (L2) still uses it.
|
|
942
995
|
|
|
943
|
-
export { signUrl, verifyUrl } from "./signing";
|
|
944
|
-
import {
|
|
996
|
+
export { signUrl, verifyUrl, signUrlV2, mintSeal } from "./signing";
|
|
997
|
+
import { verifyUrl, mintSeal } from "./signing";
|
|
945
998
|
import { checkAssetUrls } from "./asset-allowlist";
|
|
946
999
|
import { fetchDesign } from "./design-ref";
|
|
947
1000
|
import {
|
|
@@ -950,6 +1003,9 @@ import {
|
|
|
950
1003
|
normalizeBgColor,
|
|
951
1004
|
signDevSig,
|
|
952
1005
|
parsePublicUrl,
|
|
1006
|
+
renderUrlLengthError,
|
|
1007
|
+
E_RENDER_URL_TOO_LONG,
|
|
1008
|
+
MAX_DESIGN_ELEMENTS,
|
|
953
1009
|
PARAMS,
|
|
954
1010
|
type DesignElement,
|
|
955
1011
|
} from "@snowcone-app/mockup-url";
|
|
@@ -958,8 +1014,13 @@ import {
|
|
|
958
1014
|
fetchProduct,
|
|
959
1015
|
looksLikeResolveRequest,
|
|
960
1016
|
resolveAlbumPagePlacement,
|
|
1017
|
+
resolveBundleScene,
|
|
961
1018
|
resolveDefaults,
|
|
962
1019
|
resolveVariant,
|
|
1020
|
+
unknownOptionPick,
|
|
1021
|
+
type BundleScene,
|
|
1022
|
+
type ResolveDefaults,
|
|
1023
|
+
type VariantResolution,
|
|
963
1024
|
type ResolvedPlacement,
|
|
964
1025
|
} from "./resolve";
|
|
965
1026
|
import { rejectUnknownPublicParams } from "./public-params";
|
|
@@ -1049,11 +1110,7 @@ async function handleMockupUrl(request: Request, env: Env): Promise<Response> {
|
|
|
1049
1110
|
}
|
|
1050
1111
|
|
|
1051
1112
|
// Resolve catalog defaults (Meilisearch, KV-cached).
|
|
1052
|
-
const product = await fetchProduct(productCode,
|
|
1053
|
-
host: meiliHost,
|
|
1054
|
-
apiKey: meiliKey,
|
|
1055
|
-
index: meiliIndex,
|
|
1056
|
-
}, env.ACCOUNTS);
|
|
1113
|
+
const product = await fetchProduct(productCode, env.ACCOUNTS);
|
|
1057
1114
|
if (!product) {
|
|
1058
1115
|
return err(404, "product_not_found", `Product not found: ${productCode}`);
|
|
1059
1116
|
}
|
|
@@ -1105,7 +1162,11 @@ async function handleMockupUrl(request: Request, env: Env): Promise<Response> {
|
|
|
1105
1162
|
// signature" at the box.
|
|
1106
1163
|
sigParams.delete("debug");
|
|
1107
1164
|
const relative = `${urlObj.pathname}?${sigParams.toString()}`;
|
|
1108
|
-
const
|
|
1165
|
+
const tooLong = renderUrlLengthError(relative, 1);
|
|
1166
|
+
if (tooLong) {
|
|
1167
|
+
return err(414, "render_url_too_long", tooLong);
|
|
1168
|
+
}
|
|
1169
|
+
const sig = await mintSeal(relative, signingSecret, env.RENDER_SEAL_PRIVATE_KEY);
|
|
1109
1170
|
urlObj.searchParams.append("seal", sig);
|
|
1110
1171
|
|
|
1111
1172
|
return json({ url: urlObj.toString() });
|
|
@@ -1132,9 +1193,13 @@ async function handleMockupUrl(request: Request, env: Env): Promise<Response> {
|
|
|
1132
1193
|
*/
|
|
1133
1194
|
async function loadAccountByKey(
|
|
1134
1195
|
key: string,
|
|
1135
|
-
env: Env
|
|
1196
|
+
env: Env,
|
|
1197
|
+
ctx?: { waitUntil(p: Promise<unknown>): void }
|
|
1136
1198
|
): Promise<AccountData | null> {
|
|
1137
|
-
|
|
1199
|
+
// POP cache first (edge-record-cache.ts); the backend purges
|
|
1200
|
+
// /_edge/account/<shopId> on every account config write.
|
|
1201
|
+
const cached = await edgeCachedRecord<string>("account", key, () => env.ACCOUNTS.get(key), ctx);
|
|
1202
|
+
let accountDataStr = cached.value;
|
|
1138
1203
|
if (accountDataStr) {
|
|
1139
1204
|
try {
|
|
1140
1205
|
const parsed = JSON.parse(accountDataStr) as AccountData;
|
|
@@ -1255,7 +1320,9 @@ function houseAssetUrl(request: Request): string {
|
|
|
1255
1320
|
async function handlePublicResolve(
|
|
1256
1321
|
request: Request,
|
|
1257
1322
|
env: Env,
|
|
1258
|
-
productCode: string
|
|
1323
|
+
productCode: string,
|
|
1324
|
+
ctx?: { waitUntil(p: Promise<unknown>): void },
|
|
1325
|
+
tEntry?: number
|
|
1259
1326
|
): Promise<Response> {
|
|
1260
1327
|
// All resolver responses are uncacheable — the resolver must stay in the loop
|
|
1261
1328
|
// for invalidation + per-request auth/rate (ADR-0076 §7). 4xx must never be
|
|
@@ -1274,6 +1341,8 @@ async function handlePublicResolve(
|
|
|
1274
1341
|
);
|
|
1275
1342
|
|
|
1276
1343
|
const t0 = Date.now(); // Server-Timing base — emitted on the success 302
|
|
1344
|
+
let sigMs = 0; // L3 developer-signature check (HMAC), when required
|
|
1345
|
+
let sealMs = 0; // Ed25519 seal mint
|
|
1277
1346
|
const reqUrl = new URL(request.url);
|
|
1278
1347
|
const q = reqUrl.searchParams;
|
|
1279
1348
|
|
|
@@ -1365,9 +1434,10 @@ async function handlePublicResolve(
|
|
|
1365
1434
|
|
|
1366
1435
|
// 1. Shop ID lookup → AccountData (404 unknown, 403 revoked).
|
|
1367
1436
|
const tAcct = Date.now();
|
|
1437
|
+
refreshCacheGen(env);
|
|
1368
1438
|
let account = ttlGet<AccountData | null>(`acct:${key}`);
|
|
1369
1439
|
if (account === undefined) {
|
|
1370
|
-
account = await loadAccountByKey(key, env);
|
|
1440
|
+
account = await loadAccountByKey(key, env, ctx);
|
|
1371
1441
|
ttlSet(`acct:${key}`, account, ACCT_CACHE_TTL_MS);
|
|
1372
1442
|
}
|
|
1373
1443
|
const acctMs = Date.now() - tAcct;
|
|
@@ -1417,7 +1487,9 @@ async function handlePublicResolve(
|
|
|
1417
1487
|
if (!provided) return errResp(403, "Missing required signature");
|
|
1418
1488
|
// canonicalForSig reads the RAW query verbatim — use the original URL string.
|
|
1419
1489
|
const canonical = canonicalForSig(request.url);
|
|
1490
|
+
const tSig = Date.now();
|
|
1420
1491
|
const expected = await signDevSig(canonical, account.l3Secret);
|
|
1492
|
+
sigMs = Date.now() - tSig;
|
|
1421
1493
|
let ok = expected.length === provided.length;
|
|
1422
1494
|
if (ok) {
|
|
1423
1495
|
let r = 0;
|
|
@@ -1451,18 +1523,11 @@ async function handlePublicResolve(
|
|
|
1451
1523
|
return errResp(500, "Resolver not configured");
|
|
1452
1524
|
}
|
|
1453
1525
|
|
|
1526
|
+
const limitsExempt = isLoadtestExempt(clientIp, env.LOADTEST_EXEMPT_IPS);
|
|
1454
1527
|
const tLimits = Date.now();
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
: fetchProduct(
|
|
1459
|
-
productCode,
|
|
1460
|
-
{ host: meiliHost, apiKey: meiliKey, index: meiliIndex },
|
|
1461
|
-
env.ACCOUNTS
|
|
1462
|
-
).then((p) => {
|
|
1463
|
-
ttlSet(`prod:${productCode}`, p, PRODUCT_CACHE_TTL_MS);
|
|
1464
|
-
return p;
|
|
1465
|
-
});
|
|
1528
|
+
// ADR-0097: one KV read of the PUBLISHED record — no in-isolate product
|
|
1529
|
+
// cache, no TTL. The only staleness on this path is KV's own propagation.
|
|
1530
|
+
const productPromise = fetchProduct(productCode, env.ACCOUNTS, ctx);
|
|
1466
1531
|
// Detached guard: when a limit blocks below, this promise is never awaited —
|
|
1467
1532
|
// without a no-op catch, a fetch failure there would surface as an unhandled
|
|
1468
1533
|
// rejection. The real `await productPromise` further down still rethrows.
|
|
@@ -1474,6 +1539,7 @@ async function handlePublicResolve(
|
|
|
1474
1539
|
retryAfter?: number;
|
|
1475
1540
|
};
|
|
1476
1541
|
const globalCheck: Promise<LimitVerdict> = (async () => {
|
|
1542
|
+
if (limitsExempt) return { allowed: true };
|
|
1477
1543
|
try {
|
|
1478
1544
|
// Kevin-approved optimistic limiting (2026-08-15): a cold per-IP DO
|
|
1479
1545
|
// wake measured 565ms synchronously on a visitor's first render, and
|
|
@@ -1504,7 +1570,7 @@ async function handlePublicResolve(
|
|
|
1504
1570
|
}
|
|
1505
1571
|
})();
|
|
1506
1572
|
const acctCheck: Promise<LimitVerdict> = (async () => {
|
|
1507
|
-
if (!account.public?.rateLimit) return { allowed: true };
|
|
1573
|
+
if (limitsExempt || !account.public?.rateLimit) return { allowed: true };
|
|
1508
1574
|
try {
|
|
1509
1575
|
// Same optimistic pattern as the global check above.
|
|
1510
1576
|
const burstKey = `${accountId}:${clientIp}`;
|
|
@@ -1621,24 +1687,102 @@ async function handlePublicResolve(
|
|
|
1621
1687
|
);
|
|
1622
1688
|
}
|
|
1623
1689
|
}
|
|
1690
|
+
// 4-bundle (ADR-0099 slice 3). A bundle record resolves per SLOT: picks
|
|
1691
|
+
// decide which alternative's placements exist and which mockup fits, then
|
|
1692
|
+
// each slot resolves its own SKU through the member's combinations
|
|
1693
|
+
// (`variant.<role>=`, `opt.<role>.<attr>=`). The box URL keys its cache on
|
|
1694
|
+
// the per-role render-gvid set (one deterministic token), and the elements
|
|
1695
|
+
// carry role-scoped placement keys. Bare `variant=`/`opt.<attr>=` on a
|
|
1696
|
+
// bundle name no slot and are refused with the roles listed; bundle params
|
|
1697
|
+
// on a non-bundle are refused too — never silently ignored.
|
|
1698
|
+
let bundleScene: BundleScene | null = null;
|
|
1699
|
+
if (product.bundle) {
|
|
1700
|
+
if (catalogDesign) {
|
|
1701
|
+
return errResp(
|
|
1702
|
+
400,
|
|
1703
|
+
`design= is not yet supported on bundle ${productCode} — bundle pairings land with the cart work (ADR-0099 slice 5). Render with asset= / asset.<role>.<placement>= for now.`,
|
|
1704
|
+
"E_BUNDLE_DESIGN_UNSUPPORTED"
|
|
1705
|
+
);
|
|
1706
|
+
}
|
|
1707
|
+
if (pagePlacement) {
|
|
1708
|
+
return errResp(400, `page= is not valid on bundle ${productCode} (bundles have no album block)`);
|
|
1709
|
+
}
|
|
1710
|
+
const r = resolveBundleScene(product, {
|
|
1711
|
+
picks: parsed.picks ?? {},
|
|
1712
|
+
variants: parsed.variants ?? {},
|
|
1713
|
+
options: optionPicks,
|
|
1714
|
+
variantOverride,
|
|
1715
|
+
mockupOverride,
|
|
1716
|
+
});
|
|
1717
|
+
if (!r.ok) return errResp(r.status, r.message, r.code);
|
|
1718
|
+
bundleScene = r.scene;
|
|
1719
|
+
} else if (parsed.picks || parsed.variants) {
|
|
1720
|
+
return errResp(
|
|
1721
|
+
400,
|
|
1722
|
+
`pick.<role>= and variant.<role>= are bundle parameters — ${productCode} is not a bundle. ` +
|
|
1723
|
+
`Use variant=<gvid> and opt.<attribute>=<choice>.`,
|
|
1724
|
+
"E_NOT_A_BUNDLE"
|
|
1725
|
+
);
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1624
1728
|
// 4a. Resolve the variant from option picks (both catalog shapes) + the
|
|
1625
1729
|
// render-only optionSelections rendercenter needs. resolveDefaults then supplies
|
|
1626
1730
|
// the mockup scene and a default placement (for the bare-asset case).
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1731
|
+
// Strict: every `opt.<attr>=<choice>` must name a catalog attribute and one
|
|
1732
|
+
// of its choices. An unknown render-only choice used to ride through to the
|
|
1733
|
+
// box and render with no underlay; an unknown combination choice fell back
|
|
1734
|
+
// to the default variant — both silently (ADR-0099 lab product probe,
|
|
1735
|
+
// 2026-09-06). Named, with the valid values, like unknown placement keys.
|
|
1736
|
+
let vr: VariantResolution;
|
|
1737
|
+
let scene: ResolveDefaults;
|
|
1738
|
+
if (bundleScene) {
|
|
1739
|
+
vr = { variantId: bundleScene.variantToken, optionSelections: bundleScene.optionSelections };
|
|
1740
|
+
scene = {
|
|
1741
|
+
variantId: bundleScene.variantToken,
|
|
1742
|
+
mockupId: bundleScene.mockupId,
|
|
1743
|
+
placement: bundleScene.placements[0],
|
|
1744
|
+
};
|
|
1745
|
+
} else {
|
|
1746
|
+
const badPick = unknownOptionPick(product, optionPicks);
|
|
1747
|
+
if (badPick) {
|
|
1748
|
+
return badPick.validChoices
|
|
1749
|
+
? errResp(
|
|
1750
|
+
400,
|
|
1751
|
+
`Unknown choice "${badPick.choice}" for option "${badPick.attribute}" on ${productCode}. ` +
|
|
1752
|
+
`Valid choices: ${badPick.validChoices.join(", ")}.`,
|
|
1753
|
+
"E_OPTION_CHOICE_NOT_FOUND"
|
|
1754
|
+
)
|
|
1755
|
+
: errResp(
|
|
1756
|
+
400,
|
|
1757
|
+
`Unknown option "${badPick.attribute}" on ${productCode}. ` +
|
|
1758
|
+
(badPick.validAttributes.length
|
|
1759
|
+
? `Valid options: ${badPick.validAttributes.join(", ")}.`
|
|
1760
|
+
: `This product has no options.`),
|
|
1761
|
+
"E_OPTION_NOT_FOUND"
|
|
1762
|
+
);
|
|
1763
|
+
}
|
|
1764
|
+
const resolvedVariant = resolveVariant(product, optionPicks, variantOverride);
|
|
1765
|
+
if (!resolvedVariant) {
|
|
1766
|
+
return errResp(422, `Product ${productCode} has no renderable combination`);
|
|
1767
|
+
}
|
|
1768
|
+
vr = resolvedVariant;
|
|
1769
|
+
const resolvedScene = resolveDefaults(product, {
|
|
1770
|
+
variant: vr.variantId,
|
|
1771
|
+
mockupId: mockupOverride,
|
|
1772
|
+
placement: placementOverride,
|
|
1773
|
+
});
|
|
1774
|
+
if (!resolvedScene) {
|
|
1775
|
+
return errResp(422, `Product ${productCode} has no renderable combination`);
|
|
1776
|
+
}
|
|
1777
|
+
scene = resolvedScene;
|
|
1778
|
+
// page=N selects which album page feeds the scene: the resolved default
|
|
1779
|
+
// placement becomes the repeating page placement's geometry.
|
|
1780
|
+
if (pagePlacement) scene.placement = pagePlacement;
|
|
1638
1781
|
}
|
|
1639
|
-
//
|
|
1640
|
-
//
|
|
1641
|
-
|
|
1782
|
+
// The placements artwork resolves against: a bundle's are narrowed to the
|
|
1783
|
+
// pick set (so `top.front` is the picked alternative's Front and the
|
|
1784
|
+
// E_PLACEMENT_NOT_FOUND list names only keys that exist for these picks).
|
|
1785
|
+
const renderProduct = bundleScene ? { ...product, placements: bundleScene.placements } : product;
|
|
1642
1786
|
|
|
1643
1787
|
// 4b. Build the design elements: one base broadcast across every placement
|
|
1644
1788
|
// plus per-placement overrides (ADR-0089), or a catalog design verbatim.
|
|
@@ -1652,8 +1796,8 @@ async function handlePublicResolve(
|
|
|
1652
1796
|
// the repeating placement's geometry, ADR-0086); null for everything else,
|
|
1653
1797
|
// so non-album products behave exactly as before.
|
|
1654
1798
|
const findPlacement = (k: string) =>
|
|
1655
|
-
|
|
1656
|
-
resolveAlbumPagePlacement(
|
|
1799
|
+
renderProduct.placements.find((p) => p.key === k) ??
|
|
1800
|
+
resolveAlbumPagePlacement(renderProduct, k);
|
|
1657
1801
|
|
|
1658
1802
|
const designElements: DesignElement[] = [];
|
|
1659
1803
|
if (catalogDesign) {
|
|
@@ -1693,7 +1837,7 @@ async function handlePublicResolve(
|
|
|
1693
1837
|
// override key fails loudly (E_PLACEMENT_NOT_FOUND, listing valid keys).
|
|
1694
1838
|
// The base broadcast fans out across `product.placements` directly — it no
|
|
1695
1839
|
// longer rides the single default-placement resolution.
|
|
1696
|
-
const assembled = assembleArtwork(
|
|
1840
|
+
const assembled = assembleArtwork(renderProduct, {
|
|
1697
1841
|
asset,
|
|
1698
1842
|
design,
|
|
1699
1843
|
house,
|
|
@@ -1707,9 +1851,15 @@ async function handlePublicResolve(
|
|
|
1707
1851
|
if (designElements.length === 0) {
|
|
1708
1852
|
return errResp(400, "Missing artwork: provide asset= or asset.<placement>=");
|
|
1709
1853
|
}
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1854
|
+
// One cap, three enforcers (resolver, buy worker, render box) — the number
|
|
1855
|
+
// lives in @snowcone-app/mockup-url; the box pins the same literal.
|
|
1856
|
+
if (designElements.length > MAX_DESIGN_ELEMENTS) {
|
|
1857
|
+
return errResp(
|
|
1858
|
+
400,
|
|
1859
|
+
`Too many placements: ${designElements.length} (max ${MAX_DESIGN_ELEMENTS}). ` +
|
|
1860
|
+
`Reference a saved design with design=<reference> for more surfaces.`,
|
|
1861
|
+
"E_TOO_MANY_PLACEMENTS"
|
|
1862
|
+
);
|
|
1713
1863
|
}
|
|
1714
1864
|
|
|
1715
1865
|
// 5. Build the render URL FRESH — never forward the incoming query string, so
|
|
@@ -1745,6 +1895,15 @@ async function handlePublicResolve(
|
|
|
1745
1895
|
if (catalogDesign) {
|
|
1746
1896
|
urlObj.searchParams.append("catalog", catalogDesign.pairingId);
|
|
1747
1897
|
}
|
|
1898
|
+
// Catalog render version (resolve.ts renderVersion), UNDER the seal: keys
|
|
1899
|
+
// the box Redis cache, the edge R2/POP cache and the browser ETag, so a
|
|
1900
|
+
// catalog fix re-keys every tier at once — the public URL stays the same
|
|
1901
|
+
// and the next revalidation (private, max-age=300) fetches the fixed
|
|
1902
|
+
// pixels instead of a 304. Empty only for records published before the
|
|
1903
|
+
// field existed; those keep legacy keys until their next publish.
|
|
1904
|
+
if (product.renderVersion) {
|
|
1905
|
+
urlObj.searchParams.append("pv", product.renderVersion);
|
|
1906
|
+
}
|
|
1748
1907
|
// Operator debug passthrough (ADR-0096): with the 302 retired, the client
|
|
1749
1908
|
// never learns the sealed URL, so the lab's full-waterfall replay re-fetches
|
|
1750
1909
|
// the PUBLIC url with debug=<RENDER_DEBUG_SECRET>. Forward it onto the
|
|
@@ -1764,7 +1923,16 @@ async function handlePublicResolve(
|
|
|
1764
1923
|
// signature" at the box.
|
|
1765
1924
|
sigParams.delete("debug");
|
|
1766
1925
|
const relative = `${urlObj.pathname}?${sigParams.toString()}`;
|
|
1767
|
-
|
|
1926
|
+
// Whole-URL ceiling, checked BEFORE the seal: past ~16 KiB the render box's
|
|
1927
|
+
// HTTP parser answers a bare 431 with no code and no hint (prod probe
|
|
1928
|
+
// 2026-09-06, 7 placements × 1.9 KB asset URLs). Typed here, with the fix.
|
|
1929
|
+
const tooLong = renderUrlLengthError(relative, designElements.length);
|
|
1930
|
+
if (tooLong) {
|
|
1931
|
+
return errResp(414, tooLong, E_RENDER_URL_TOO_LONG);
|
|
1932
|
+
}
|
|
1933
|
+
const tSeal = Date.now();
|
|
1934
|
+
const sig = await mintSeal(relative, signingSecret, env.RENDER_SEAL_PRIVATE_KEY);
|
|
1935
|
+
sealMs = Date.now() - tSeal;
|
|
1768
1936
|
urlObj.searchParams.append("seal", sig);
|
|
1769
1937
|
|
|
1770
1938
|
// 7. Single-leg render (ADR-0096, retired the 302): call the render edge
|
|
@@ -1787,31 +1955,79 @@ async function handlePublicResolve(
|
|
|
1787
1955
|
// overlapping totals make waterfalls unreadable (browser wait then reads:
|
|
1788
1956
|
// transit + rsv_total + edge_total, no envelope arithmetic needed).
|
|
1789
1957
|
const resolverMs = Date.now() - t0;
|
|
1958
|
+
// Forward the CLIENT's cf blob through the service binding: a fresh
|
|
1959
|
+
// Request has NO cf, so without this the render router downstream sees a
|
|
1960
|
+
// geo-less request and can't do proximity routing — which, on the
|
|
1961
|
+
// single-leg path, is EVERY public render (pre-fix they all landed on
|
|
1962
|
+
// whatever box sat first in the RENDER_BOXES KV array; observed as a US
|
|
1963
|
+
// user's renders consistently served from the EU box). The redirect-era
|
|
1964
|
+
// flow never had this problem because the browser hit the edge directly.
|
|
1965
|
+
const tEdge = Date.now();
|
|
1790
1966
|
const edgeRes = await env.RENDER_EDGE.fetch(
|
|
1791
1967
|
new Request(urlObj.toString(), {
|
|
1792
1968
|
method: "GET",
|
|
1793
1969
|
headers: request.headers,
|
|
1794
|
-
|
|
1970
|
+
cf: (request as unknown as { cf?: RequestInitCfProperties }).cf,
|
|
1971
|
+
} as RequestInit)
|
|
1795
1972
|
);
|
|
1973
|
+
// rsv_hop = the service-binding round trip minus the edge's own edge_total:
|
|
1974
|
+
// pure worker-to-worker cost. Measured ~10-15 ms (2026-09-02); merging the
|
|
1975
|
+
// two workers did not remove it (reverted, #2063).
|
|
1976
|
+
const edgeWallMs = Date.now() - tEdge;
|
|
1977
|
+
const edgeTotalMs = Number((/(?:^|[ ,])edge_total;dur=([0-9.]+)/.exec(edgeRes.headers.get("Server-Timing") || "") || [])[1] ?? NaN);
|
|
1978
|
+
const hopMs = Number.isFinite(edgeTotalMs) ? Math.max(0, Math.round(edgeWallMs - edgeTotalMs)) : edgeWallMs;
|
|
1796
1979
|
const headers = new Headers(edgeRes.headers);
|
|
1797
|
-
|
|
1980
|
+
// Revalidation (ADR-0096 amendment, 2026-09-04): the edge stamps the render
|
|
1981
|
+
// key as a strong ETag and answers If-None-Match with a 304 — the browser's
|
|
1982
|
+
// header rides through on `request.headers` above. A 304 is a SUCCESS here:
|
|
1983
|
+
// it must carry the same `private, max-age=300` so the browser extends its
|
|
1984
|
+
// copy's freshness for another five minutes (a `no-store` on a 304 would
|
|
1985
|
+
// poison the stored entry instead). So after the window a page refresh
|
|
1986
|
+
// costs one header-only round trip per image, not a re-download — while
|
|
1987
|
+
// every control point (auth, limits, catalog, DMCA at the edge) still ran.
|
|
1988
|
+
// stale-while-revalidate: past the 5-minute window the browser paints its
|
|
1989
|
+
// cached copy immediately and revalidates in the background, so a
|
|
1990
|
+
// returning visitor never waits on our round trip. The trade, stated: a
|
|
1991
|
+
// catalog fix reaches that visitor on the load AFTER the revalidation, not
|
|
1992
|
+
// the one that triggered it (Kevin 2026-09-04, accepted for instant paint).
|
|
1993
|
+
const edgeOk = edgeRes.ok || edgeRes.status === 304;
|
|
1994
|
+
headers.set("Cache-Control", edgeOk ? "private, max-age=300, stale-while-revalidate=86400" : "no-store");
|
|
1798
1995
|
headers.set("Access-Control-Allow-Origin", "*");
|
|
1799
1996
|
headers.set("Timing-Allow-Origin", "*");
|
|
1997
|
+
// Let browser tooling (the render-speed lab) read box attribution + the
|
|
1998
|
+
// encoder choice off cross-origin responses.
|
|
1999
|
+
headers.set(
|
|
2000
|
+
"Access-Control-Expose-Headers",
|
|
2001
|
+
"ETag, Server-Timing, X-Render-Box, X-Render-Pinned, X-Render-Overflow, X-Encoder"
|
|
2002
|
+
);
|
|
1800
2003
|
headers.append(
|
|
1801
2004
|
"Server-Timing",
|
|
1802
|
-
`rsv_acct;dur=${acctMs}, rsv_limits;dur=${limitsMs}, ` +
|
|
1803
|
-
`rsv_product;dur=${productMs}, rsv_total;dur=${resolverMs}`
|
|
2005
|
+
`rsv_pre;dur=${tEntry ? t0 - tEntry : 0}, rsv_acct;dur=${acctMs}, rsv_sig;dur=${sigMs}, rsv_limits;dur=${limitsMs}${limitsExempt ? ';desc="exempt"' : ""}, ` +
|
|
2006
|
+
`rsv_product;dur=${productMs}, rsv_seal;dur=${sealMs}, rsv_total;dur=${resolverMs}, rsv_hop;dur=${hopMs}, ` +
|
|
2007
|
+
// desc-only: the isolate AGE is not a duration of this request (a dur= here drew a 30-minute bar in the lab)
|
|
2008
|
+
`rsv_iso;desc="${(rsvIsoBorn || (rsvIsoBorn = tEdge, rsvIsoId = crypto.randomUUID().slice(0, 8)), rsvIsoId)} age=${((tEdge - rsvIsoBorn) / 1000).toFixed(1)}s n=${++rsvIsoReqCount}"`
|
|
1804
2009
|
);
|
|
1805
|
-
|
|
2010
|
+
// A 304 has no body by definition; the Response constructor rejects a
|
|
2011
|
+
// stream on a null-body status, so pass null explicitly.
|
|
2012
|
+
return new Response(edgeRes.status === 304 ? null : edgeRes.body, {
|
|
1806
2013
|
status: edgeRes.status,
|
|
1807
2014
|
statusText: edgeRes.statusText,
|
|
1808
2015
|
headers,
|
|
1809
2016
|
});
|
|
1810
2017
|
}
|
|
1811
2018
|
|
|
2019
|
+
// Per-isolate identity for rsv_iso (pairs with the edge's edge_iso: a hop
|
|
2020
|
+
// spike on a young edge isolate is a cold start; on an old one it is the
|
|
2021
|
+
// service-binding dispatch itself).
|
|
2022
|
+
// Initialised on first use: random values/clocks are disallowed in the global scope.
|
|
2023
|
+
let rsvIsoId = ''
|
|
2024
|
+
let rsvIsoBorn = 0
|
|
2025
|
+
let rsvIsoReqCount = 0
|
|
2026
|
+
|
|
1812
2027
|
// Cloudflare Worker entry point
|
|
1813
2028
|
export default {
|
|
1814
2029
|
async fetch(request: Request, env: Env, ctx: any): Promise<Response> {
|
|
2030
|
+
const tEntry = Date.now(); // Server-Timing rsv_pre = worker entry → resolve handler
|
|
1815
2031
|
// SECURITY: the former unauthenticated `/test-kv` debug endpoint was removed.
|
|
1816
2032
|
// It dumped/enumerated/wrote the ACCOUNTS KV (account configs, key hashes,
|
|
1817
2033
|
// L3 secrets) with no auth, live in production. Nothing depends on it; do
|
|
@@ -1824,7 +2040,11 @@ export default {
|
|
|
1824
2040
|
"Access-Control-Allow-Origin": request.headers.get("Origin") || "*",
|
|
1825
2041
|
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
1826
2042
|
"Access-Control-Allow-Headers":
|
|
1827
|
-
"Content-Type, X-API-Key, X-Client-ID",
|
|
2043
|
+
"Content-Type, X-API-Key, X-Client-ID, X-Render-Pin",
|
|
2044
|
+
// Let the browser reuse this preflight verdict for a day: a client
|
|
2045
|
+
// that sends custom headers (X-Client-ID, X-Render-Pin) otherwise
|
|
2046
|
+
// pays an OPTIONS round trip through this worker per render.
|
|
2047
|
+
"Access-Control-Max-Age": "86400",
|
|
1828
2048
|
// Reflected Origin → cache must vary by Origin (see CORS notes above).
|
|
1829
2049
|
Vary: "Origin",
|
|
1830
2050
|
},
|
|
@@ -1876,7 +2096,7 @@ export default {
|
|
|
1876
2096
|
url.pathname.split("/").filter(Boolean)[0]
|
|
1877
2097
|
);
|
|
1878
2098
|
return addCorsHeaders(
|
|
1879
|
-
await handlePublicResolve(request, env, productCode),
|
|
2099
|
+
await handlePublicResolve(request, env, productCode, ctx, tEntry),
|
|
1880
2100
|
request
|
|
1881
2101
|
);
|
|
1882
2102
|
}
|
|
@@ -2016,7 +2236,7 @@ export default {
|
|
|
2016
2236
|
? urlObj.pathname + urlObj.search
|
|
2017
2237
|
: urlObj.toString();
|
|
2018
2238
|
|
|
2019
|
-
const signature = await
|
|
2239
|
+
const signature = await mintSeal(finalUrlToSign, secretKey, env.RENDER_SEAL_PRIVATE_KEY);
|
|
2020
2240
|
|
|
2021
2241
|
// Construct the signed URL by adding the signature parameter
|
|
2022
2242
|
urlObj.searchParams.append("seal", signature);
|