@snowcone-app/mockup-resolver 1.0.3 → 1.0.5

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/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
@@ -316,6 +364,15 @@ function addCorsHeaders(response: Response, request: Request): Response {
316
364
  "Access-Control-Allow-Headers",
317
365
  "Content-Type, X-API-Key, X-Client-ID"
318
366
  );
367
+ // This reflects the request Origin into ACAO, so shared caches MUST key on
368
+ // Origin — otherwise a cached entry for origin A (or a no-Origin request) is
369
+ // replayed to origin B and the crossorigin <img> fails (CORS poisoning).
370
+ // Preserve any upstream Vary rather than clobbering it.
371
+ const prevVary = corsResponse.headers.get("Vary");
372
+ corsResponse.headers.set(
373
+ "Vary",
374
+ prevVary && !/\borigin\b/i.test(prevVary) ? `${prevVary}, Origin` : prevVary || "Origin"
375
+ );
319
376
 
320
377
  return corsResponse;
321
378
  }
@@ -339,6 +396,42 @@ async function hashApiKey(apiKey: string): Promise<string> {
339
396
  }
340
397
 
341
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
+
342
435
  async function authenticate(
343
436
  request: Request,
344
437
  env: Env
@@ -676,37 +769,53 @@ async function authenticate(
676
769
  );
677
770
  const globalRateLimiter = env.API_RATE_LIMITER.get(globalRateLimiterId);
678
771
 
679
- // Check global per-second IP rate limit
680
- const globalPerSecondRateLimitResult =
681
- 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
+ }
682
800
 
