@snowcone-app/mockup-resolver 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@snowcone-app/mockup-resolver",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
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.3.0"
9
+ "@snowcone-app/mockup-url": "0.3.2"
10
10
  },
11
11
  "devDependencies": {
12
12
  "@cloudflare/workers-types": "^4.20250303.0",
@@ -1,70 +1,16 @@
1
1
  /**
2
- * L2 asset-source allowlist (ADR-0076 security ladder) — pure module so the
3
- * default `pnpm test` glob can unit-test it (src/index.ts imports
4
- * `cloudflare:workers` and only loads inside the Workers runtime).
2
+ * L2 asset-source allowlist (ADR-0076 security ladder).
3
+ *
4
+ * The implementation moved to `@snowcone-app/mockup-url/asset-allowlist` so
5
+ * the backend publish/listing guard enforces the EXACT same origin-matching
6
+ * as this worker (QA finding 0013: a published design whose asset origin
7
+ * fails this check renders a blank catalog card; the guard refuses it at
8
+ * publish time instead). This module stays as the worker-local entry point —
9
+ * src/index.ts and the unit tests import from here.
5
10
  */
6
-
7
- // Helper function to convert glob-like pattern to RegExp
8
- export function globToRegExp(glob: string): RegExp {
9
- let regexString = "^";
10
- for (let i = 0; i < glob.length; i++) {
11
- const char = glob[i];
12
- if (char === "*") {
13
- regexString += ".*?"; // Non-greedy match for any characters
14
- } else if (/[.+\[\]?^${}()|\-\\]/.test(char)) {
15
- // Corrected regex for special characters
16
- regexString += "\\" + char; // Escape them
17
- } else {
18
- regexString += char;
19
- }
20
- }
21
- regexString += "$";
22
- return new RegExp(regexString, "i"); // Added 'i' flag for case-insensitive matching
23
- }
24
-
25
- /** Check a hostname against a glob allowlist (reuses globToRegExp). */
26
- export function isHostAllowed(host: string, allowlist: string[]): boolean {
27
- if (allowlist.length === 0) return true; // unset = any
28
- for (const pattern of allowlist) {
29
- if (pattern === "*") return true;
30
- try {
31
- if (globToRegExp(pattern).test(host)) return true;
32
- } catch {
33
- // skip malformed pattern
34
- }
35
- }
36
- return false;
37
- }
38
-
39
- export type AssetAllowlistVerdict =
40
- | { ok: true }
41
- | { ok: false; status: 400 | 403; message: string };
42
-
43
- /**
44
- * Run the L2 check over every developer-supplied image URL. No origin is ever
45
- * exempt: catalog designs render by reference (`design=`, ADR-0086) with
46
- * resolver-injected components, so they never pass through this check — the
47
- * old EXEMPT_ASSET_ORIGINS escape hatch is gone.
48
- */
49
- export function checkAssetUrls(
50
- imageUrls: string[],
51
- allowlist: string[] | undefined
52
- ): AssetAllowlistVerdict {
53
- if (!allowlist || allowlist.length === 0) return { ok: true };
54
- for (const imageUrl of imageUrls) {
55
- let assetHost: string;
56
- try {
57
- assetHost = new URL(imageUrl).hostname;
58
- } catch {
59
- return { ok: false, status: 400, message: "Invalid asset URL" };
60
- }
61
- if (!isHostAllowed(assetHost, allowlist)) {
62
- return {
63
- ok: false,
64
- status: 403,
65
- message: "Asset source not allowed for this shop",
66
- };
67
- }
68
- }
69
- return { ok: true };
70
- }
11
+ export {
12
+ globToRegExp,
13
+ isHostAllowed,
14
+ checkAssetUrls,
15
+ type AssetAllowlistVerdict,
16
+ } from "@snowcone-app/mockup-url/asset-allowlist";
package/src/index.ts CHANGED
@@ -31,11 +31,25 @@ interface RateLimiterStub extends DurableObjectStub {
31
31
  currentCount?: number;
32
32
  dailyLimit?: number;
33
33
  }>;
34
+ checkPublicLimits(
35
+ requestsPerSecond: number,
36
+ dailyMaxRequests: number
37
+ ): Promise<{
38
+ allowed: boolean;
39
+ scope?: "second" | "day";
40
+ retryAfter?: number;
41
+ currentCount?: number;
42
+ dailyLimit?: number;
43
+ }>;
34
44
  }
