@snowcone-app/mockup-resolver 1.0.0 → 1.0.2

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
@@ -50,6 +50,12 @@ interface Env {
50
50
  // ACCOUNTS KV, the signer fetches it from the backend's /kv-cache/api-key.
51
51
  KV_CACHE_BASE_URL?: string; // backend base URL; defaults to http://localhost:4000 for local dev
52
52
  KV_CACHE_SERVICE_TOKEN?: string; // Bearer service token — SECRET (wrangler secret put / process-compose --var). No source default.
53
+ /**
54
+ * Designs catalog index uid for `design=<pairingId|slug>` references
55
+ * (ADR-0086) — `snowcone-designs` in prod, `snowcone-designs-dev` elsewhere.
56
+ * Read with the same public MEILISEARCH_API_KEY as the products index.
57
+ */
58
+ MEILISEARCH_DESIGNS_INDEX?: string;
53
59
  }
54
60
 
55
61
  // Type definitions for account data - updated format
@@ -69,6 +75,16 @@ interface AccountData {
69
75
  requireSig?: boolean;
70
76
  /** Explicit kill switch — a revoked key 403s regardless of any other config. */
71
77
  revoked?: boolean;
78
+ /**
79
+ * Set when a sandbox shop has been RELEASED (ADR-0078). The backend leaves a
80
+ * render-only tombstone in KV so already-produced mockup URLs keep resolving
81
+ * after release (a produced mockup is public marketing imagery and must outlive
82
+ * the shop). A retained shop has no apiKeys/l3Secret and `revoked:false`, so the
83
+ * existing resolve path already serves it render-only. The flag is informational
84
+ * here (it lets the resolver/observability distinguish a live shop from a
85
+ * retained-artifact stub) and intentionally does NOT change render behaviour.
86
+ */
87
+ retained?: boolean;
72
88
  }
73
89
 