683
- if (!globalPerSecondRateLimitResult.allowed) {
801
+ if (!globalVerdict.allowed && globalVerdict.scope === "second") {
684
802
  console.log(
685
803
  `❌ Global IP per-second rate limit exceeded for IP: ${clientIp}`
686
804
  );
687
805
  return {
688
806
  authenticated: false,
689
807
  error: `Global per-second rate limit exceeded. Try again in ${Math.ceil(
690
- globalPerSecondRateLimitResult.retryAfter! / 1000
808
+ globalVerdict.retryAfter! / 1000
691
809
  )} seconds`,
692
810
  };
693
811
  }
694
- console.log(
695
- `✅ Global IP per-second rate limit check passed for IP: ${clientIp}`
696
- );
697
-
698
- // Check global daily IP rate limit
699
- const dailyRateLimitResult = await globalRateLimiter.checkDailyRateLimit(
700
- GLOBAL_DAILY_IP_RATE_LIMIT
701
- );
702
-
703
- if (!dailyRateLimitResult.allowed) {
812
+ if (!globalVerdict.allowed) {
704
813
  console.log(
705
- `❌ 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}`
706
815
  );
707
816
  let retryMessage = "Global daily rate limit exceeded.";
708
- if (dailyRateLimitResult.retryAfter) {
709
- const totalSeconds = Math.floor(dailyRateLimitResult.retryAfter / 1000);
817
+ if (globalVerdict.retryAfter) {
818
+ const totalSeconds = Math.floor(globalVerdict.retryAfter / 1000);
710
819
  const hours = Math.floor(totalSeconds / 3600);
711
820
  const minutes = Math.floor((totalSeconds % 3600) / 60);
712
821
  retryMessage += ` Try again in approximately ${hours}h ${minutes}m.`;
@@ -717,7 +826,7 @@ async function authenticate(
717
826
  };
718
827
  }
719
828
  console.log(
720
- `✅ 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}`
721
830
  );
722
831
  } catch (error) {
723
832
  console.error(
@@ -737,10 +846,28 @@ async function authenticate(
737
846
  );
738
847
  const rateLimiter = env.API_RATE_LIMITER.get(rateLimiterId);
739
848
 
740
- // Call the method directly on the Durable Object via RPC
741
- const result = await rateLimiter.checkRateLimit(
742
- 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
743
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
+ }
744
871
 
745
872
  if (!result.allowed) {
746
873
  console.log(`❌ Rate limit exceeded for IP: ${clientIp}`);
@@ -776,13 +903,14 @@ import { fetchDesign } from "./design-ref";
776
903
  import {
777
904
  buildMockupUrl,
778
905
  canonicalForSig,
906
+ normalizeBgColor,
779
907
  signDevSig,
780
908
  parsePublicUrl,
781
909
  PARAMS,
782
910
  type DesignElement,
783
- type ImageAlignment,
784
911
  } from "@snowcone-app/mockup-url";
785
912
  import {
913
+ assembleArtwork,
786
914
  fetchProduct,
787
915
  looksLikeResolveRequest,
788
916
  resolveAlbumPagePlacement,
@@ -1083,12 +1211,19 @@ async function handlePublicResolve(
1083
1211
  // for invalidation + per-request auth/rate (ADR-0076 §7). 4xx must never be
1084
1212
  // cached as the image.
1085
1213
  const NO_STORE = { "Cache-Control": "no-store" } as const;
1086
- const errResp = (status: number, message: string): Response =>
1087
- new Response(JSON.stringify({ error: message }), {
1088
- status,
1089
- headers: { "Content-Type": "application/json", ...NO_STORE },
1090
- });
1214
+ // `code` is a stable machine-readable error code (the `E_*` family, ADR-0089 /
1215
+ // canvas error house style) included alongside the human message so agents
1216
+ // branch on the code, not the prose. Omitted for the legacy untyped 400s.
1217
+ const errResp = (status: number, message: string, code?: string): Response =>
1218
+ new Response(
1219
+ JSON.stringify(code ? { error: message, code } : { error: message }),
1220
+ {
1221
+ status,
1222
+ headers: { "Content-Type": "application/json", ...NO_STORE },
1223
+ }
1224
+ );
1091
1225
 
1226
+ const t0 = Date.now(); // Server-Timing base — emitted on the success 302
1092
1227
  const reqUrl = new URL(request.url);
1093
1228
  const q = reqUrl.searchParams;
1094
1229
 
@@ -1119,6 +1254,33 @@ async function handlePublicResolve(
1119
1254
  const aspectParam = q.get(PARAMS.aspect);
1120
1255
  const aspect: "16:9" | "2:3" | undefined =
1121
1256
  aspectParam === "2:3" ? "2:3" : aspectParam === "16:9" ? "16:9" : undefined;
1257
+ // Per-render background override (`bg=`): painted behind the mockup, visible
1258
+ // only through scene transparency. Validated here (via the grammar SSOT) so a
1259
+ // malformed color fails loudly at the edge, and required in CANONICAL form
1260
+ // (lowercase, no '#') because the URL is the cache key — accepting spelling
1261
+ // variants would cache the same pixels under multiple entries. When ABSENT
1262
+ // the render server falls back to the shop's configured default
1263
+ // (`mockup_bg_color`), else transparent; the reserved `bg=transparent` token
1264
+ // suppresses that default for this one render (forwarded verbatim — the
1265
+ // render server skips its shop-default fallback for it).
1266
+ const bg = q.get(PARAMS.bg) ?? undefined;
1267
+ if (bg !== undefined) {
1268
+ const canonical = normalizeBgColor(bg);
1269
+ if (canonical === null) {
1270
+ return errResp(
1271
+ 400,
1272
+ `bg= must be a 6-digit hex color (e.g. bg=f5f0ea) or bg=transparent, got "${bg}". ` +
1273
+ "Omit it to use the shop's configured default background."
1274
+ );
1275
+ }
1276
+ if (canonical !== bg) {
1277
+ return errResp(
1278
+ 400,
1279
+ `bg= must be the canonical lowercase form without '#' — use bg=${canonical}. ` +
1280
+ "(URLs are cache keys, so one value must always be one spelling.)"
1281
+ );
1282
+ }
1283
+ }
1122
1284
 
1123
1285
  if (!productCode) return errResp(400, "Missing productCode in path");
1124
1286
  if (!asset && designKeys.length === 0 && !designRef) {
@@ -1152,7 +1314,9 @@ async function handlePublicResolve(
1152
1314
  if (!key) return errResp(400, "Missing required query param: shop");
1153
1315
 
1154
1316
  // 1. Shop ID lookup → AccountData (404 unknown, 403 revoked).
1317
+ const tAcct = Date.now();
1155
1318
  const account = await loadAccountByKey(key, env);
1319
+ const acctMs = Date.now() - tAcct;
1156
1320
  if (!account) return errResp(404, "Unknown shop");
1157
1321
  if (account.revoked) return errResp(403, "Shop revoked");
1158
1322
 
@@ -1211,60 +1375,20 @@ async function handlePublicResolve(
1211
1375
  if (!ok) return errResp(403, "Invalid signature: s");
1212
1376
  }
1213
1377
 
1214
- // 3. Rate limit — reuse the existing per-account/IP public limiter.
1378
+ // 3+4. Rate limits and product fetch, OVERLAPPED. Each limiter DO lives in
1379
+ // exactly one location, so awaiting them serially stacked up to three
1380
+ // cross-region round-trips ahead of the redirect (~200ms warm, plus
1381
+ // hibernation wake when cold — the docs-click latency). Now the global
1382
+ // per-second + daily checks share ONE RPC (checkPublicLimits), the
1383
+ // per-account limiter runs in parallel with it, and the read-only product
1384
+ // fetch starts concurrently so its latency hides behind the DO hop.
1385
+ // Enforcement is unchanged: every limit verdict is awaited before any
1386
+ // response is built; when a limit blocks, the product result is discarded.
1215
1387
  const clientIp =
1216
1388
  request.headers.get("CF-Connecting-IP") ||
1217
1389
  request.headers.get("X-Forwarded-For") ||
1218
1390
  "unknown-ip";
1219
- // Global IP guard (same caps as authenticate()'s public path).
1220
- try {
1221
- const globalRl = env.API_RATE_LIMITER.get(
1222
- env.API_RATE_LIMITER.idFromName(`global:public:${clientIp}`)
1223
- );
1224
- const perSec = await globalRl.checkRateLimit(20);
1225
- if (!perSec.allowed) {
1226
- const resp = errResp(429, "Rate limit exceeded");
1227
- resp.headers.set(
1228
- "Retry-After",
1229
- String(Math.ceil((perSec.retryAfter ?? 1000) / 1000))
1230
- );
1231
- return resp;
1232
- }
1233
- const daily = await globalRl.checkDailyRateLimit(50000);
1234
- if (!daily.allowed) {
1235
- const resp = errResp(429, "Daily rate limit exceeded");
1236
- if (daily.retryAfter) {
1237
- resp.headers.set(
1238
- "Retry-After",
1239
- String(Math.ceil(daily.retryAfter / 1000))
1240
- );
1241
- }
1242
- return resp;
1243
- }
1244
- } catch (e) {
1245
- console.error(`Public resolve: global rate-limit error (fail open): ${e}`);
1246
- }
1247
- // Per-account public rate limit, if configured.
1248
- if (account.public?.rateLimit) {
1249
- try {
1250
- const acctRl = env.API_RATE_LIMITER.get(
1251
- env.API_RATE_LIMITER.idFromName(`${accountId}:public:${clientIp}`)
1252
- );
1253
- const result = await acctRl.checkRateLimit(account.public.rateLimit);
1254
- if (!result.allowed) {
1255
- const resp = errResp(429, "Rate limit exceeded");
1256
- resp.headers.set(
1257
- "Retry-After",
1258
- String(Math.ceil((result.retryAfter ?? 1000) / 1000))
1259
- );
1260
- return resp;
1261
- }
1262
- } catch (e) {
1263
- console.error(`Public resolve: account rate-limit error (fail open): ${e}`);
1264
- }
1265
- }
1266
1391
 
1267
- // 4. Resolve catalog config (Meilisearch, KV-cached).
1268
1392
  const meiliHost = env.MEILISEARCH_HOST;
1269
1393
  const meiliKey = env.MEILISEARCH_API_KEY;
1270
1394
  const meiliIndex = env.MEILISEARCH_INDEX;
@@ -1272,12 +1396,79 @@ async function handlePublicResolve(
1272
1396
  if (!meiliHost || !meiliKey || !meiliIndex || !mockupBaseUrl) {
1273
1397
  return errResp(500, "Resolver not configured");
1274
1398
  }
1275
- const product = await fetchProduct(
1399
+
1400
+ const tLimits = Date.now();
1401
+ const productPromise = fetchProduct(
1276
1402
  productCode,
1277
1403
  { host: meiliHost, apiKey: meiliKey, index: meiliIndex },
1278
1404
  env.ACCOUNTS
1279
1405
  );
1406
+ // Detached guard: when a limit blocks below, this promise is never awaited —
1407
+ // without a no-op catch, a fetch failure there would surface as an unhandled
1408
+ // rejection. The real `await productPromise` further down still rethrows.
1409
+ productPromise.catch(() => {});
1410
+
1411
+ type LimitVerdict = {
1412
+ allowed: boolean;
1413
+ scope?: "second" | "day";
1414
+ retryAfter?: number;
1415
+ };
1416
+ const globalCheck: Promise<LimitVerdict> = (async () => {
1417
+ try {
1418
+ const globalRl = env.API_RATE_LIMITER.get(
1419
+ env.API_RATE_LIMITER.idFromName(`global:public:${clientIp}`)
1420
+ );
1421
+ return await globalRl.checkPublicLimits(20, 50000);
1422
+ } catch (e) {
1423
+ console.error(`Public resolve: global rate-limit error (fail open): ${e}`);
1424
+ return { allowed: true };
1425
+ }
1426
+ })();
1427
+ const acctCheck: Promise<LimitVerdict> = (async () => {
1428
+ if (!account.public?.rateLimit) return { allowed: true };
1429
+ try {
1430
+ const acctRl = env.API_RATE_LIMITER.get(
1431
+ env.API_RATE_LIMITER.idFromName(`${accountId}:public:${clientIp}`)
1432
+ );
1433
+ return await acctRl.checkRateLimit(account.public.rateLimit);
1434
+ } catch (e) {
1435
+ console.error(`Public resolve: account rate-limit error (fail open): ${e}`);
1436
+ return { allowed: true };
1437
+ }
1438
+ })();
1439
+ const [globalVerdict, acctVerdict] = await Promise.all([
1440
+ globalCheck,
1441
+ acctCheck,
1442
+ ]);
1443
+ if (!globalVerdict.allowed) {
1444
+ const resp = errResp(
1445
+ 429,
1446
+ globalVerdict.scope === "day"
1447
+ ? "Daily rate limit exceeded"
1448
+ : "Rate limit exceeded"
1449
+ );
1450
+ if (globalVerdict.retryAfter) {
1451
+ resp.headers.set(
1452
+ "Retry-After",
1453
+ String(Math.ceil(globalVerdict.retryAfter / 1000))
1454
+ );
1455
+ }
1456
+ return resp;
1457
+ }
1458
+ if (!acctVerdict.allowed) {
1459
+ const resp = errResp(429, "Rate limit exceeded");
1460
+ resp.headers.set(
1461
+ "Retry-After",
1462
+ String(Math.ceil((acctVerdict.retryAfter ?? 1000) / 1000))
1463
+ );
1464
+ return resp;
1465
+ }
1466
+ const limitsMs = Date.now() - tLimits;
1467
+
1468
+ const tProduct = Date.now();
1469
+ const product = await productPromise;
1280
1470
  if (!product) return errResp(404, `Product not found: ${productCode}`);
1471
+ const productMs = Date.now() - tProduct;
1281
1472
 
1282
1473
  // 4-design. Resolve the catalog reference (ADR-0086). Membership in the
1283
1474
  // designs index IS the license check — a miss is a loud 404, never a
@@ -1353,12 +1544,9 @@ async function handlePublicResolve(
1353
1544
  // placement becomes the repeating page placement's geometry.
1354
1545
  if (pagePlacement) scene.placement = pagePlacement;
1355
1546
 
1356
- // 4b. Build the design elements: a multi-placement map, or the single bare asset.
1357
- const ALLOWED_TILES = [0.25, 0.5, 1, 2, 4];
1358
- const ALIGNMENTS = new Set<string>([
1359
- "center", "top", "far-top", "bottom", "far-bottom",
1360
- "left", "far-left", "right", "far-right",
1361
- ]);
1547
+ // 4b. Build the design elements: one base broadcast across every placement
1548
+ // plus per-placement overrides (ADR-0089), or a catalog design verbatim.
1549
+ //
1362
1550
  // Strict: the URL key must equal the placement's canonical catalog `key`
1363
1551
  // EXACTLY — no label/slug/case fallbacks. A wrong key fails loudly with
1364
1552
  // "Unknown placement" instead of being silently coerced, and this matches the
@@ -1402,46 +1590,23 @@ async function handlePublicResolve(
1402
1590
  alignment: "center",
1403
1591
  });
1404
1592
  }
1405
- } else if (designKeys.length > 0) {
1406
- for (const k of designKeys) {
1407
- const fill = design[k];
1408
- const pl = findPlacement(k);
1409
- if (!pl) return errResp(400, `Unknown placement: ${k}`);
1410
- if (fill.color) {
1411
- designElements.push({
1412
- type: "color",
1413
- hex: fill.color,
1414
- placement: pl.label,
1415
- width: pl.width,
1416
- height: pl.height,
1417
- });
1418
- } else if (fill.src) {
1419
- const el: DesignElement = {
1420
- type: "image",
1421
- imageUrl: isDefaultToken(fill.src) ? house : fill.src,
1422
- placement: pl.label,
1423
- width: pl.width,
1424
- height: pl.height,
1425
- alignment:
1426
- fill.align && ALIGNMENTS.has(fill.align)
1427
- ? (fill.align as ImageAlignment)
1428
- : "center",
1429
- };
1430
- if (fill.tile !== undefined && ALLOWED_TILES.includes(fill.tile)) {
1431
- el.tiles = fill.tile as 0.25 | 0.5 | 1 | 2 | 4;
1432
- }
1433
- designElements.push(el);
1434
- }
1435
- }
1436
- } else if (asset) {
1437
- designElements.push({
1438
- type: "image",
1439
- imageUrl: isDefaultToken(asset) ? house : asset,
1440
- placement: scene.placement.label,
1441
- width: scene.placement.width,
1442
- height: scene.placement.height,
1443
- alignment: "center",
1593
+ } else {
1594
+ // ADR-0089 base+override: the scalar `asset=` SEEDS every placement (each
1595
+ // with ITS OWN geometry), then each `asset.<key>=` OVERRIDES the base on
1596
+ // that one placement. `default` blanks (house) at either scope. An unknown
1597
+ // override key fails loudly (E_PLACEMENT_NOT_FOUND, listing valid keys).
1598
+ // The base broadcast fans out across `product.placements` directly — it no
1599
+ // longer rides the single default-placement resolution.
1600
+ const assembled = assembleArtwork(product, {
1601
+ asset,
1602
+ design,
1603
+ house,
1604
+ findPlacement,
1444
1605
  });
1606
+ if (!assembled.ok) {
1607
+ return errResp(assembled.status, assembled.message, assembled.code);
1608
+ }
1609
+ designElements.push(...assembled.elements);
1445
1610
  }
1446
1611
  if (designElements.length === 0) {
1447
1612
  return errResp(400, "Missing artwork: provide asset= or asset.<placement>=");
@@ -1467,6 +1632,7 @@ async function handlePublicResolve(
1467
1632
  variantId: vr.variantId,
1468
1633
  width,
1469
1634
  ...(aspect ? { aspect } : {}),
1635
+ ...(bg ? { bg } : {}),
1470
1636
  ...(hasOptionSelections ? { optionSelections: vr.optionSelections } : {}),
1471
1637
  design: designElements,
1472
1638
  },
@@ -1483,64 +1649,71 @@ async function handlePublicResolve(
1483
1649
  if (catalogDesign) {
1484
1650
  urlObj.searchParams.append("catalog", catalogDesign.pairingId);
1485
1651
  }
1652
+ // Operator debug passthrough (ADR-0096): with the 302 retired, the client
1653
+ // never learns the sealed URL, so the lab's full-waterfall replay re-fetches
1654
+ // the PUBLIC url with debug=<RENDER_DEBUG_SECRET>. Forward it onto the
1655
+ // sealed URL — INSIDE the signature (appended before signing), so seal
1656
+ // verification still holds — and the render edge/box gate it exactly as
1657
+ // before (wrong value = no stages, edge debug-branch bypasses R2).
1658
+ const debugParam = q.get("debug");
1659
+ if (debugParam) {
1660
+ urlObj.searchParams.append("debug", debugParam);
1661
+ }
1486
1662
  const sigParams = new URLSearchParams(urlObj.search);
1487
1663
  sigParams.delete("seal");
1488
1664
  const relative = `${urlObj.pathname}?${sigParams.toString()}`;
1489
1665
  const sig = await signUrl(relative, signingSecret);
1490
1666
  urlObj.searchParams.append("seal", sig);
1491
1667
 
1492
- // 7. 302 to the relay-signed render URL, no-store on the REDIRECT.
1493
- return new Response(null, {
1494
- status: 302,
1495
- headers: {
1496
- Location: urlObj.toString(),
1497
- ...NO_STORE,
1498
- },
1668
+ // 7. Single-leg render (ADR-0096, retired the 302): call the render edge
1669
+ // over the service binding with the sealed URL and stream its bytes back.
1670
+ // Worker-to-worker on Cloudflare's backbone — no second client RTT, no
1671
+ // second TLS handshake, no redirect processing. The edge still verifies
1672
+ // the seal, DMCA deny-set and cache exactly as if the browser had fetched
1673
+ // the sealed URL itself.
1674
+ //
1675
+ // Cache semantics: the OLD 302 was `private, max-age=300` so a browser
1676
+ // re-resolved (revocation / key rotation / catalog edits) within 5
1677
+ // minutes, while the sealed CDN response stayed immutable. The single-leg
1678
+ // response answers on the PUBLIC url, so it must keep the resolver-layer
1679
+ // semantics — override the edge's immutable header with the redirect-era
1680
+ // policy. rsv_* Server-Timing entries expose the resolver's own stages
1681
+ // next to the edge/box entries (acct = KV/backend account load, limits =
1682
+ // rate-limit verdict, product = catalog fetch).
1683
+ // rsv_total = the resolver's OWN work only (auth, limits, product, seal),
1684
+ // captured BEFORE the edge call — the edge stamps edge_total itself, and
1685
+ // overlapping totals make waterfalls unreadable (browser wait then reads:
1686
+ // transit + rsv_total + edge_total, no envelope arithmetic needed).
1687
+ const resolverMs = Date.now() - t0;
1688
+ const edgeRes = await env.RENDER_EDGE.fetch(
1689
+ new Request(urlObj.toString(), {
1690
+ method: "GET",
1691
+ headers: request.headers,
1692
+ })
1693
+ );
1694
+ const headers = new Headers(edgeRes.headers);
1695
+ headers.set("Cache-Control", edgeRes.ok ? "private, max-age=300" : "no-store");
1696
+ headers.set("Access-Control-Allow-Origin", "*");
1697
+ headers.set("Timing-Allow-Origin", "*");
1698
+ headers.append(
1699
+ "Server-Timing",
1700
+ `rsv_acct;dur=${acctMs}, rsv_limits;dur=${limitsMs}, ` +
1701
+ `rsv_product;dur=${productMs}, rsv_total;dur=${resolverMs}`
1702
+ );
1703
+ return new Response(edgeRes.body, {
1704
+ status: edgeRes.status,
1705
+ statusText: edgeRes.statusText,
1706
+ headers,
1499
1707
  });
1500
1708
  }
1501
1709
 
1502
1710
  // Cloudflare Worker entry point
1503
1711
  export default {
1504
1712
  async fetch(request: Request, env: Env, ctx: any): Promise<Response> {
1505
- // Add test endpoint
1506
- const requestUrl = new URL(request.url);
1507
- if (requestUrl.pathname === "/test-kv") {
1508
- try {
1509
- // Try to write a test key
1510
- await env.ACCOUNTS.put("test-key", "test-value");
1511
-
1512
- // Try to read all keys
1513
- const keys = await env.ACCOUNTS.list();
1514
-
1515
- // Try to read our test key
1516
- const testValue = await env.ACCOUNTS.get("test-key");
1517
-
1518
- // Try to read account123
1519
- const account123 = await env.ACCOUNTS.get("account123");
1520
-
1521
- return new Response(
1522
- JSON.stringify({
1523
- testWrite: "success",
1524
- testRead: testValue,
1525
- keys: keys,
1526
- account123: account123,
1527
- }),
1528
- {
1529
- headers: { "Content-Type": "application/json" },
1530
- }
1531
- );
1532
- } catch (error: any) {
1533
- return new Response(
1534
- JSON.stringify({
1535
- error: `KV test failed: ${error.message || String(error)}`,
1536
- }),
1537
- {
1538
- status: 500,
1539
- headers: { "Content-Type": "application/json" },
1540
- }
1541
- );
1542
- }
1543
- }
1713
+ // SECURITY: the former unauthenticated `/test-kv` debug endpoint was removed.
1714
+ // It dumped/enumerated/wrote the ACCOUNTS KV (account configs, key hashes,
1715
+ // L3 secrets) with no auth, live in production. Nothing depends on it; do
1716
+ // not reintroduce a KV-dumping route without auth + a non-prod gate.
1544
1717
 
1545
1718
  // Handle CORS preflight
1546
1719
  if (request.method === "OPTIONS") {
@@ -1550,6 +1723,8 @@ export default {
1550
1723
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
1551
1724
  "Access-Control-Allow-Headers":
1552
1725
  "Content-Type, X-API-Key, X-Client-ID",
1726
+ // Reflected Origin → cache must vary by Origin (see CORS notes above).
1727
+ Vary: "Origin",
1553
1728
  },
1554
1729
  });
1555
1730
  }
@@ -1642,6 +1817,37 @@ export default {
1642
1817
  const accountId = authResult.accountId!;
1643
1818
 
1644
1819
  if (url.pathname === "/sign") {
1820
+ // SECURITY: /sign mints the internal RELAY `seal` (URL_SIGNING_SECRET)
1821
+ // that rendercenter trusts — the SAME credential handlePublicResolve
1822
+ // produces only AFTER the L2 asset-origin allowlist and L3 requireSig
1823
+ // checks. Signing here does NOT re-run those checks (an authenticated
1824
+ // integrator is trusted to sign its own renders, like /mockups/url), so
1825
+ // this endpoint must never be reachable with only a PUBLIC shop id —
1826
+ // otherwise it is an open signing oracle that launders a disallowed
1827
+ // origin/host past L2/L3. Require a real API-key credential: with the
1828
+ // x-api-key header present, authenticate() above took Method 1 (hash +
1829
+ // 'mockups' scope, validated against THIS shop) — the rate-limited
1830
+ // public fallback (Method 2) can no longer satisfy /sign.
1831
+ //
1832
+ // Gated to production the same way handleMockupUrl/loadAccountByKey are:
1833
+ // local dev runs with the 'dev-unsigned' secret (seals are worthless
1834
+ // off-box) and has no provisioned API keys, so the dev flow is unchanged.
1835
+ const isDevUnsigned =
1836
+ !env.URL_SIGNING_SECRET || env.URL_SIGNING_SECRET === "dev-unsigned";
1837
+ if (!isDevUnsigned && !request.headers.get("x-api-key")) {
1838
+ const errorResponse = new Response(
1839
+ JSON.stringify({
1840
+ error:
1841
+ "The /sign endpoint requires an API key with the 'mockups' scope (X-API-Key header). A public shop id is not sufficient.",
1842
+ }),
1843
+ {
1844
+ status: 401,
1845
+ headers: { "Content-Type": "application/json" },
1846
+ }
1847
+ );
1848
+ return addCorsHeaders(errorResponse, request);
1849
+ }
1850
+
1645
1851
  // Get the URL to sign from the query parameter
1646
1852
  let urlToSign = url.searchParams.get("url");
1647
1853
  let isRelativeUrl = false;