35
45
 
36
46
  // Interface for environment bindings
37
47
  interface Env {
38
48
  URL_SIGNING_SECRET: string;
49
+ /** ADR-0096: service binding to the render edge (mockup-edge-cache) — the
50
+ * resolver calls it in-process after sealing and streams bytes back.
51
+ * One client leg; the 302 hop is retired. */
52
+ RENDER_EDGE: Fetcher;
39
53
  ACCOUNTS: KVNamespace; // Single KV store for all account data
40
54
  API_RATE_LIMITER: {
41
55
  idFromName(name: string): DurableObjectId;
@@ -298,6 +312,40 @@ export class RateLimiter extends DurableObject {
298
312
  dailyLimit: dailyMaxRequests,
299
313
  };
300
314
  }
315
+
316
+ /**
317
+ * Per-second + daily check in ONE DO round-trip. The resolver used to
318
+ * await checkRateLimit() then checkDailyRateLimit() back-to-back — two
319
+ * cross-region RPCs to this same object on every public request. Same
320
+ * semantics as the sequential pair (per-second slot is consumed even
321
+ * when the daily check then blocks, matching the old call order).
322
+ */
323
+ async checkPublicLimits(
324
+ requestsPerSecond: number,
325
+ dailyMaxRequests: number
326
+ ): Promise<{
327
+ allowed: boolean;
328
+ scope?: "second" | "day";
329
+ retryAfter?: number;
330
+ currentCount?: number;
331
+ dailyLimit?: number;
332
+ }> {
333
+ const perSec = await this.checkRateLimit(requestsPerSecond);
334
+ if (!perSec.allowed) {
335
+ return { allowed: false, scope: "second", retryAfter: perSec.retryAfter };
336
+ }
337
+ const daily = await this.checkDailyRateLimit(dailyMaxRequests);
338
+ if (!daily.allowed) {
339
+ return {
340
+ allowed: false,
341
+ scope: "day",
342
+ retryAfter: daily.retryAfter,
343
+ currentCount: daily.currentCount,
344
+ dailyLimit: daily.dailyLimit,
345
+ };
346
+ }
347
+ return { allowed: true };
348
+ }
301
349
  }
302
350
 
303
351
  // Helper function to add CORS headers to a response
@@ -348,6 +396,42 @@ async function hashApiKey(apiKey: string): Promise<string> {
348
396
  }
349
397
 
350
398
  // Authentication middleware
