@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/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # @snowcone-app/mockup-resolver
2
+
3
+ ## 1.0.2
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`342d320`](https://github.com/snowcone-app/snowcone-monorepo/commit/342d320998c062dc9f8db817a5bd2860ec8c23fc)]:
8
+ - @snowcone-app/mockup-url@0.2.0
9
+
10
+ ## 1.0.1
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [[`e1e9b7e`](https://github.com/snowcone-app/snowcone-monorepo/commit/e1e9b7e716d0d33c763e6a633ee540cd2aa24408)]:
15
+ - @snowcone-app/mockup-url@0.1.1
package/README.md CHANGED
@@ -96,6 +96,27 @@ curl "https://api.snowcone.app/v1/url-signer/sign?url=https://example.com/resour
96
96
  curl "https://api.snowcone.app/v1/url-signer/verify?url=https://example.com/resource.jpg?signature=xxx&expires=123456789"
97
97
  ```
98
98
 
99
+ ### Blank items (`asset=default`)
100
+
101
+ A reserved asset **value** renders a blank (un-printed) item, for every shop with
102
+ zero setup. Pass `default` in place of an artwork URL:
103
+
104
+ ```
105
+ https://img.snowcone.app/{productCode}?asset=default&shop=...
106
+ https://img.snowcone.app/{productCode}?asset.front=default&shop=... # per-placement
107
+ ```
108
+
109
+ The resolver substitutes the transparent `/_blank.png` this worker serves itself
110
+ (1×1, composites to nothing → a bare mockup). No hosting, no allowlist entry, no
111
+ per-shop setup.
112
+
113
+ Because the resolver injects this asset, it is **exempt from the L2 asset-origin
114
+ allowlist by provenance** (L2 only polices developer-supplied hosts). Omitting
115
+ artwork entirely still returns `400` — `default` is an explicit opt-in.
116
+
117
+ Future: a per-shop brand override could resolve `default` to the shop's own mark
118
+ instead of the transparent blank — the same URL, no caller change. Not built yet.
119
+
99
120
  ## Configuration
100
121
 
101
122
  The service is configured using `wrangler.toml`:
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@snowcone-app/mockup-resolver",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
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.0"
9
+ "@snowcone-app/mockup-url": "0.2.0"
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
+ }