@snowcone-app/mockup-resolver 1.0.1 → 1.0.3

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 CHANGED
@@ -1,5 +1,19 @@
1
1
  # @snowcone-app/mockup-resolver
2
2
 
3
+ ## 1.0.3
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`89893bc`](https://github.com/snowcone-app/snowcone-monorepo/commit/89893bc6e492d152dbd42d4887b5cd5c4cd51eb8)]:
8
+ - @snowcone-app/mockup-url@0.2.1
9
+
10
+ ## 1.0.2
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [[`342d320`](https://github.com/snowcone-app/snowcone-monorepo/commit/342d320998c062dc9f8db817a5bd2860ec8c23fc)]:
15
+ - @snowcone-app/mockup-url@0.2.0
16
+
3
17
  ## 1.0.1
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.1",
3
+ "version": "1.0.3",
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.1.1"
9
+ "@snowcone-app/mockup-url": "0.2.1"
10
10
  },
11
11
  "devDependencies": {
12
12
  "@cloudflare/workers-types": "^4.20250303.0",
@@ -0,0 +1,70 @@
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).
5
+ */
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
+ }
@@ -0,0 +1,104 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ // Resolve a `design=<pairingId|slug>` catalog reference (ADR-0086) to its
3
+ // render components from the public `snowcone-designs` Meilisearch index, with
4
+ // the same short-TTL KV cache pattern as ./resolve's fetchProduct. Membership
5
+ // in the index IS the license check: published ⇒ remixable ⇒ renderable, and
6
+ // de-indexing revokes render access. Edge-safe: plain fetch + JSON.
7
+
8
+ export interface DesignsMeiliConfig {
9
+ host: string;
10
+ apiKey: string;
11
+ /** The designs index uid, e.g. `snowcone-designs` / `snowcone-designs-dev`. */
12
+ index: string;
13
+ }
14
+
15
+ /** The slice of the public DesignDoc the resolver renders from. */
16
+ export interface ResolvedDesign {
17
+ pairingId: string;
18
+ slug: string | null;
19
+ /** The product the design was published against — must match the URL path. */
20
+ productId: string;
21
+ /** Bare-asset component (flattened full-canvas export). */
22
+ asset: string | null;
23
+ /** Per-placement components: public wire placement key → image URL. */
24
+ assets: Record<string, string> | null;
25
+ }
26
+
27
+ const CACHE_TTL_SECONDS = 300; // mirrors fetchProduct's product cache
28
+ const CACHE_VERSION = "v1";
29
+
30
+ interface RawDesignDoc {
31
+ pairingId?: string;
32
+ slug?: string | null;
33
+ productId?: string;
34
+ asset?: string | null;
35
+ assets?: Record<string, string> | null;
36
+ }
37
+
38
+ function toResolvedDesign(raw: RawDesignDoc): ResolvedDesign | null {
39
+ if (typeof raw.pairingId !== "string" || typeof raw.productId !== "string") {
40
+ return null;
41
+ }
42
+ const assets =
43
+ raw.assets && typeof raw.assets === "object" && !Array.isArray(raw.assets)
44
+ ? raw.assets
45
+ : null;
46
+ const asset = typeof raw.asset === "string" ? raw.asset : null;
47
+ if (!asset && (!assets || Object.keys(assets).length === 0)) return null;
48
+ return {
49
+ pairingId: raw.pairingId,
50
+ slug: typeof raw.slug === "string" ? raw.slug : null,
51
+ productId: raw.productId,
52
+ asset,
53
+ assets,
54
+ };
55
+ }
56
+
57
+ /**
58
+ * Look a design reference up in the catalog index (KV-cached). Tries the ref
59
+ * as the document id (= pairingId, the primary key) first, then as a `slug`
60
+ * filter. Returns null when the ref is not in the catalog — the caller 404s
61
+ * loudly (no fallback to URL-mode).
62
+ */
63
+ export async function fetchDesign(
64
+ ref: string,
65
+ meili: DesignsMeiliConfig,
66
+ kv: KVNamespace
67
+ ): Promise<ResolvedDesign | null> {
68
+ const cacheKey = `design:${CACHE_VERSION}:${ref}`;
69
+ const cached = await kv.get(cacheKey, "json");
70
+ if (cached) return cached as ResolvedDesign;
71
+
72
+ const headers = { Authorization: `Bearer ${meili.apiKey}` };
73
+
74
+ // 1. By document id (pairingId is the index primaryKey).
75
+ let raw: RawDesignDoc | null = null;
76
+ const byId = await fetch(
77
+ `${meili.host}/indexes/${meili.index}/documents/${encodeURIComponent(ref)}`,
78
+ { headers }
79
+ );
80
+ if (byId.ok) {
81
+ raw = (await byId.json()) as RawDesignDoc;
82
+ } else {
83
+ // 2. By slug (filterable attribute on the designs index).
84
+ const safe = ref.replace(/["\\]/g, "");
85
+ const search = await fetch(`${meili.host}/indexes/${meili.index}/search`, {
86
+ method: "POST",
87
+ headers: { ...headers, "Content-Type": "application/json" },
88
+ body: JSON.stringify({ q: "", filter: `slug = "${safe}"`, limit: 1 }),
89
+ });
90
+ if (search.ok) {
91
+ const body = (await search.json()) as { hits?: RawDesignDoc[] };
92
+ raw = body.hits?.[0] ?? null;
93
+ }
94
+ }
95
+ if (!raw) return null;
96
+
97
+ const resolved = toResolvedDesign(raw);
98
+ if (!resolved) return null;
99
+
100
+ await kv.put(cacheKey, JSON.stringify(resolved), {
101
+ expirationTtl: CACHE_TTL_SECONDS,
102
+ });
103
+ return resolved;
104
+ }
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
@@ -757,31 +763,16 @@ async function authenticate(
757
763
  return { authenticated: true, accountId };
758
764
  }
759
765
 
760
- // Helper function to convert glob-like pattern to RegExp
761
- function globToRegExp(glob: string): RegExp {
762
- let regexString = "^";
763
- for (let i = 0; i < glob.length; i++) {
764
- const char = glob[i];
765
- if (char === "*") {
766
- regexString += ".*?"; // Non-greedy match for any characters
767
- } else if (/[.+\[\]?^${}()|\-\\]/.test(char)) {
768
- // Corrected regex for special characters
769
- regexString += "\\" + char; // Escape them
770
- } else {
771
- regexString += char;
772
- }
773
- }
774
- regexString += "$";
775
- return new RegExp(regexString, "i"); // Added 'i' flag for case-insensitive matching
776
- }
777
-
778
766
  // NOTE: `isOriginAllowed` (the page-origin / domain allowlist matcher) was
779
767
  // removed alongside the `allowedOrigins` config — see the PublicData comment
780
- // above. `globToRegExp` is retained because the asset-source allowlist (L2,
781
- // `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.
782
771
 
783
772
  export { signUrl, verifyUrl } from "./signing";
784
773
  import { signUrl, verifyUrl } from "./signing";
774
+ import { checkAssetUrls } from "./asset-allowlist";
775
+ import { fetchDesign } from "./design-ref";
785
776
  import {
786
777
  buildMockupUrl,
787
778
  canonicalForSig,
@@ -794,8 +785,10 @@ import {
794
785
  import {
795
786
  fetchProduct,
796
787
  looksLikeResolveRequest,
788
+ resolveAlbumPagePlacement,
797
789
  resolveDefaults,
798
790
  resolveVariant,
791
+ type ResolvedPlacement,
799
792
  } from "./resolve";
800
793
  import { rejectUnknownPublicParams } from "./public-params";
801
794
 
@@ -1078,19 +1071,8 @@ function houseAssetUrl(request: Request): string {
1078
1071
  return `https://${new URL(request.url).host}${BLANK_PNG_PATH}`;
1079
1072
  }
1080
1073
 
1081
- /** Check a hostname against a glob allowlist (reuses globToRegExp). */
1082
- function isHostAllowed(host: string, allowlist: string[]): boolean {
1083
- if (allowlist.length === 0) return true; // unset = any
1084
- for (const pattern of allowlist) {
1085
- if (pattern === "*") return true;
1086
- try {
1087
- if (globToRegExp(pattern).test(host)) return true;
1088
- } catch {
1089
- // skip malformed pattern
1090
- }
1091
- }
1092
- return false;
1093
- }
1074
+ // L2 hostname matching + exempt-origin logic live in ./asset-allowlist
1075
+ // (pure module) so they run under the default unit-test glob.
1094
1076
 
1095
1077
  async function handlePublicResolve(
1096
1078
  request: Request,
@@ -1125,18 +1107,47 @@ async function handlePublicResolve(
1125
1107
  const design = parsed.design ?? {};
1126
1108
  const optionPicks = parsed.options ?? {};
1127
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;
1128
1113
  const key = q.get(PARAMS.shop);
1129
1114
  const widthParam = q.get(PARAMS.width);
1130
1115
  const mockupOverride = q.get(PARAMS.mockup) ?? undefined;
1131
1116
  const variantOverride = q.get(PARAMS.variant) ?? undefined;
1132
1117
  const placementOverride = q.get(PARAMS.placement) ?? undefined;
1118
+ const pageParam = q.get(PARAMS.page) ?? undefined;
1133
1119
  const aspectParam = q.get(PARAMS.aspect);
1134
1120
  const aspect: "16:9" | "2:3" | undefined =
1135
1121
  aspectParam === "2:3" ? "2:3" : aspectParam === "16:9" ? "16:9" : undefined;
1136
1122
 
1137
1123
  if (!productCode) return errResp(400, "Missing productCode in path");
1138
- if (!asset && designKeys.length === 0) {
1139
- 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
+ );
1140
1151
  }
1141
1152
  if (!key) return errResp(400, "Missing required query param: shop");
1142
1153
 
@@ -1167,17 +1178,14 @@ async function handlePublicResolve(
1167
1178
  }
1168
1179
 
1169
1180
  // 2b. L2 — asset-source allowlist (checked for EVERY image URL's hostname).
1170
- if (account.assetAllowlist && account.assetAllowlist.length > 0) {
1171
- for (const imageUrl of imageUrls) {
1172
- let assetHost: string;
1173
- try {
1174
- assetHost = new URL(imageUrl).hostname;
1175
- } catch {
1176
- return errResp(400, "Invalid asset URL");
1177
- }
1178
- if (!isHostAllowed(assetHost, account.assetAllowlist)) {
1179
- return errResp(403, "Asset source not allowed for this shop");
1180
- }
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);
1181
1189
  }
1182
1190
  }
1183
1191
 
@@ -1270,6 +1278,62 @@ async function handlePublicResolve(
1270
1278
  env.ACCOUNTS
1271
1279
  );
1272
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
+ }
1273
1337
  // 4a. Resolve the variant from option picks (both catalog shapes) + the
1274
1338
  // render-only optionSelections rendercenter needs. resolveDefaults then supplies
1275
1339
  // the mockup scene and a default placement (for the bare-asset case).
@@ -1285,6 +1349,9 @@ async function handlePublicResolve(
1285
1349
  if (!scene) {
1286
1350
  return errResp(422, `Product ${productCode} has no renderable combination`);
1287
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;
1288
1355
 
1289
1356
  // 4b. Build the design elements: a multi-placement map, or the single bare asset.
1290
1357
  const ALLOWED_TILES = [0.25, 0.5, 1, 2, 4];
@@ -1297,11 +1364,45 @@ async function handlePublicResolve(
1297
1364
  // "Unknown placement" instead of being silently coerced, and this matches the
1298
1365
  // buy worker's strict `placementByKey.get(key)`, so any URL that previews is
1299
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.
1300
1370
  const findPlacement = (k: string) =>
1301
- product.placements.find((p) => p.key === k);
1371
+ product.placements.find((p) => p.key === k) ??
1372
+ resolveAlbumPagePlacement(product, k);
1302
1373
 
1303
1374
  const designElements: DesignElement[] = [];
1304
- 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) {
1305
1406
  for (const k of designKeys) {
1306
1407
  const fill = design[k];
1307
1408
  const pl = findPlacement(k);
@@ -1376,6 +1477,12 @@ async function handlePublicResolve(
1376
1477
  // RELATIVE path+query minus seal). The developer never sees this secret.
1377
1478
  const signingSecret = env.URL_SIGNING_SECRET || "dev-unsigned";
1378
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
+ }
1379
1486
  const sigParams = new URLSearchParams(urlObj.search);
1380
1487
  sigParams.delete("seal");
1381
1488
  const relative = `${urlObj.pathname}?${sigParams.toString()}`;
package/src/resolve.ts CHANGED
@@ -72,6 +72,25 @@ interface RawProduct {
72
72
  // Flat rows: each is `{ <AttrName>: <choiceLabel>, …, price, variantId }`.
73
73
  combinations?: Array<Record<string, unknown>>;
74
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 };
75
94
  }
76
95
 
77
96
  export interface ResolvedPlacement {
@@ -93,6 +112,8 @@ export interface ResolvedProduct {
93
112
  attributes: Record<string, { affectsCombinations: boolean; choices: string[] }>;
94
113
  /** Normalized SKU rows: option selection → variant gvid. */
95
114
  combinations: { variantId: string; options: Record<string, string> }[];
115
+ /** The album block (ADR-0086), or null for ordinary products. */
116
+ album: AlbumBlock | null;
96
117
  }
97
118
 
98
119
  export interface ResolveDefaults {
@@ -111,7 +132,7 @@ export interface VariantResolution {
111
132
 
112
133
  const CACHE_TTL_SECONDS = 300; // 5 min — see ADR-0073 open question #1 (TTL vs event-driven)
113
134
  // Bump when ResolvedProduct's shape changes, so stale-shape cache entries are skipped.
114
- const CACHE_VERSION = "v2";
135
+ const CACHE_VERSION = "v3";
115
136
 
116
137
  /** Lowercase + collapse non-alphanumerics to `_` — the fallback slug for a
117
138
  * placement that has no catalog `key` yet (pre-P1). */
@@ -123,6 +144,62 @@ export function slugify(label: string): string {
123
144
  .replace(/^_+|_+$/g, "");
124
145
  }
125
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
+
126
203
  /** Fetch a product from Meilisearch (KV-cached). Returns null if not found. */
127
204
  export async function fetchProduct(
128
205
  productCode: string,
@@ -182,6 +259,7 @@ export async function fetchProduct(
182
259
  defaultGvid: raw.defaultGvid ?? null,
183
260
  attributes,
184
261
  combinations,
262
+ album: normalizeAlbum(raw.album),
185
263
  };
186
264
 
187
265
  await kv.put(cacheKey, JSON.stringify(resolved), {
@@ -0,0 +1,87 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { checkAssetUrls, isHostAllowed } from "../src/asset-allowlist";
3
+
4
+ /**
5
+ * L2 asset-origin allowlist. No origin is ever exempt (ADR-0086): catalog
6
+ * designs render by reference (`design=`) with resolver-injected components,
7
+ * so the old EXEMPT_ASSET_ORIGINS bypass is gone — every developer-supplied
8
+ * URL is checked against the shop's own allowlist, per-URL.
9
+ */
10
+
11
+ const ALLOWLIST = ["allowed.example.com", "*.cdn.example.com"];
12
+
13
+ describe("checkAssetUrls (L2)", () => {
14
+ it("passes everything when the allowlist is unset or empty", () => {
15
+ expect(
16
+ checkAssetUrls(["https://evil.example.com/a.png"], undefined).ok
17
+ ).toBe(true);
18
+ expect(checkAssetUrls(["https://evil.example.com/a.png"], []).ok).toBe(
19
+ true
20
+ );
21
+ });
22
+
23
+ it("403s an off-list origin", () => {
24
+ const verdict = checkAssetUrls(
25
+ ["https://evil.example.com/a.png"],
26
+ ALLOWLIST
27
+ );
28
+ expect(verdict).toEqual({
29
+ ok: false,
30
+ status: 403,
31
+ message: "Asset source not allowed for this shop",
32
+ });
33
+ });
34
+
35
+ it("passes an allowlisted origin (including glob patterns)", () => {
36
+ expect(
37
+ checkAssetUrls(["https://allowed.example.com/a.png"], ALLOWLIST).ok
38
+ ).toBe(true);
39
+ expect(
40
+ checkAssetUrls(["https://img.cdn.example.com/a.png"], ALLOWLIST).ok
41
+ ).toBe(true);
42
+ });
43
+
44
+ it("no origin is exempt — other shops' storage origins are off-list (ADR-0086)", () => {
45
+ const verdict = checkAssetUrls(
46
+ ["https://zzz999.storage.snowcone.app/exports/full.png"],
47
+ ALLOWLIST
48
+ );
49
+ expect(verdict.ok).toBe(false);
50
+ });
51
+
52
+ it("multi-placement mixed allowed + off-list still fails per-URL", () => {
53
+ const verdict = checkAssetUrls(
54
+ [
55
+ "https://allowed.example.com/front.png",
56
+ "https://evil.example.com/back.png",
57
+ ],
58
+ ALLOWLIST
59
+ );
60
+ expect(verdict).toEqual({
61
+ ok: false,
62
+ status: 403,
63
+ message: "Asset source not allowed for this shop",
64
+ });
65
+ });
66
+
67
+ it("400s an unparsable asset URL", () => {
68
+ const verdict = checkAssetUrls(["not a url"], ALLOWLIST);
69
+ expect(verdict).toEqual({
70
+ ok: false,
71
+ status: 400,
72
+ message: "Invalid asset URL",
73
+ });
74
+ });
75
+ });
76
+
77
+ describe("isHostAllowed", () => {
78
+ it("treats an empty allowlist as allow-any", () => {
79
+ expect(isHostAllowed("anything.example.com", [])).toBe(true);
80
+ });
81
+
82
+ it("matches case-insensitively and via globs", () => {
83
+ expect(isHostAllowed("Allowed.Example.COM", ALLOWLIST)).toBe(true);
84
+ expect(isHostAllowed("a.b.cdn.example.com", ALLOWLIST)).toBe(true);
85
+ expect(isHostAllowed("evil.example.com", ALLOWLIST)).toBe(false);
86
+ });
87
+ });
@@ -0,0 +1,139 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { fetchDesign } from "../src/design-ref";
3
+
4
+ /**
5
+ * `design=<pairingId|slug>` catalog lookup (ADR-0086): document-id fetch
6
+ * first, slug-filter search fallback, short-TTL KV cache, and a null (→ loud
7
+ * 404 at the caller) for refs that are not in the catalog.
8
+ */
9
+
10
+ const MEILI = {
11
+ host: "https://search.example",
12
+ apiKey: "public-key",
13
+ index: "snowcone-designs-dev",
14
+ };
15
+
16
+ const DOC = {
17
+ pairingId: "pairing-1",
18
+ slug: "watercolor-christmas-card",
19
+ productId: "KMYKUK",
20
+ asset: "https://abc.storage.snowcone.app/exports/full.png",
21
+ assets: { front: "https://abc.storage.snowcone.app/exports/front.png" },
22
+ };
23
+
24
+ function kvStub(seed: Record<string, string> = {}) {
25
+ const store = new Map(Object.entries(seed));
26
+ return {
27
+ get: vi.fn(async (k: string, _type?: string) => {
28
+ const v = store.get(k);
29
+ return v ? JSON.parse(v) : null;
30
+ }),
31
+ put: vi.fn(async (k: string, v: string) => {
32
+ store.set(k, v);
33
+ }),
34
+ store,
35
+ } as any;
36
+ }
37
+
38
+ afterEach(() => vi.unstubAllGlobals());
39
+
40
+ describe("fetchDesign", () => {
41
+ it("resolves by document id (pairingId) and caches the slice", async () => {
42
+ const fetchMock = vi.fn(async (url: string) => {
43
+ expect(url).toBe(
44
+ `${MEILI.host}/indexes/${MEILI.index}/documents/pairing-1`
45
+ );
46
+ return new Response(JSON.stringify(DOC), { status: 200 });
47
+ });
48
+ vi.stubGlobal("fetch", fetchMock);
49
+ const kv = kvStub();
50
+
51
+ const design = await fetchDesign("pairing-1", MEILI, kv);
52
+ expect(design).toEqual({
53
+ pairingId: "pairing-1",
54
+ slug: "watercolor-christmas-card",
55
+ productId: "KMYKUK",
56
+ asset: DOC.asset,
57
+ assets: DOC.assets,
58
+ });
59
+ expect(kv.put).toHaveBeenCalledOnce();
60
+
61
+ // Second call is served from KV — no further fetches.
62
+ await fetchDesign("pairing-1", MEILI, kv);
63
+ expect(fetchMock).toHaveBeenCalledTimes(1);
64
+ });
65
+
66
+ it("falls back to a slug-filter search when the id lookup 404s", async () => {
67
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
68
+ if (String(url).includes("/documents/")) {
69
+ return new Response("{}", { status: 404 });
70
+ }
71
+ expect(String(url)).toBe(`${MEILI.host}/indexes/${MEILI.index}/search`);
72
+ const body = JSON.parse(String(init?.body));
73
+ expect(body.filter).toBe('slug = "watercolor-christmas-card"');
74
+ return new Response(JSON.stringify({ hits: [DOC] }), { status: 200 });
75
+ });
76
+ vi.stubGlobal("fetch", fetchMock);
77
+
78
+ const design = await fetchDesign(
79
+ "watercolor-christmas-card",
80
+ MEILI,
81
+ kvStub()
82
+ );
83
+ expect(design?.pairingId).toBe("pairing-1");
84
+ });
85
+
86
+ it("strips quote/backslash from the ref before building the slug filter", async () => {
87
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
88
+ if (String(url).includes("/documents/")) {
89
+ return new Response("{}", { status: 404 });
90
+ }
91
+ const body = JSON.parse(String(init?.body));
92
+ expect(body.filter).toBe('slug = "x OR pairingId != "');
93
+ return new Response(JSON.stringify({ hits: [] }), { status: 200 });
94
+ });
95
+ vi.stubGlobal("fetch", fetchMock);
96
+
97
+ const design = await fetchDesign(
98
+ 'x" OR pairingId != "',
99
+ MEILI,
100
+ kvStub()
101
+ );
102
+ expect(design).toBeNull();
103
+ });
104
+
105
+ it("returns null (caller 404s loudly) for a ref not in the catalog", async () => {
106
+ vi.stubGlobal(
107
+ "fetch",
108
+ vi.fn(async (url: string) =>
109
+ String(url).includes("/documents/")
110
+ ? new Response("{}", { status: 404 })
111
+ : new Response(JSON.stringify({ hits: [] }), { status: 200 })
112
+ )
113
+ );
114
+ const kv = kvStub();
115
+ expect(await fetchDesign("nope", MEILI, kv)).toBeNull();
116
+ // Misses are NOT cached — a just-synced design becomes renderable
117
+ // immediately.
118
+ expect(kv.put).not.toHaveBeenCalled();
119
+ });
120
+
121
+ it("returns null for a doc with nothing renderable (no asset, no assets)", async () => {
122
+ vi.stubGlobal(
123
+ "fetch",
124
+ vi.fn(
125
+ async () =>
126
+ new Response(
127
+ JSON.stringify({
128
+ pairingId: "p2",
129
+ productId: "KMYKUK",
130
+ asset: null,
131
+ assets: {},
132
+ }),
133
+ { status: 200 }
134
+ )
135
+ )
136
+ );
137
+ expect(await fetchDesign("p2", MEILI, kvStub())).toBeNull();
138
+ });
139
+ });
@@ -14,12 +14,12 @@ import { rejectUnknownPublicParams } from '../src/public-params'
14
14
 
15
15
  describe('isKnownPublicParam', () => {
16
16
  it('accepts every exact public param name', () => {
17
- for (const name of ['asset', 'shop', 'placement', 'variant', 'mockup', 'width', 'aspect', 'signature']) {
17
+ for (const name of ['asset', 'design', 'shop', 'placement', 'page', 'variant', 'mockup', 'width', 'aspect', 'signature']) {
18
18
  expect(isKnownPublicParam(name), name).toBe(true)
19
19
  }
20
20
  // The exported list matches the grammar exactly (no extras, no omissions).
21
21
  expect([...PUBLIC_PARAM_NAMES].sort()).toEqual(
22
- ['aspect', 'asset', 'mockup', 'placement', 'shop', 'signature', 'variant', 'width'],
22
+ ['aspect', 'asset', 'design', 'mockup', 'page', 'placement', 'shop', 'signature', 'variant', 'width'],
23
23
  )
24
24
  })
25
25
 
@@ -59,6 +59,16 @@ describe('unknownPublicParams', () => {
59
59
  expect(unknownPublicParams(url.searchParams)).toEqual([])
60
60
  })
61
61
 
62
+ it('returns [] for a catalog design reference (ADR-0086)', () => {
63
+ const url = new URL('https://img.snowcone.app/tee?design=watercolor-christmas-card&shop=abc123')
64
+ expect(unknownPublicParams(url.searchParams)).toEqual([])
65
+ })
66
+
67
+ it('returns [] for an album page selector (ADR-0086 §5)', () => {
68
+ const url = new URL('https://img.snowcone.app/album?asset=https%3A%2F%2Fx%2Fa.png&shop=abc123&page=3')
69
+ expect(unknownPublicParams(url.searchParams)).toEqual([])
70
+ })
71
+
62
72
  it('names unknown keys, deduped, in first-seen order', () => {
63
73
  const url = new URL(
64
74
  'https://img.snowcone.app/tee?asset=x&view=a&shop=abc123&view=b&foo=1',
@@ -1,6 +1,8 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import {
3
3
  looksLikeResolveRequest,
4
+ normalizeAlbum,
5
+ resolveAlbumPagePlacement,
4
6
  resolveVariant,
5
7
  slugify,
6
8
  type ResolvedProduct,
@@ -18,6 +20,7 @@ const tee: ResolvedProduct = {
18
20
  { variantId: "qS", options: { Size: "S" } },
19
21
  { variantId: "qM", options: { Size: "M" } },
20
22
  ],
23
+ album: null,
21
24
  };
22
25
 
23
26
  // The cap: NO combinations; render-only attributes (resolve via defaultGvid).
@@ -32,6 +35,7 @@ const cap: ResolvedProduct = {
32
35
  Pocket: { affectsCombinations: false, choices: ["None", "Left chest"] },
33
36
  },
34
37
  combinations: [],
38
+ album: null,
35
39
  };
36
40
 
37
41
  describe("resolveVariant", () => {
@@ -67,6 +71,7 @@ describe("resolveVariant", () => {
67
71
  defaultGvid: null,
68
72
  attributes: {},
69
73
  combinations: [],
74
+ album: null,
70
75
  };
71
76
  expect(resolveVariant(empty, {})).toBeNull();
72
77
  });
@@ -150,6 +155,111 @@ describe("looksLikeResolveRequest", () => {
150
155
  });
151
156
  });
152
157
 
158
+ // An album (ADR-0086): covers enumerated, ONE page placement that repeats.
159
+ const album: ResolvedProduct = {
160
+ id: "ALBUM1",
161
+ variants: [{ gvid: "gA" }],
162
+ mockups: [],
163
+ placements: [
164
+ { key: "front_cover", label: "Front cover", type: "image", width: 3000, height: 3000 },
165
+ { key: "page", label: "Page", type: "image", width: 2400, height: 2400 },
166
+ { key: "spine", label: "Spine", type: "image", width: 200, height: 3000 },
167
+ ],
168
+ defaultGvid: "gA",
169
+ attributes: { Pages: { affectsCombinations: true, choices: ["20", "24"] } },
170
+ combinations: [],
171
+ album: {
172
+ pagePlacement: "page",
173
+ pageAxis: "Pages",
174
+ pageExtent: { min: 20, max: 100, step: 4 },
175
+ },
176
+ };
177
+
178
+ describe("resolveAlbumPagePlacement", () => {
179
+ it("expands page_N to the repeating placement's geometry (catalog never enumerates pages)", () => {
180
+ const pl = resolveAlbumPagePlacement(album, "page_3");
181
+ expect(pl).toEqual({
182
+ key: "page_3", // the public wire address is kept…
183
+ label: "Page", // …but the label is the base placement's (render wire unchanged)
184
+ type: "image",
185
+ width: 2400,
186
+ height: 2400,
187
+ });
188
+ });
189
+
190
+ it("accepts the full extent (1..pageExtent.max)", () => {
191
+ expect(resolveAlbumPagePlacement(album, "page_1")?.key).toBe("page_1");
192
+ expect(resolveAlbumPagePlacement(album, "page_100")?.key).toBe("page_100");
193
+ });
194
+
195
+ it("rejects out-of-range and non-canonical page numbers", () => {
196
+ expect(resolveAlbumPagePlacement(album, "page_0")).toBeNull();
197
+ expect(resolveAlbumPagePlacement(album, "page_101")).toBeNull();
198
+ expect(resolveAlbumPagePlacement(album, "page_07")).toBeNull(); // would alias page_7
199
+ expect(resolveAlbumPagePlacement(album, "page_x")).toBeNull();
200
+ expect(resolveAlbumPagePlacement(album, "page_")).toBeNull();
201
+ });
202
+
203
+ it("only expands the album's pagePlacement, never other placements", () => {
204
+ expect(resolveAlbumPagePlacement(album, "front_cover_2")).toBeNull();
205
+ expect(resolveAlbumPagePlacement(album, "spine_1")).toBeNull();
206
+ });
207
+
208
+ it("returns null for non-album products (byte-identical behavior today)", () => {
209
+ expect(resolveAlbumPagePlacement(tee, "page_3")).toBeNull();
210
+ });
211
+
212
+ it("returns null when the album names a placement the doc no longer has", () => {
213
+ const drifted: ResolvedProduct = {
214
+ ...album,
215
+ placements: album.placements.filter((p) => p.key !== "page"),
216
+ };
217
+ expect(resolveAlbumPagePlacement(drifted, "page_3")).toBeNull();
218
+ });
219
+ });
220
+
221
+ describe("normalizeAlbum", () => {
222
+ it("passes a well-formed block through", () => {
223
+ expect(
224
+ normalizeAlbum({
225
+ pagePlacement: "page",
226
+ pageAxis: "Pages",
227
+ pageExtent: { min: 20, max: 100, step: 4 },
228
+ })
229
+ ).toEqual({
230
+ pagePlacement: "page",
231
+ pageAxis: "Pages",
232
+ pageExtent: { min: 20, max: 100, step: 4 },
233
+ });
234
+ });
235
+
236
+ it("rejects missing or malformed blocks (the product behaves as non-album)", () => {
237
+ expect(normalizeAlbum(undefined)).toBeNull();
238
+ expect(normalizeAlbum({ pagePlacement: "page" })).toBeNull();
239
+ expect(
240
+ normalizeAlbum({
241
+ pagePlacement: "page",
242
+ pageAxis: "Pages",
243
+ pageExtent: { min: 100, max: 20, step: 4 }, // max < min
244
+ })
245
+ ).toBeNull();
246
+ expect(
247
+ normalizeAlbum({
248
+ pagePlacement: "",
249
+ pageAxis: "Pages",
250
+ pageExtent: { min: 20, max: 100, step: 4 },
251
+ })
252
+ ).toBeNull();
253
+ expect(
254
+ normalizeAlbum({
255
+ pagePlacement: "page",
256
+ pageAxis: "Pages",
257
+ pageExtent: { min: 20, max: 100, step: 0 },
258
+ })
259
+ ).toBeNull();
260
+ });
261
+ });
262
+
153
263
  describe("slugify", () => {
154
264
  it("derives URL-safe placement keys from labels", () => {
155
265
  expect(slugify("Front")).toBe("front");
package/wrangler.jsonc CHANGED
@@ -38,7 +38,10 @@
38
38
  "MEILISEARCH_API_KEY": "eee819b849798ad9091228c486ec05d0931e5292",
39
39
  "MEILISEARCH_INDEX": "snowcone",
40
40
  "MOCKUP_BASE_URL": "https://cdn.snowcone.app",
41
- "KV_CACHE_BASE_URL": "https://api.snowcone.app"
41
+ "KV_CACHE_BASE_URL": "https://api.snowcone.app",
42
+ // Designs catalog (ADR-0086): the index `design=<pairingId|slug>` resolves
43
+ // against, read with the same public search key.
44
+ "MEILISEARCH_DESIGNS_INDEX": "snowcone-designs"
42
45
  },
43
46
  "kv_namespaces": [
44
47
  {
@@ -63,7 +66,9 @@
63
66
  "MEILISEARCH_API_KEY": "eee819b849798ad9091228c486ec05d0931e5292",
64
67
  "MEILISEARCH_INDEX": "snowcone-dev",
65
68
  "MOCKUP_BASE_URL": "https://cdn.snowcone.app",
66
- "KV_CACHE_BASE_URL": "http://localhost:4000"
69
+ "KV_CACHE_BASE_URL": "http://localhost:4000",
70
+ // See top-level MEILISEARCH_DESIGNS_INDEX comment.
71
+ "MEILISEARCH_DESIGNS_INDEX": "snowcone-designs-dev"
67
72
  },
68
73
  "kv_namespaces": [
69
74
  {