74
90
  interface ApiKeyData {
@@ -747,31 +763,16 @@ async function authenticate(
747
763
  return { authenticated: true, accountId };
748
764
  }
749
765
 
750
- // Helper function to convert glob-like pattern to RegExp
751
- function globToRegExp(glob: string): RegExp {
752
- let regexString = "^";
753
- for (let i = 0; i < glob.length; i++) {
754
- const char = glob[i];
755
- if (char === "*") {
756
- regexString += ".*?"; // Non-greedy match for any characters
757
- } else if (/[.+\[\]?^${}()|\-\\]/.test(char)) {
758
- // Corrected regex for special characters
759
- regexString += "\\" + char; // Escape them
760
- } else {
761
- regexString += char;
762
- }
763
- }
764
- regexString += "$";
765
- return new RegExp(regexString, "i"); // Added 'i' flag for case-insensitive matching
766
- }
767
-
768
766
  // NOTE: `isOriginAllowed` (the page-origin / domain allowlist matcher) was
769
767
  // removed alongside the `allowedOrigins` config — see the PublicData comment
770
- // above. `globToRegExp` is retained because the asset-source allowlist (L2,
771
- // `isHostAllowed`) still uses it.
768
+ // above. `globToRegExp` moved to ./asset-allowlist (pure module, unit-tested
769
+ // in the default test glob) along with the L2 check; the asset-source
770
+ // allowlist (L2) still uses it.
772
771
 
773
772
  export { signUrl, verifyUrl } from "./signing";
774
773
  import { signUrl, verifyUrl } from "./signing";
774
+ import { checkAssetUrls } from "./asset-allowlist";
775
+ import { fetchDesign } from "./design-ref";
775
776
  import {
776
777
  buildMockupUrl,
777
778
  canonicalForSig,
@@ -783,9 +784,13 @@ import {
783
784
  } from "@snowcone-app/mockup-url";
784
785
  import {
785
786
  fetchProduct,
787
+ looksLikeResolveRequest,
788
+ resolveAlbumPagePlacement,
786
789
  resolveDefaults,
787
790
  resolveVariant,
791
+ type ResolvedPlacement,
788
792
  } from "./resolve";
793
+ import { rejectUnknownPublicParams } from "./public-params";
789
794
 
790
795
  // ADR-0073 §10 — resolve + build + sign for `getMockupUrl(assetUrl, productCode)`.
791
796
  // The BFF POSTs { accountId, productCode, assetUrl, variant?, mockupId?, placement?, width? }
@@ -1016,20 +1021,59 @@ async function loadAccountByKey(
1016
1021
  }
1017
1022
  }
1018
1023
 
1019
- /** Check a hostname against a glob allowlist (reuses globToRegExp). */
1020
- function isHostAllowed(host: string, allowlist: string[]): boolean {
1021
- if (allowlist.length === 0) return true; // unset = any
1022
- for (const pattern of allowlist) {
1023
- if (pattern === "*") return true;
1024
- try {
1025
- if (globToRegExp(pattern).test(host)) return true;
1026
- } catch {
1027
- // skip malformed pattern
1028
- }
1029
- }
1030
- return false;
1024
+ // ───────────────────────────────────────────────────────────────────────────
1025
+ // "Blank item" affordance (the homepage's bottom-of-page blanks, but available
1026
+ // to every shop out of the box). A reserved asset VALUE — `asset=default` (or
1027
+ // `asset.<key>=default`) — that the resolver substitutes server-side for the
1028
+ // transparent /_blank.png this worker serves itself (below). So a blank item
1029
+ // needs no hosting, no allowlist entry, and no per-shop setup.
1030
+ //
1031
+ // Because the resolver INJECTS this asset, it is exempt from the L2 asset-origin
1032
+ // allowlist by provenance — L2 polices developer-supplied hosts (anti-theft),
1033
+ // and the house placeholder is not developer-supplied. The "no artwork" contract
1034
+ // is unchanged: omitting artwork entirely still 400s; `default` is an explicit
1035
+ // opt-in. (Asset-origin allowlist context: ADR-0076.)
1036
+ //
1037
+ // Per-shop branding (resolving `default` to the shop's own mark instead of the
1038
+ // transparent blank) is a future addition — the same URL would then render
1039
+ // branding with no caller change. Not built yet.
1040
+ const DEFAULT_ASSET_TOKEN = "default";
1041
+ const isDefaultToken = (v: string | null | undefined): boolean =>
1042
+ v === DEFAULT_ASSET_TOKEN;
1043
+
1044
+ // A 1×1 fully-transparent PNG (68 bytes), served at /_blank.png. Generated as an
1045
+ // 8-bit RGBA PNG with a single transparent pixel; rendercenter composites it to
1046
+ // nothing, so the placement contributes zero pixels → a bare (blank) mockup.
1047
+ const BLANK_PNG_BASE64 =
1048
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNgAAIAAAUAAen63NgAAAAASUVORK5CYII=";
1049
+ const BLANK_PNG_PATH = "/_blank.png";
1050
+
1051
+ /** Decode a base64 string to bytes (Workers-safe; no Buffer). */
1052
+ function base64ToBytes(b64: string): Uint8Array {
1053
+ const bin = atob(b64);
1054
+ const out = new Uint8Array(bin.length);
1055
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1056
+ return out;
1057
+ }
1058
+
1059
+ /**
1060
+ * The URL the `default` token resolves to: this worker's own transparent
1061
+ * `/_blank.png` on the request's host (img.snowcone.app in prod, the workspace
1062
+ * host in dev) — no separate hosting to keep in sync. (A per-shop brand override
1063
+ * would branch here in future.)
1064
+ *
1065
+ * Scheme is forced to https: both prod and the local dev proxy (caddy/traefik on
1066
+ * *.img.lvh.me) serve the resolver over https ONLY. Behind that TLS-terminating
1067
+ * proxy the worker sees the request as http, so deriving the scheme from
1068
+ * request.url would inject an http asset URL the renderer can't fetch.
1069
+ */
1070
+ function houseAssetUrl(request: Request): string {
1071
+ return `https://${new URL(request.url).host}${BLANK_PNG_PATH}`;
1031
1072
  }
1032
1073
 
1074
+ // L2 hostname matching + exempt-origin logic live in ./asset-allowlist
1075
+ // (pure module) so they run under the default unit-test glob.
1076
+
1033
1077
  async function handlePublicResolve(
1034
1078
  request: Request,
1035
1079
  env: Env,
@@ -1047,6 +1091,14 @@ async function handlePublicResolve(
1047
1091
 
1048
1092
  const reqUrl = new URL(request.url);
1049
1093
  const q = reqUrl.searchParams;
1094
+
1095
+ // Strict params FIRST: any query key outside the public grammar 400s loudly
1096
+ // (naming the key + the allowed grammar) instead of being silently ignored —
1097
+ // a hand-edited `view=<sceneId>` used to render the default scene with zero
1098
+ // feedback. Predicate lives in @snowcone-app/mockup-url (grammar SSOT).
1099
+ const badParams = rejectUnknownPublicParams(reqUrl);
1100
+ if (badParams) return badParams;
1101
+
1050
1102
  // The full grammar: bare `asset=` (default placement) OR a multi-placement
1051
1103
  // design map (`asset.<key>`/`color.<key>`/`tile.<key>`/`align.<key>`) + variant
1052
1104
  // option picks (`opt.<attr>`).
@@ -1055,18 +1107,47 @@ async function handlePublicResolve(
1055
1107
  const design = parsed.design ?? {};
1056
1108
  const optionPicks = parsed.options ?? {};
1057
1109
  const designKeys = Object.keys(design);
1110
+ // Catalog design reference (ADR-0086): `design=<pairingId|slug>` renders a
1111
+ // published catalog design as-is — resolver-injected components, free tier.
1112
+ const designRef = parsed.designRef;
1058
1113
  const key = q.get(PARAMS.shop);
1059
1114
  const widthParam = q.get(PARAMS.width);
1060
1115
  const mockupOverride = q.get(PARAMS.mockup) ?? undefined;
1061
1116
  const variantOverride = q.get(PARAMS.variant) ?? undefined;
1062
1117
  const placementOverride = q.get(PARAMS.placement) ?? undefined;
1118
+ const pageParam = q.get(PARAMS.page) ?? undefined;
1063
1119
  const aspectParam = q.get(PARAMS.aspect);
1064
1120
  const aspect: "16:9" | "2:3" | undefined =
1065
1121
  aspectParam === "2:3" ? "2:3" : aspectParam === "16:9" ? "16:9" : undefined;
1066
1122
 
1067
1123
  if (!productCode) return errResp(400, "Missing productCode in path");
1068
- if (!asset && designKeys.length === 0) {
1069
- return errResp(400, "Missing artwork: provide asset= or asset.<placement>=");
1124
+ if (!asset && designKeys.length === 0 && !designRef) {
1125
+ return errResp(
1126
+ 400,
1127
+ "Missing artwork: provide asset=, asset.<placement>=, or design=<catalog design>"
1128
+ );
1129
+ }
1130
+ // Free = the design as published (ADR-0086): a catalog reference cannot be
1131
+ // combined with developer-supplied artwork params.
1132
+ if (designRef && (asset || designKeys.length > 0)) {
1133
+ return errResp(
1134
+ 400,
1135
+ "design= renders the catalog design as published and cannot be combined " +
1136
+ "with asset=, asset.<placement>=, or color.<placement>= — drop those " +
1137
+ "params, or drop design= to render your own artwork (billable)"
1138
+ );
1139
+ }
1140
+ // page=N (ADR-0086 §5): syntax checks up front; the album-block semantics
1141
+ // need the catalog doc, so they run after the product fetch below.
1142
+ if (pageParam !== undefined && !/^[1-9][0-9]*$/.test(pageParam)) {
1143
+ return errResp(400, "page= must be a positive integer");
1144
+ }
1145
+ if (pageParam !== undefined && placementOverride !== undefined) {
1146
+ return errResp(
1147
+ 400,
1148
+ "page= and placement= are mutually exclusive — page=N already selects " +
1149
+ "the album's repeating page placement"
1150
+ );
1070
1151
  }
1071
1152
  if (!key) return errResp(400, "Missing required query param: shop");
1072
1153
 
@@ -1082,26 +1163,29 @@ async function handlePublicResolve(
1082
1163
  // never be enforced. Anti-theft is the asset-source allowlist (L2, below) plus
1083
1164
  // signed URLs (L3). See ADR-0075/0076.
1084
1165
 
1085
- // Every image URL the design references (bare asset + per-placement srcs).
1166
+ // The asset the reserved `default` token resolves to (the transparent
1167
+ // /_blank.png this worker serves). Computed once; injected below.
1168
+ const house = houseAssetUrl(request);
1169
+
1170
+ // Every DEVELOPER-supplied image URL the design references (bare asset +
1171
+ // per-placement srcs). Reserved `default` tokens are EXCLUDED — they are
1172
+ // platform-injected (resolved to `house`), so they bypass L2 by provenance.
1086
1173
  const imageUrls: string[] = [];
1087
- if (asset) imageUrls.push(asset);
1174
+ if (asset && !isDefaultToken(asset)) imageUrls.push(asset);
1088
1175
  for (const k of designKeys) {
1089
1176
  const src = design[k].src;
1090
- if (src) imageUrls.push(src);
1177
+ if (src && !isDefaultToken(src)) imageUrls.push(src);
1091
1178
  }
1092
1179
 
1093
1180
  // 2b. L2 — asset-source allowlist (checked for EVERY image URL's hostname).
1094
- if (account.assetAllowlist && account.assetAllowlist.length > 0) {
1095
- for (const imageUrl of imageUrls) {
1096
- let assetHost: string;
1097
- try {
1098
- assetHost = new URL(imageUrl).hostname;
1099
- } catch {
1100
- return errResp(400, "Invalid asset URL");
1101
- }
1102
- if (!isHostAllowed(assetHost, account.assetAllowlist)) {
1103
- return errResp(403, "Asset source not allowed for this shop");
1104
- }
1181
+ // Catalog designs (`design=`) never reach this check: their components are
1182
+ // resolver-injected (bypass by provenance, like the `default` token), and
1183
+ // the grammar forbids combining design= with developer asset params — so
1184
+ // imageUrls is empty for catalog renders and no origin is ever exempted.
1185
+ {
1186
+ const verdict = checkAssetUrls(imageUrls, account.assetAllowlist);
1187
+ if (!verdict.ok) {
1188
+ return errResp(verdict.status, verdict.message);
1105
1189
  }
1106
1190
  }
1107
1191
 
@@ -1194,6 +1278,62 @@ async function handlePublicResolve(
1194
1278
  env.ACCOUNTS
1195
1279
  );
1196
1280
  if (!product) return errResp(404, `Product not found: ${productCode}`);
1281
+
1282
+ // 4-design. Resolve the catalog reference (ADR-0086). Membership in the
1283
+ // designs index IS the license check — a miss is a loud 404, never a
1284
+ // fallback to URL-mode.
1285
+ let catalogDesign: Awaited<ReturnType<typeof fetchDesign>> = null;
1286
+ if (designRef) {
1287
+ const designsIndex = env.MEILISEARCH_DESIGNS_INDEX;
1288
+ if (!designsIndex) return errResp(500, "Designs catalog not configured");
1289
+ catalogDesign = await fetchDesign(
1290
+ designRef,
1291
+ { host: meiliHost, apiKey: meiliKey, index: designsIndex },
1292
+ env.ACCOUNTS
1293
+ );
1294
+ if (!catalogDesign) {
1295
+ return errResp(404, `Design not found in catalog: ${designRef}`);
1296
+ }
1297
+ if (catalogDesign.productId !== productCode) {
1298
+ return errResp(
1299
+ 400,
1300
+ `Design ${designRef} belongs to product ${catalogDesign.productId} — ` +
1301
+ `use https://img.snowcone.app/${catalogDesign.productId}?design=…`
1302
+ );
1303
+ }
1304
+ }
1305
+ // 4-page. Album page selection (ADR-0086 §5): page=N maps to the wire key
1306
+ // `<pagePlacement>_N`, which resolves to the GEOMETRY of the repeating page
1307
+ // placement — the catalog never enumerates page_1..page_100. Only album
1308
+ // products accept page=; everything else fails loudly.
1309
+ let pagePlacement: ResolvedPlacement | null = null;
1310
+ if (pageParam !== undefined) {
1311
+ if (!product.album) {
1312
+ return errResp(
1313
+ 400,
1314
+ `page= is only valid for album products — ${productCode} has no album block`
1315
+ );
1316
+ }
1317
+ const pageNum = Number(pageParam);
1318
+ if (pageNum > product.album.pageExtent.max) {
1319
+ return errResp(
1320
+ 400,
1321
+ `page=${pageNum} is out of range for ${productCode} ` +
1322
+ `(pages 1–${product.album.pageExtent.max})`
1323
+ );
1324
+ }
1325
+ pagePlacement = resolveAlbumPagePlacement(
1326
+ product,
1327
+ `${product.album.pagePlacement}_${pageNum}`
1328
+ );
1329
+ if (!pagePlacement) {
1330
+ // Catalog drift: the album block names a placement the doc no longer has.
1331
+ return errResp(
1332
+ 422,
1333
+ `Album page placement "${product.album.pagePlacement}" no longer exists: ${productCode}`
1334
+ );
1335
+ }
1336
+ }
1197
1337
  // 4a. Resolve the variant from option picks (both catalog shapes) + the
1198
1338
  // render-only optionSelections rendercenter needs. resolveDefaults then supplies
1199
1339
  // the mockup scene and a default placement (for the bare-asset case).
@@ -1209,6 +1349,9 @@ async function handlePublicResolve(
1209
1349
  if (!scene) {
1210
1350
  return errResp(422, `Product ${productCode} has no renderable combination`);
1211
1351
  }
1352
+ // page=N selects which album page feeds the scene: the resolved default
1353
+ // placement becomes the repeating page placement's geometry.
1354
+ if (pagePlacement) scene.placement = pagePlacement;
1212
1355
 
1213
1356
  // 4b. Build the design elements: a multi-placement map, or the single bare asset.
1214
1357
  const ALLOWED_TILES = [0.25, 0.5, 1, 2, 4];
@@ -1221,11 +1364,45 @@ async function handlePublicResolve(
1221
1364
  // "Unknown placement" instead of being silently coerced, and this matches the
1222
1365
  // buy worker's strict `placementByKey.get(key)`, so any URL that previews is
1223
1366
  // guaranteed to also check out (no preview-works/buy-400s divergence).
1367
+ // Album products additionally accept the expanded page keys (`page_N` →
1368
+ // the repeating placement's geometry, ADR-0086); null for everything else,
1369
+ // so non-album products behave exactly as before.
1224
1370
  const findPlacement = (k: string) =>
1225
- product.placements.find((p) => p.key === k);
1371
+ product.placements.find((p) => p.key === k) ??
1372
+ resolveAlbumPagePlacement(product, k);
1226
1373
 
1227
1374
  const designElements: DesignElement[] = [];
1228
- if (designKeys.length > 0) {
1375
+ if (catalogDesign) {
1376
+ // Catalog design: render its published components verbatim. Per-placement
1377
+ // assets when present (keys are this product's wire keys — the doc was
1378
+ // built from the same catalog placements), else the bare flattened asset.
1379
+ if (catalogDesign.assets && Object.keys(catalogDesign.assets).length > 0) {
1380
+ for (const k of Object.keys(catalogDesign.assets)) {
1381
+ const pl = findPlacement(k);
1382
+ if (!pl) {
1383
+ // Catalog/doc drift (placement renamed since the sync) — fail loudly.
1384
+ return errResp(422, `Catalog design placement no longer exists: ${k}`);
1385
+ }
1386
+ designElements.push({
1387
+ type: "image",
1388
+ imageUrl: catalogDesign.assets[k],
1389
+ placement: pl.label,
1390
+ width: pl.width,
1391
+ height: pl.height,
1392
+ alignment: "center",
1393
+ });
1394
+ }
1395
+ } else if (catalogDesign.asset) {
1396
+ designElements.push({
1397
+ type: "image",
1398
+ imageUrl: catalogDesign.asset,
1399
+ placement: scene.placement.label,
1400
+ width: scene.placement.width,
1401
+ height: scene.placement.height,
1402
+ alignment: "center",
1403
+ });
1404
+ }
1405
+ } else if (designKeys.length > 0) {
1229
1406
  for (const k of designKeys) {
1230
1407
  const fill = design[k];
1231
1408
  const pl = findPlacement(k);
@@ -1241,7 +1418,7 @@ async function handlePublicResolve(
1241
1418
  } else if (fill.src) {
1242
1419
  const el: DesignElement = {
1243
1420
  type: "image",
1244
- imageUrl: fill.src,
1421
+ imageUrl: isDefaultToken(fill.src) ? house : fill.src,
1245
1422
  placement: pl.label,
1246
1423
  width: pl.width,
1247
1424
  height: pl.height,
@@ -1259,7 +1436,7 @@ async function handlePublicResolve(
1259
1436
  } else if (asset) {
1260
1437
  designElements.push({
1261
1438
  type: "image",
1262
- imageUrl: asset,
1439
+ imageUrl: isDefaultToken(asset) ? house : asset,
1263
1440
  placement: scene.placement.label,
1264
1441
  width: scene.placement.width,
1265
1442
  height: scene.placement.height,
@@ -1300,6 +1477,12 @@ async function handlePublicResolve(
1300
1477
  // RELATIVE path+query minus seal). The developer never sees this secret.
1301
1478
  const signingSecret = env.URL_SIGNING_SECRET || "dev-unsigned";
1302
1479
  const urlObj = new URL(unsigned);
1480
+ // Catalog provenance (ADR-0086): rendercenter zero-bills `catalog=` renders
1481
+ // and records the pairingId. Trustworthy because it is under the seal — only
1482
+ // this resolver mints it, and only after the membership check above.
1483
+ if (catalogDesign) {
1484
+ urlObj.searchParams.append("catalog", catalogDesign.pairingId);
1485
+ }
1303
1486
  const sigParams = new URLSearchParams(urlObj.search);
1304
1487
  sigParams.delete("seal");
1305
1488
  const relative = `${urlObj.pathname}?${sigParams.toString()}`;
@@ -1388,6 +1571,22 @@ export default {
1388
1571
  );
1389
1572
  }
1390
1573
 
1574
+ // The transparent house placeholder the `asset=default` token resolves to
1575
+ // (see DEFAULT_ASSET_TOKEN). Served by this worker so the "blank item"
1576
+ // affordance deploys atomically with no external hosting to keep in sync.
1577
+ // Immutable → long cache.
1578
+ if (request.method === "GET" && url.pathname === BLANK_PNG_PATH) {
1579
+ return addCorsHeaders(
1580
+ new Response(base64ToBytes(BLANK_PNG_BASE64), {
1581
+ headers: {
1582
+ "Content-Type": "image/png",
1583
+ "Cache-Control": "public, max-age=31536000, immutable",
1584
+ },
1585
+ }),
1586
+ request
1587
+ );
1588
+ }
1589
+
1391
1590
  // ADR-0076: the public image-CDN resolver on img.snowcone.app.
1392
1591
  // GET https://img.snowcone.app/{productCode}?asset=…&shop=…
1393
1592
  // Routed by Host (img.*) in production; in local dev (single host) we also
@@ -1395,19 +1594,10 @@ export default {
1395
1594
  // (or the legacy `key` alias), so the resolver is reachable without the
1396
1595
  // custom domain binding.
1397
1596
  const host = (request.headers.get("Host") || url.host || "").toLowerCase();
1398
- const isImgHost = host.startsWith("img.");
1399
- const pathSegments = url.pathname.split("/").filter(Boolean);
1400
- const isSingleSegmentPath = pathSegments.length === 1;
1401
- const RESERVED_PATHS = new Set(["test-kv", "mockups", "sign", "verify"]);
1402
- const looksLikeResolve =
1403
- request.method === "GET" &&
1404
- isSingleSegmentPath &&
1405
- !RESERVED_PATHS.has(pathSegments[0]) &&
1406
- (isImgHost ||
1407
- (url.searchParams.has(PARAMS.asset) &&
1408
- url.searchParams.has(PARAMS.shop)));
1409
- if (looksLikeResolve) {
1410
- const productCode = decodeURIComponent(pathSegments[0]);
1597
+ if (looksLikeResolveRequest(request.method, host, url)) {
1598
+ const productCode = decodeURIComponent(
1599
+ url.pathname.split("/").filter(Boolean)[0]
1600
+ );
1411
1601
  return addCorsHeaders(
1412
1602
  await handlePublicResolve(request, env, productCode),
1413
1603
  request
@@ -0,0 +1,36 @@
1
+ // Strict query-param validation for the ADR-0076 public resolver
2
+ // (img.snowcone.app). The grammar predicate lives in @snowcone-app/mockup-url
3
+ // (the wire-grammar SSOT); this module just turns "unknown keys" into the 400
4
+ // Response. Kept free of `cloudflare:workers` imports so unit tests can load
5
+ // it in plain node vitest (same pattern as src/signing.ts).
6
+
7
+ import {
8
+ unknownPublicParams,
9
+ unknownPublicParamsMessage,
10
+ } from "@snowcone-app/mockup-url";
11
+
12
+ /**
13
+ * If the public resolve URL carries any query key outside the public grammar,
14
+ * return a 400 JSON Response naming the offending key(s) and listing the
15
+ * allowed grammar (with `view=` → `mockup=` style hints). Returns null when
16
+ * every key is known.
17
+ *
18
+ * Rationale: the resolver used to silently ignore unknown params — a
19
+ * hand-edited `view=<sceneId>` returned the DEFAULT scene with zero feedback
20
+ * (4 different `view=` values → 4 identical images). Pre-launch, fail loudly.
21
+ */
22
+ export function rejectUnknownPublicParams(url: URL): Response | null {
23
+ const unknown = unknownPublicParams(url.searchParams);
24
+ if (unknown.length === 0) return null;
25
+ return new Response(
26
+ JSON.stringify({ error: unknownPublicParamsMessage(unknown) }),
27
+ {
28
+ status: 400,
29
+ headers: {
30
+ "Content-Type": "application/json",
31
+ // 4xx must never be cached as the image (ADR-0076 §7).
32
+ "Cache-Control": "no-store",
33
+ },
34
+ }
35
+ );
36
+ }
package/src/resolve.ts CHANGED
@@ -4,6 +4,48 @@
4
4
  // logic in `apps/www/app/api/harness/mockup/route.ts` (the prototype) and the
5
5
  // SDK's `getProduct`. Edge-safe: plain fetch + JSON. (ADR-0073 §10.)
6
6
 
7
+ import { PARAMS } from "@snowcone-app/mockup-url";
8
+
9
+ /** Paths reserved for the signer/utility surface — never treated as a productCode. */
10
+ const RESERVED_RESOLVE_PATHS = new Set([
11
+ "test-kv",
12
+ "mockups",
13
+ "sign",
14
+ "verify",
15
+ "_blank.png", // the house placeholder the `asset=default` token resolves to
16
+ ]);
17
+
18
+ /**
19
+ * Decide whether an incoming request is an ADR-0076 public resolve
20
+ * (`GET /{productCode}?asset[.key]=…&shop=…`) versus the signer surface.
21
+ *
22
+ * Routed by Host in prod (`img.snowcone.app`); the `img` label may also be
23
+ * interior behind the workspace-prefixed dev proxy (`lima-v2.img.lvh.me`).
24
+ * The single-host dev fallback accepts any artwork param — bare `asset=` or a
25
+ * multi-placement `asset.<key>=` — plus `shop=`, so a resolve is reachable
26
+ * without the custom domain binding.
27
+ */
28
+ export function looksLikeResolveRequest(
29
+ method: string,
30
+ host: string,
31
+ url: URL
32
+ ): boolean {
33
+ if (method !== "GET") return false;
34
+
35
+ const segments = url.pathname.split("/").filter(Boolean);
36
+ if (segments.length !== 1) return false;
37
+ if (RESERVED_RESOLVE_PATHS.has(segments[0])) return false;
38
+
39
+ const h = host.toLowerCase();
40
+ const isImgHost = h.startsWith("img.") || h.includes(".img.");
41
+ if (isImgHost) return true;
42
+
43
+ const hasAssetParam = [...url.searchParams.keys()].some(
44
+ (k) => k === PARAMS.asset || k.startsWith(`${PARAMS.asset}.`)
45
+ );
46
+ return hasAssetParam && url.searchParams.has(PARAMS.shop);
47
+ }
48
+
7
49
  export interface MeiliConfig {
8
50
  host: string;
9
51
  apiKey: string;
@@ -30,6 +72,25 @@ interface RawProduct {
30
72
  // Flat rows: each is `{ <AttrName>: <choiceLabel>, …, price, variantId }`.
31
73
  combinations?: Array<Record<string, unknown>>;
32
74
  };
75
+ album?: {
76
+ pagePlacement?: string;
77
+ pageAxis?: string;
78
+ pageExtent?: { min?: number; max?: number; step?: number };
79
+ };
80
+ }
81
+
82
+ /**
83
+ * The catalog `album` block (ADR-0086): one page placement repeats, the buyer
84
+ * picks the count. Catalog documents never enumerate `page_1..page_100` —
85
+ * consumers expand the page placement on demand from the extent.
86
+ */
87
+ export interface AlbumBlock {
88
+ /** Wire `key` of the repeating page placement (e.g. "page"). */
89
+ pagePlacement: string;
90
+ /** Name of the options attribute carrying the page count (e.g. "Pages"). */
91
+ pageAxis: string;
92
+ /** Buyable page counts: min..max in increments of step. */
93
+ pageExtent: { min: number; max: number; step: number };
33
94
  }
34
95
 
35
96
  export interface ResolvedPlacement {
@@ -51,6 +112,8 @@ export interface ResolvedProduct {
51
112
  attributes: Record<string, { affectsCombinations: boolean; choices: string[] }>;
52
113
  /** Normalized SKU rows: option selection → variant gvid. */
53
114
  combinations: { variantId: string; options: Record<string, string> }[];
115
+ /** The album block (ADR-0086), or null for ordinary products. */
116
+ album: AlbumBlock | null;
54
117
  }
55
118
 
56
119
  export interface ResolveDefaults {
@@ -69,7 +132,7 @@ export interface VariantResolution {
69
132
 
70
133
  const CACHE_TTL_SECONDS = 300; // 5 min — see ADR-0073 open question #1 (TTL vs event-driven)
71
134
  // Bump when ResolvedProduct's shape changes, so stale-shape cache entries are skipped.
72
- const CACHE_VERSION = "v2";
135
+ const CACHE_VERSION = "v3";
73
136
 
74
137
  /** Lowercase + collapse non-alphanumerics to `_` — the fallback slug for a
75
138
  * placement that has no catalog `key` yet (pre-P1). */
@@ -81,6 +144,62 @@ export function slugify(label: string): string {
81
144
  .replace(/^_+|_+$/g, "");
82
145
  }
83
146
 
147
+ /**
148
+ * Normalize a raw catalog `album` block (ADR-0086). Returns null unless every
149
+ * field is present and well-formed — a partial block is catalog drift, and a
150
+ * null here makes the product behave like any ordinary (non-album) product.
151
+ */
152
+ export function normalizeAlbum(raw: RawProduct["album"]): AlbumBlock | null {
153
+ if (!raw) return null;
154
+ const { pagePlacement, pageAxis, pageExtent } = raw;
155
+ if (typeof pagePlacement !== "string" || pagePlacement.length === 0) return null;
156
+ if (typeof pageAxis !== "string" || pageAxis.length === 0) return null;
157
+ const { min, max, step } = pageExtent ?? {};
158
+ if (
159
+ !Number.isInteger(min) ||
160
+ !Number.isInteger(max) ||
161
+ !Number.isInteger(step) ||
162
+ min! < 1 ||
163
+ max! < min! ||
164
+ step! < 1
165
+ ) {
166
+ return null;
167
+ }
168
+ return {
169
+ pagePlacement,
170
+ pageAxis,
171
+ pageExtent: { min: min!, max: max!, step: step! },
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Expand a `page_N` wire key against an album product (ADR-0086): the key
177
+ * `<album.pagePlacement>_<N>` (canonical positive integer, 1 ≤ N ≤
178
+ * pageExtent.max) resolves to the GEOMETRY of the repeating page placement —
179
+ * the catalog never enumerates pages. The returned placement keeps the
180
+ * caller's `page_N` key (the public address) but the base placement's label,
181
+ * so the render URL rendercenter sees is exactly the one it already knows.
182
+ * Null for non-album products, foreign keys, or out-of-range pages.
183
+ */
184
+ export function resolveAlbumPagePlacement(
185
+ product: ResolvedProduct,
186
+ key: string
187
+ ): ResolvedPlacement | null {
188
+ const album = product.album;
189
+ if (!album) return null;
190
+ const prefix = `${album.pagePlacement}_`;
191
+ if (!key.startsWith(prefix)) return null;
192
+ const suffix = key.slice(prefix.length);
193
+ // Canonical integers only ("page_07" would alias "page_7" into a second
194
+ // CDN cache key for identical pixels).
195
+ if (!/^[1-9][0-9]*$/.test(suffix)) return null;
196
+ const n = Number(suffix);
197
+ if (n > album.pageExtent.max) return null;
198
+ const base = product.placements.find((p) => p.key === album.pagePlacement);
199
+ if (!base) return null;
200
+ return { ...base, key };
201
+ }
202
+
84
203
  /** Fetch a product from Meilisearch (KV-cached). Returns null if not found. */
85
204
  export async function fetchProduct(
86
205
  productCode: string,
@@ -140,6 +259,7 @@ export async function fetchProduct(
140
259
  defaultGvid: raw.defaultGvid ?? null,
141
260
  attributes,
142
261
  combinations,
262
+ album: normalizeAlbum(raw.album),
143
263
  };
144
264
 
145
265
  await kv.put(cacheKey, JSON.stringify(resolved), {