399
+ /**
400
+ * Per-isolate burst absorber for the public rate-limit DO (ADR-0096).
401
+ *
402
+ * A Durable Object is single-threaded per key, so N parallel renders from
403
+ * one IP serialize N RPCs (~100ms each — measured as the lab's ~600ms
404
+ * "queued" at 5-way concurrency). After one ALLOWED verdict we grant up to
405
+ * the per-second limit locally for the rest of that 1s window and fire the
406
+ * DO check asynchronously (fire-and-forget: its side effect is the counter
407
+ * increment). Enforcement slack is bounded by one window per isolate —
408
+ * invisible at a 20rps limit — while burst latency drops to ~0. A DENIED
409
+ * verdict is cached for its window too, so hammering stays cheap.
410
+ */
411
+ const publicLimitBurstCache = new Map<
412
+ string,
413
+ { windowEnd: number; used: number; allowed: boolean }
414
+ >();
415
+
416
+ /** grant = allowed locally (skip the DO await); deny = cached denial;
417
+ * miss = no fresh window — do the authoritative DO round-trip. */
418
+ function burstAllow(key: string, rps: number): "grant" | "deny" | "miss" {
419
+ const entry = publicLimitBurstCache.get(key);
420
+ const nowMs = Date.now();
421
+ if (!entry || nowMs >= entry.windowEnd) return "miss";
422
+ if (!entry.allowed) return "deny";
423
+ if (entry.used < rps) {
424
+ entry.used++;
425
+ return "grant";
426
+ }
427
+ return "miss";
428
+ }
429
+
430
+ function burstRecord(key: string, allowed: boolean): void {
431
+ if (publicLimitBurstCache.size > 10_000) publicLimitBurstCache.clear();
432
+ publicLimitBurstCache.set(key, { windowEnd: Date.now() + 1000, used: 1, allowed });
433
+ }
434
+
351
435
  async function authenticate(
352
436
  request: Request,
353
437
  env: Env
@@ -685,37 +769,53 @@ async function authenticate(
685
769
  );
686
770
  const globalRateLimiter = env.API_RATE_LIMITER.get(globalRateLimiterId);
687
771
 
688
- // Check global per-second IP rate limit
689
- const globalPerSecondRateLimitResult =
690
- await globalRateLimiter.checkRateLimit(GLOBAL_IP_RATE_LIMIT_RPS);
772
+ // Burst absorber: same-window repeats from this isolate skip the
773
+ // serialized DO round-trip (see publicLimitBurstCache doc). Grants do
774
+ // NOT return early — the account-specific limit below still applies.
775
+ const globalBurstKey = `g:${clientIp}`;
776
+ const globalGrant = burstAllow(globalBurstKey, GLOBAL_IP_RATE_LIMIT_RPS);
777
+ let globalVerdict: Awaited<ReturnType<RateLimiterStub["checkPublicLimits"]>>;
778
+ if (globalGrant === "grant") {
779
+ // Record the hit in the DO without waiting on it — the RPC's side
780
+ // effect is the per-second/daily counter increment.
781
+ void globalRateLimiter
782
+ .checkPublicLimits(GLOBAL_IP_RATE_LIMIT_RPS, GLOBAL_DAILY_IP_RATE_LIMIT)
783
+ .catch(() => {});
784
+ globalVerdict = { allowed: true } as Awaited<
785
+ ReturnType<RateLimiterStub["checkPublicLimits"]>
786
+ >;
787
+ } else if (globalGrant === "deny") {
788
+ globalVerdict = { allowed: false, scope: "second", retryAfter: 1000 } as Awaited<
789
+ ReturnType<RateLimiterStub["checkPublicLimits"]>
790
+ >;
791
+ } else {
792
+ // Per-second + daily in ONE DO round-trip (was two sequential RPCs to
793
+ // the same object — pure added latency on every public request).
794
+ globalVerdict = await globalRateLimiter.checkPublicLimits(
795
+ GLOBAL_IP_RATE_LIMIT_RPS,
796
+ GLOBAL_DAILY_IP_RATE_LIMIT
797
+ );
798
+ burstRecord(globalBurstKey, globalVerdict.allowed);
799
+ }
691
800
 
692
- if (!globalPerSecondRateLimitResult.allowed) {
801
+ if (!globalVerdict.allowed && globalVerdict.scope === "second") {
693
802
  console.log(
694
803
  `❌ Global IP per-second rate limit exceeded for IP: ${clientIp}`
695
804
  );
696
805
  return {
697
806
  authenticated: false,
698
807
  error: `Global per-second rate limit exceeded. Try again in ${Math.ceil(
699
- globalPerSecondRateLimitResult.retryAfter! / 1000
808
+ globalVerdict.retryAfter! / 1000
700
809
  )} seconds`,
701
810
  };
702
811
  }
703
- console.log(
704
- `✅ Global IP per-second rate limit check passed for IP: ${clientIp}`
705
- );
706
-
707
- // Check global daily IP rate limit
708
- const dailyRateLimitResult = await globalRateLimiter.checkDailyRateLimit(
709
- GLOBAL_DAILY_IP_RATE_LIMIT
710
- );
711
-
712
- if (!dailyRateLimitResult.allowed) {
812
+ if (!globalVerdict.allowed) {
713
813
  console.log(
714
- `❌ Global daily IP rate limit exceeded for IP: ${clientIp}. Count: ${dailyRateLimitResult.currentCount}/${dailyRateLimitResult.dailyLimit}`
814
+ `❌ Global daily IP rate limit exceeded for IP: ${clientIp}. Count: ${globalVerdict.currentCount}/${globalVerdict.dailyLimit}`
715
815
  );
716
816
  let retryMessage = "Global daily rate limit exceeded.";
717
- if (dailyRateLimitResult.retryAfter) {
718
- const totalSeconds = Math.floor(dailyRateLimitResult.retryAfter / 1000);
817
+ if (globalVerdict.retryAfter) {
818
+ const totalSeconds = Math.floor(globalVerdict.retryAfter / 1000);
719
819
  const hours = Math.floor(totalSeconds / 3600);
720
820
  const minutes = Math.floor((totalSeconds % 3600) / 60);
721
821
  retryMessage += ` Try again in approximately ${hours}h ${minutes}m.`;
@@ -726,7 +826,7 @@ async function authenticate(
726
826
  };
727
827
  }
728
828
  console.log(
729
- `✅ Global daily IP rate limit check passed for IP: ${clientIp}. Count: ${dailyRateLimitResult.currentCount}/${dailyRateLimitResult.dailyLimit}`
829
+ `✅ Global IP rate limit checks passed for IP: ${clientIp}`
730
830
  );
731
831
  } catch (error) {
732
832
  console.error(
@@ -746,10 +846,28 @@ async function authenticate(
746
846
  );
747
847
  const rateLimiter = env.API_RATE_LIMITER.get(rateLimiterId);
748
848
 
749
- // Call the method directly on the Durable Object via RPC
750
- const result = await rateLimiter.checkRateLimit(
751
- accountData.public.rateLimit
849
+ // Same burst absorber as the global limiter: the account DO is the
850
+ // SECOND serialized RPC on this path — under N-way one-IP bursts the
851
+ // two together were the lab's ~600ms "queued".
852
+ const acctBurstKey = `${accountId}:${clientIp}`;
853
+ const acctRps = Math.max(
854
+ 1,
855
+ Number((accountData.public.rateLimit as { requestsPerSecond?: number }).requestsPerSecond) || 5
752
856
  );
857
+ const acctGrant = burstAllow(acctBurstKey, acctRps);
858
+ let result: Awaited<ReturnType<RateLimiterStub["checkRateLimit"]>>;
859
+ if (acctGrant === "grant") {
860
+ void rateLimiter.checkRateLimit(accountData.public.rateLimit).catch(() => {});
861
+ result = { allowed: true } as Awaited<ReturnType<RateLimiterStub["checkRateLimit"]>>;
862
+ } else if (acctGrant === "deny") {
863
+ result = { allowed: false, retryAfter: 1000 } as Awaited<
864
+ ReturnType<RateLimiterStub["checkRateLimit"]>
865
+ >;
866
+ } else {
867
+ // Call the method directly on the Durable Object via RPC
868
+ result = await rateLimiter.checkRateLimit(accountData.public.rateLimit);
869
+ burstRecord(acctBurstKey, result.allowed);
870
+ }
753
871
 
754
872
  if (!result.allowed) {
755
873
  console.log(`❌ Rate limit exceeded for IP: ${clientIp}`);
@@ -936,6 +1054,12 @@ async function handleMockupUrl(request: Request, env: Env): Promise<Response> {
936
1054
  const urlObj = new URL(unsigned);
937
1055
  const sigParams = new URLSearchParams(urlObj.search);
938
1056
  sigParams.delete("seal");
1057
+ // Mirror the BOX's sealed canonical exactly (rendercenter url-verifier
1058
+ // deletes BOTH seal and debug before verifying — debug is observability
1059
+ // transport appended to already-sealed URLs since long before ADR-0096).
1060
+ // Signing WITH debug included made every debug render 401 "Invalid URL
1061
+ // signature" at the box.
1062
+ sigParams.delete("debug");
939
1063
  const relative = `${urlObj.pathname}?${sigParams.toString()}`;
940
1064
  const sig = await signUrl(relative, signingSecret);
941
1065
  urlObj.searchParams.append("seal", sig);
@@ -1105,6 +1229,7 @@ async function handlePublicResolve(
1105
1229
  }
1106
1230
  );
1107
1231
 
1232
+ const t0 = Date.now(); // Server-Timing base — emitted on the success 302
1108
1233
  const reqUrl = new URL(request.url);
1109
1234
  const q = reqUrl.searchParams;
1110
1235
 
@@ -1195,7 +1320,9 @@ async function handlePublicResolve(
1195
1320
  if (!key) return errResp(400, "Missing required query param: shop");
1196
1321
 
1197
1322
  // 1. Shop ID lookup → AccountData (404 unknown, 403 revoked).
1323
+ const tAcct = Date.now();
1198
1324
  const account = await loadAccountByKey(key, env);
1325
+ const acctMs = Date.now() - tAcct;
1199
1326
  if (!account) return errResp(404, "Unknown shop");
1200
1327
  if (account.revoked) return errResp(403, "Shop revoked");
1201
1328
 
@@ -1254,60 +1381,20 @@ async function handlePublicResolve(
1254
1381
  if (!ok) return errResp(403, "Invalid signature: s");
1255
1382
  }
1256
1383
 
1257
- // 3. Rate limit — reuse the existing per-account/IP public limiter.
1384
+ // 3+4. Rate limits and product fetch, OVERLAPPED. Each limiter DO lives in
1385
+ // exactly one location, so awaiting them serially stacked up to three
1386
+ // cross-region round-trips ahead of the redirect (~200ms warm, plus
1387
+ // hibernation wake when cold — the docs-click latency). Now the global
1388
+ // per-second + daily checks share ONE RPC (checkPublicLimits), the
1389
+ // per-account limiter runs in parallel with it, and the read-only product
1390
+ // fetch starts concurrently so its latency hides behind the DO hop.
1391
+ // Enforcement is unchanged: every limit verdict is awaited before any
1392
+ // response is built; when a limit blocks, the product result is discarded.
1258
1393
  const clientIp =
1259
1394
  request.headers.get("CF-Connecting-IP") ||
1260
1395
  request.headers.get("X-Forwarded-For") ||
1261
1396
  "unknown-ip";
1262
- // Global IP guard (same caps as authenticate()'s public path).
1263
- try {
1264
- const globalRl = env.API_RATE_LIMITER.get(
1265
- env.API_RATE_LIMITER.idFromName(`global:public:${clientIp}`)
1266
- );
1267
- const perSec = await globalRl.checkRateLimit(20);
1268
- if (!perSec.allowed) {
1269
- const resp = errResp(429, "Rate limit exceeded");
1270
- resp.headers.set(
1271
- "Retry-After",
1272
- String(Math.ceil((perSec.retryAfter ?? 1000) / 1000))
1273
- );
1274
- return resp;
1275
- }
1276
- const daily = await globalRl.checkDailyRateLimit(50000);
1277
- if (!daily.allowed) {
1278
- const resp = errResp(429, "Daily rate limit exceeded");
1279
- if (daily.retryAfter) {
1280
- resp.headers.set(
1281
- "Retry-After",
1282
- String(Math.ceil(daily.retryAfter / 1000))
1283
- );
1284
- }
1285
- return resp;
1286
- }
1287
- } catch (e) {
1288
- console.error(`Public resolve: global rate-limit error (fail open): ${e}`);
1289
- }
1290
- // Per-account public rate limit, if configured.
1291
- if (account.public?.rateLimit) {
1292
- try {
1293
- const acctRl = env.API_RATE_LIMITER.get(
1294
- env.API_RATE_LIMITER.idFromName(`${accountId}:public:${clientIp}`)
1295
- );
1296
- const result = await acctRl.checkRateLimit(account.public.rateLimit);
1297
- if (!result.allowed) {
1298
- const resp = errResp(429, "Rate limit exceeded");
1299
- resp.headers.set(
1300
- "Retry-After",
1301
- String(Math.ceil((result.retryAfter ?? 1000) / 1000))
1302
- );
1303
- return resp;
1304
- }
1305
- } catch (e) {
1306
- console.error(`Public resolve: account rate-limit error (fail open): ${e}`);
1307
- }
1308
- }
1309
1397
 
1310
- // 4. Resolve catalog config (Meilisearch, KV-cached).
1311
1398
  const meiliHost = env.MEILISEARCH_HOST;
1312
1399
  const meiliKey = env.MEILISEARCH_API_KEY;
1313
1400
  const meiliIndex = env.MEILISEARCH_INDEX;
@@ -1315,12 +1402,79 @@ async function handlePublicResolve(
1315
1402
  if (!meiliHost || !meiliKey || !meiliIndex || !mockupBaseUrl) {
1316
1403
  return errResp(500, "Resolver not configured");
1317
1404
  }
1318
- const product = await fetchProduct(
1405
+
1406
+ const tLimits = Date.now();
1407
+ const productPromise = fetchProduct(
1319
1408
  productCode,
1320
1409
  { host: meiliHost, apiKey: meiliKey, index: meiliIndex },
1321
1410
  env.ACCOUNTS
1322
1411
  );
1412
+ // Detached guard: when a limit blocks below, this promise is never awaited —
1413
+ // without a no-op catch, a fetch failure there would surface as an unhandled
1414
+ // rejection. The real `await productPromise` further down still rethrows.
1415
+ productPromise.catch(() => {});
1416
+
1417
+ type LimitVerdict = {
1418
+ allowed: boolean;
1419
+ scope?: "second" | "day";
1420
+ retryAfter?: number;
1421
+ };
1422
+ const globalCheck: Promise<LimitVerdict> = (async () => {
1423
+ try {
1424
+ const globalRl = env.API_RATE_LIMITER.get(
1425
+ env.API_RATE_LIMITER.idFromName(`global:public:${clientIp}`)
1426
+ );
1427
+ return await globalRl.checkPublicLimits(20, 50000);
1428
+ } catch (e) {
1429
+ console.error(`Public resolve: global rate-limit error (fail open): ${e}`);
1430
+ return { allowed: true };
1431
+ }
1432
+ })();
1433
+ const acctCheck: Promise<LimitVerdict> = (async () => {
1434
+ if (!account.public?.rateLimit) return { allowed: true };
1435
+ try {
1436
+ const acctRl = env.API_RATE_LIMITER.get(
1437
+ env.API_RATE_LIMITER.idFromName(`${accountId}:public:${clientIp}`)
1438
+ );
1439
+ return await acctRl.checkRateLimit(account.public.rateLimit);
1440
+ } catch (e) {
1441
+ console.error(`Public resolve: account rate-limit error (fail open): ${e}`);
1442
+ return { allowed: true };
1443
+ }
1444
+ })();
1445
+ const [globalVerdict, acctVerdict] = await Promise.all([
1446
+ globalCheck,
1447
+ acctCheck,
1448
+ ]);
1449
+ if (!globalVerdict.allowed) {
1450
+ const resp = errResp(
1451
+ 429,
1452
+ globalVerdict.scope === "day"
1453
+ ? "Daily rate limit exceeded"
1454
+ : "Rate limit exceeded"
1455
+ );
1456
+ if (globalVerdict.retryAfter) {
1457
+ resp.headers.set(
1458
+ "Retry-After",
1459
+ String(Math.ceil(globalVerdict.retryAfter / 1000))
1460
+ );
1461
+ }
1462
+ return resp;
1463
+ }
1464
+ if (!acctVerdict.allowed) {
1465
+ const resp = errResp(429, "Rate limit exceeded");
1466
+ resp.headers.set(
1467
+ "Retry-After",
1468
+ String(Math.ceil((acctVerdict.retryAfter ?? 1000) / 1000))
1469
+ );
1470
+ return resp;
1471
+ }
1472
+ const limitsMs = Date.now() - tLimits;
1473
+
1474
+ const tProduct = Date.now();
1475
+ const product = await productPromise;
1323
1476
  if (!product) return errResp(404, `Product not found: ${productCode}`);
1477
+ const productMs = Date.now() - tProduct;
1324
1478
 
1325
1479
  // 4-design. Resolve the catalog reference (ADR-0086). Membership in the
1326
1480
  // designs index IS the license check — a miss is a loud 404, never a
@@ -1501,64 +1655,77 @@ async function handlePublicResolve(
1501
1655
  if (catalogDesign) {
1502
1656
  urlObj.searchParams.append("catalog", catalogDesign.pairingId);
1503
1657
  }
1658
+ // Operator debug passthrough (ADR-0096): with the 302 retired, the client
1659
+ // never learns the sealed URL, so the lab's full-waterfall replay re-fetches
1660
+ // the PUBLIC url with debug=<RENDER_DEBUG_SECRET>. Forward it onto the
1661
+ // sealed URL — INSIDE the signature (appended before signing), so seal
1662
+ // verification still holds — and the render edge/box gate it exactly as
1663
+ // before (wrong value = no stages, edge debug-branch bypasses R2).
1664
+ const debugParam = q.get("debug");
1665
+ if (debugParam) {
1666
+ urlObj.searchParams.append("debug", debugParam);
1667
+ }
1504
1668
  const sigParams = new URLSearchParams(urlObj.search);
1505
1669
  sigParams.delete("seal");
1670
+ // Mirror the BOX's sealed canonical exactly (rendercenter url-verifier
1671
+ // deletes BOTH seal and debug before verifying — debug is observability
1672
+ // transport appended to already-sealed URLs since long before ADR-0096).
1673
+ // Signing WITH debug included made every debug render 401 "Invalid URL
1674
+ // signature" at the box.
1675
+ sigParams.delete("debug");
1506
1676
  const relative = `${urlObj.pathname}?${sigParams.toString()}`;
1507
1677
  const sig = await signUrl(relative, signingSecret);
1508
1678
  urlObj.searchParams.append("seal", sig);
1509
1679
 
1510
- // 7. 302 to the relay-signed render URL, no-store on the REDIRECT.
1511
- return new Response(null, {
1512
- status: 302,
1513
- headers: {
1514
- Location: urlObj.toString(),
1515
- ...NO_STORE,
1516
- },
1680
+ // 7. Single-leg render (ADR-0096, retired the 302): call the render edge
1681
+ // over the service binding with the sealed URL and stream its bytes back.
1682
+ // Worker-to-worker on Cloudflare's backbone — no second client RTT, no
1683
+ // second TLS handshake, no redirect processing. The edge still verifies
1684
+ // the seal, DMCA deny-set and cache exactly as if the browser had fetched
1685
+ // the sealed URL itself.
1686
+ //
1687
+ // Cache semantics: the OLD 302 was `private, max-age=300` so a browser
1688
+ // re-resolved (revocation / key rotation / catalog edits) within 5
1689
+ // minutes, while the sealed CDN response stayed immutable. The single-leg
1690
+ // response answers on the PUBLIC url, so it must keep the resolver-layer
1691
+ // semantics — override the edge's immutable header with the redirect-era
1692
+ // policy. rsv_* Server-Timing entries expose the resolver's own stages
1693
+ // next to the edge/box entries (acct = KV/backend account load, limits =
1694
+ // rate-limit verdict, product = catalog fetch).
1695
+ // rsv_total = the resolver's OWN work only (auth, limits, product, seal),
1696
+ // captured BEFORE the edge call — the edge stamps edge_total itself, and
1697
+ // overlapping totals make waterfalls unreadable (browser wait then reads:
1698
+ // transit + rsv_total + edge_total, no envelope arithmetic needed).
1699
+ const resolverMs = Date.now() - t0;
1700
+ const edgeRes = await env.RENDER_EDGE.fetch(
1701
+ new Request(urlObj.toString(), {
1702
+ method: "GET",
1703
+ headers: request.headers,
1704
+ })
1705
+ );
1706
+ const headers = new Headers(edgeRes.headers);
1707
+ headers.set("Cache-Control", edgeRes.ok ? "private, max-age=300" : "no-store");
1708
+ headers.set("Access-Control-Allow-Origin", "*");
1709
+ headers.set("Timing-Allow-Origin", "*");
1710
+ headers.append(
1711
+ "Server-Timing",
1712
+ `rsv_acct;dur=${acctMs}, rsv_limits;dur=${limitsMs}, ` +
1713
+ `rsv_product;dur=${productMs}, rsv_total;dur=${resolverMs}`
1714
+ );
1715
+ return new Response(edgeRes.body, {
1716
+ status: edgeRes.status,
1717
+ statusText: edgeRes.statusText,
1718
+ headers,
1517
1719
  });
1518
1720
  }
1519
1721
 
1520
1722
  // Cloudflare Worker entry point
1521
1723
  export default {
1522
1724
  async fetch(request: Request, env: Env, ctx: any): Promise<Response> {
1523
- // Add test endpoint
1524
- const requestUrl = new URL(request.url);
1525
- if (requestUrl.pathname === "/test-kv") {
1526
- try {
1527
- // Try to write a test key
1528
- await env.ACCOUNTS.put("test-key", "test-value");
1529
-
1530
- // Try to read all keys
1531
- const keys = await env.ACCOUNTS.list();
1532
-
1533
- // Try to read our test key
1534
- const testValue = await env.ACCOUNTS.get("test-key");
1535
-
1536
- // Try to read account123
1537
- const account123 = await env.ACCOUNTS.get("account123");
1538
-
1539
- return new Response(
1540
- JSON.stringify({
1541
- testWrite: "success",
1542
- testRead: testValue,
1543
- keys: keys,
1544
- account123: account123,
1545
- }),
1546
- {
1547
- headers: { "Content-Type": "application/json" },
1548
- }
1549
- );
1550
- } catch (error: any) {
1551
- return new Response(
1552
- JSON.stringify({
1553
- error: `KV test failed: ${error.message || String(error)}`,
1554
- }),
1555
- {
1556
- status: 500,
1557
- headers: { "Content-Type": "application/json" },
1558
- }
1559
- );
1560
- }
1561
- }
1725
+ // SECURITY: the former unauthenticated `/test-kv` debug endpoint was removed.
1726
+ // It dumped/enumerated/wrote the ACCOUNTS KV (account configs, key hashes,
1727
+ // L3 secrets) with no auth, live in production. Nothing depends on it; do
1728
+ // not reintroduce a KV-dumping route without auth + a non-prod gate.
1562
1729
 
1563
1730
  // Handle CORS preflight
1564
1731
  if (request.method === "OPTIONS") {
@@ -1662,6 +1829,37 @@ export default {
1662
1829
  const accountId = authResult.accountId!;
1663
1830
 
1664
1831
  if (url.pathname === "/sign") {
1832
+ // SECURITY: /sign mints the internal RELAY `seal` (URL_SIGNING_SECRET)
1833
+ // that rendercenter trusts — the SAME credential handlePublicResolve
1834
+ // produces only AFTER the L2 asset-origin allowlist and L3 requireSig
1835
+ // checks. Signing here does NOT re-run those checks (an authenticated
1836
+ // integrator is trusted to sign its own renders, like /mockups/url), so
1837
+ // this endpoint must never be reachable with only a PUBLIC shop id —
1838
+ // otherwise it is an open signing oracle that launders a disallowed
1839
+ // origin/host past L2/L3. Require a real API-key credential: with the
1840
+ // x-api-key header present, authenticate() above took Method 1 (hash +
1841
+ // 'mockups' scope, validated against THIS shop) — the rate-limited
1842
+ // public fallback (Method 2) can no longer satisfy /sign.
1843
+ //
1844
+ // Gated to production the same way handleMockupUrl/loadAccountByKey are:
1845
+ // local dev runs with the 'dev-unsigned' secret (seals are worthless
1846
+ // off-box) and has no provisioned API keys, so the dev flow is unchanged.
1847
+ const isDevUnsigned =
1848
+ !env.URL_SIGNING_SECRET || env.URL_SIGNING_SECRET === "dev-unsigned";
1849
+ if (!isDevUnsigned && !request.headers.get("x-api-key")) {
1850
+ const errorResponse = new Response(
1851
+ JSON.stringify({
1852
+ error:
1853
+ "The /sign endpoint requires an API key with the 'mockups' scope (X-API-Key header). A public shop id is not sufficient.",
1854
+ }),
1855
+ {
1856
+ status: 401,
1857
+ headers: { "Content-Type": "application/json" },
1858
+ }
1859
+ );
1860
+ return addCorsHeaders(errorResponse, request);
1861
+ }
1862
+
1665
1863
  // Get the URL to sign from the query parameter
1666
1864
  let urlToSign = url.searchParams.get("url");
1667
1865
  let isRelativeUrl = false;
@@ -20,7 +20,15 @@ import {
20
20
  * (4 different `view=` values → 4 identical images). Pre-launch, fail loudly.
21
21
  */
22
22
  export function rejectUnknownPublicParams(url: URL): Response | null {
23
- const unknown = unknownPublicParams(url.searchParams);
23
+ const unknown = unknownPublicParams(url.searchParams).filter(
24
+ // Operator debug passthrough (ADR-0096): `debug=<RENDER_DEBUG_SECRET>`
25
+ // is transport, not public grammar — with the 302 retired, waterfall
26
+ // replays re-fetch the PUBLIC url, so the resolver must accept the
27
+ // param (it forwards it under the seal; the render box gates its
28
+ // value). Deliberately NOT added to mockup-url's PARAMS: it is an
29
+ // operator surface, not part of the developer contract.
30
+ (p) => p !== "debug",
31
+ );
24
32
  if (unknown.length === 0) return null;
25
33
  return new Response(
26
34
  JSON.stringify({ error: unknownPublicParamsMessage(unknown) }),