@snowcone-app/mockup-resolver 1.0.0

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/resolve.ts ADDED
@@ -0,0 +1,240 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ // Resolve a productCode → (variant gvid, mockup scene, placement geometry, option
3
+ // picks) at the edge, from Meilisearch, with a short-TTL KV cache. Mirrors the
4
+ // logic in `apps/www/app/api/harness/mockup/route.ts` (the prototype) and the
5
+ // SDK's `getProduct`. Edge-safe: plain fetch + JSON. (ADR-0073 §10.)
6
+
7
+ export interface MeiliConfig {
8
+ host: string;
9
+ apiKey: string;
10
+ index: string;
11
+ }
12
+
13
+ interface RawProduct {
14
+ id: string;
15
+ placements?: {
16
+ key?: string;
17
+ label: string;
18
+ type?: string | null;
19
+ width?: number;
20
+ height?: number;
21
+ }[];
22
+ variants?: { gvid?: string; id?: string }[];
23
+ mockups?: { id: string; gvids?: string[] }[];
24
+ defaultGvid?: string | null;
25
+ options?: {
26
+ attributes?: Record<
27
+ string,
28
+ { affectsCombinations?: boolean; choices?: { label?: string }[] }
29
+ >;
30
+ // Flat rows: each is `{ <AttrName>: <choiceLabel>, …, price, variantId }`.
31
+ combinations?: Array<Record<string, unknown>>;
32
+ };
33
+ }
34
+
35
+ export interface ResolvedPlacement {
36
+ /** URL-safe slug (catalog `key`, or a slug derived from `label` as a fallback). */
37
+ key: string;
38
+ label: string;
39
+ type: "image" | "color";
40
+ width: number;
41
+ height: number;
42
+ }
43
+
44
+ export interface ResolvedProduct {
45
+ id: string;
46
+ variants: { gvid: string }[];
47
+ mockups: { id: string; gvids: string[] }[];
48
+ placements: ResolvedPlacement[];
49
+ defaultGvid: string | null;
50
+ /** Attribute name → metadata (whether it selects a SKU + its choice labels). */
51
+ attributes: Record<string, { affectsCombinations: boolean; choices: string[] }>;
52
+ /** Normalized SKU rows: option selection → variant gvid. */
53
+ combinations: { variantId: string; options: Record<string, string> }[];
54
+ }
55
+
56
+ export interface ResolveDefaults {
57
+ variantId: string;
58
+ mockupId: string;
59
+ placement: ResolvedPlacement;
60
+ }
61
+
62
+ export interface VariantResolution {
63
+ /** The resolved variant gvid. */
64
+ variantId: string;
65
+ /** Render-only picks (`affectsCombinations:false`) → `{ attrName: choiceLabel }`,
66
+ * canonicalized to the catalog's label casing for rendercenter's matcher. */
67
+ optionSelections: Record<string, string>;
68
+ }
69
+
70
+ const CACHE_TTL_SECONDS = 300; // 5 min — see ADR-0073 open question #1 (TTL vs event-driven)
71
+ // Bump when ResolvedProduct's shape changes, so stale-shape cache entries are skipped.
72
+ const CACHE_VERSION = "v2";
73
+
74
+ /** Lowercase + collapse non-alphanumerics to `_` — the fallback slug for a
75
+ * placement that has no catalog `key` yet (pre-P1). */
76
+ export function slugify(label: string): string {
77
+ return label
78
+ .trim()
79
+ .toLowerCase()
80
+ .replace(/[^a-z0-9]+/g, "_")
81
+ .replace(/^_+|_+$/g, "");
82
+ }
83
+
84
+ /** Fetch a product from Meilisearch (KV-cached). Returns null if not found. */
85
+ export async function fetchProduct(
86
+ productCode: string,
87
+ meili: MeiliConfig,
88
+ kv: KVNamespace
89
+ ): Promise<ResolvedProduct | null> {
90
+ const cacheKey = `prod:${CACHE_VERSION}:${productCode}`;
91
+ const cached = await kv.get(cacheKey, "json");
92
+ if (cached) return cached as ResolvedProduct;
93
+
94
+ const url = `${meili.host}/indexes/${meili.index}/documents/${encodeURIComponent(productCode)}`;
95
+ const res = await fetch(url, {
96
+ headers: { Authorization: `Bearer ${meili.apiKey}` },
97
+ });
98
+ if (!res.ok) return null;
99
+
100
+ const raw = (await res.json()) as RawProduct;
101
+
102
+ const rawAttrs = raw.options?.attributes ?? {};
103
+ const attributes: ResolvedProduct["attributes"] = {};
104
+ for (const [name, meta] of Object.entries(rawAttrs)) {
105
+ attributes[name] = {
106
+ // Default true: an attribute selects a SKU unless explicitly marked otherwise.
107
+ affectsCombinations: meta.affectsCombinations !== false,
108
+ choices: (meta.choices ?? [])
109
+ .map((c) => c.label)
110
+ .filter((l): l is string => typeof l === "string"),
111
+ };
112
+ }
113
+ const attributeNames = Object.keys(attributes);
114
+
115
+ const combinations: ResolvedProduct["combinations"] = [];
116
+ for (const row of raw.options?.combinations ?? []) {
117
+ const variantId = typeof row.variantId === "string" ? row.variantId : "";
118
+ if (!variantId) continue;
119
+ const options: Record<string, string> = {};
120
+ for (const name of attributeNames) {
121
+ const v = row[name];
122
+ if (typeof v === "string") options[name] = v;
123
+ }
124
+ combinations.push({ variantId, options });
125
+ }
126
+
127
+ const resolved: ResolvedProduct = {
128
+ id: raw.id,
129
+ variants: (raw.variants ?? [])
130
+ .map((v) => ({ gvid: v.gvid ?? v.id ?? "" }))
131
+ .filter((v) => v.gvid),
132
+ mockups: (raw.mockups ?? []).map((m) => ({ id: m.id, gvids: m.gvids ?? [] })),
133
+ placements: (raw.placements ?? []).map((p) => ({
134
+ key: p.key && p.key.length > 0 ? p.key : slugify(p.label),
135
+ label: p.label,
136
+ type: p.type === "color" ? "color" : "image",
137
+ width: p.width ?? 4000,
138
+ height: p.height ?? 4000,
139
+ })),
140
+ defaultGvid: raw.defaultGvid ?? null,
141
+ attributes,
142
+ combinations,
143
+ };
144
+
145
+ await kv.put(cacheKey, JSON.stringify(resolved), {
146
+ expirationTtl: CACHE_TTL_SECONDS,
147
+ });
148
+ return resolved;
149
+ }
150
+
151
+ /**
152
+ * Pick the default variant / mockup scene / placement, honoring any caller
153
+ * overrides. Returns null if the product can't yield a renderable combination.
154
+ * (Same precedence as the harness facade prototype.)
155
+ */
156
+ export function resolveDefaults(
157
+ product: ResolvedProduct,
158
+ overrides: { variant?: string; mockupId?: string; placement?: string }
159
+ ): ResolveDefaults | null {
160
+ const variantId =
161
+ overrides.variant ?? product.defaultGvid ?? product.variants[0]?.gvid;
162
+ if (!variantId) return null;
163
+
164
+ const mockup =
165
+ (overrides.mockupId
166
+ ? product.mockups.find((m) => m.id === overrides.mockupId)
167
+ : undefined) ??
168
+ product.mockups.find((m) => m.gvids.includes(variantId)) ??
169
+ product.mockups[0];
170
+ if (!mockup) return null;
171
+
172
+ const placement =
173
+ (overrides.placement
174
+ ? product.placements.find((p) => p.label === overrides.placement)
175
+ : undefined) ?? product.placements[0];
176
+ if (!placement) return null;
177
+
178
+ return { variantId, mockupId: mockup.id, placement };
179
+ }
180
+
181
+ /**
182
+ * Resolve public option picks (`opt.<attr>=<choice>`, matched case-insensitively)
183
+ * to a variant gvid + the render-only `optionSelections` rendercenter consumes.
184
+ *
185
+ * Two catalog shapes (see ADR / multi-placement spec):
186
+ * - **with `combinations`** (size/color tees): combination-affecting picks select
187
+ * the matching SKU row's `variantId`.
188
+ * - **without** (the cap): the variant is the default; all picks are render-only.
189
+ *
190
+ * Render-only picks are canonicalized to the catalog's exact choice-label casing
191
+ * (rendercenter matches `choice.label` case-sensitively for underlays).
192
+ * Returns null only if no variant can be determined at all.
193
+ */
194
+ export function resolveVariant(
195
+ product: ResolvedProduct,
196
+ picks: Record<string, string>,
197
+ variantOverride?: string
198
+ ): VariantResolution | null {
199
+ const attrs = product.attributes ?? {};
200
+ const combinations = product.combinations ?? [];
201
+
202
+ // Case-insensitive attribute-name lookup.
203
+ const attrByLower = new Map<string, string>();
204
+ for (const name of Object.keys(attrs)) attrByLower.set(name.toLowerCase(), name);
205
+
206
+ const combinationPicks: Record<string, string> = {};
207
+ const optionSelections: Record<string, string> = {};
208
+ for (const [rawAttr, rawChoice] of Object.entries(picks)) {
209
+ const attrName = attrByLower.get(rawAttr.toLowerCase()) ?? rawAttr;
210
+ const meta = attrs[attrName];
211
+ // Unknown attr defaults to combination-affecting only if combinations exist.
212
+ const affects = meta ? meta.affectsCombinations : combinations.length > 0;
213
+ if (affects) {
214
+ combinationPicks[attrName] = rawChoice;
215
+ } else {
216
+ // Canonicalize to the catalog's exact label casing where a choice matches.
217
+ const exact = meta?.choices.find(
218
+ (c) => c.toLowerCase() === rawChoice.toLowerCase()
219
+ );
220
+ optionSelections[attrName] = exact ?? rawChoice;
221
+ }
222
+ }
223
+
224
+ let variantId = variantOverride;
225
+ if (!variantId) {
226
+ if (combinations.length > 0 && Object.keys(combinationPicks).length > 0) {
227
+ const row = combinations.find((c) =>
228
+ Object.entries(combinationPicks).every(
229
+ ([attr, val]) => (c.options[attr] ?? "").toLowerCase() === val.toLowerCase()
230
+ )
231
+ );
232
+ variantId = row?.variantId;
233
+ }
234
+ variantId =
235
+ variantId ?? product.defaultGvid ?? product.variants[0]?.gvid ?? undefined;
236
+ }
237
+ if (!variantId) return null;
238
+
239
+ return { variantId, optionSelections };
240
+ }
package/src/signing.ts ADDED
@@ -0,0 +1,42 @@
1
+ // Pure URL signing — uses Web Crypto, no Cloudflare-runtime imports.
2
+ // Extracted from index.ts so unit tests can import it without pulling in
3
+ // `cloudflare:workers` (which only resolves in the Workers runtime).
4
+
5
+ export async function signUrl(url: string, secretKey: string): Promise<string> {
6
+ const encoder = new TextEncoder();
7
+ const urlData = encoder.encode(url);
8
+
9
+ const key = await crypto.subtle.importKey(
10
+ "raw",
11
+ encoder.encode(secretKey),
12
+ { name: "HMAC", hash: "SHA-256" },
13
+ false,
14
+ ["sign"]
15
+ );
16
+
17
+ const signature = await crypto.subtle.sign("HMAC", key, urlData);
18
+
19
+ // Truncate to first 8 bytes, hex-encode.
20
+ const fullDigest = new Uint8Array(signature);
21
+ const truncatedDigest = fullDigest.slice(0, 8);
22
+ return Array.from(truncatedDigest)
23
+ .map((b) => b.toString(16).padStart(2, "0"))
24
+ .join("");
25
+ }
26
+
27
+ export async function verifyUrl(
28
+ url: string,
29
+ signature: string,
30
+ secretKey: string
31
+ ): Promise<boolean> {
32
+ const expectedSignature = await signUrl(url, secretKey);
33
+
34
+ if (expectedSignature.length !== signature.length) return false;
35
+
36
+ // Constant-time comparison to prevent timing attacks.
37
+ let result = 0;
38
+ for (let i = 0; i < expectedSignature.length; i++) {
39
+ result |= expectedSignature.charCodeAt(i) ^ signature.charCodeAt(i);
40
+ }
41
+ return result === 0;
42
+ }
@@ -0,0 +1,42 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ // Imports come from signing.ts directly so the unit test doesn't pull in
4
+ // the Cloudflare worker entry (which references `cloudflare:workers` and
5
+ // can't load in a plain node vitest environment). The worker-runtime tests
6
+ // live in test/integration/worker.test.ts and are excluded from `pnpm test`.
7
+ import { signUrl, verifyUrl } from '../src/signing'
8
+
9
+ describe('Mockup Resolver', () => {
10
+ const SECRET_KEY = 'test-secret-key'
11
+ const TEST_URL = 'https://example.com/some/path?query=value'
12
+
13
+ it('should generate URL signatures', async () => {
14
+ const signature = await signUrl(TEST_URL, SECRET_KEY)
15
+
16
+ // Check that signature has the expected format (16 hex characters)
17
+ expect(signature).toMatch(/^[0-9a-f]{16}$/)
18
+ })
19
+
20
+ it('should verify valid signatures', async () => {
21
+ const signature = await signUrl(TEST_URL, SECRET_KEY)
22
+ const isValid = await verifyUrl(TEST_URL, signature, SECRET_KEY)
23
+
24
+ expect(isValid).toBe(true)
25
+ })
26
+
27
+ it('should reject invalid signatures', async () => {
28
+ const signature = await signUrl(TEST_URL, SECRET_KEY)
29
+ const tamperedSignature = signature.replace(/^./, 'f') // Tamper with the first character
30
+
31
+ const isValid = await verifyUrl(TEST_URL, tamperedSignature, SECRET_KEY)
32
+ expect(isValid).toBe(false)
33
+ })
34
+
35
+ it('should reject signatures for different URLs', async () => {
36
+ const signature = await signUrl(TEST_URL, SECRET_KEY)
37
+ const differentUrl = TEST_URL + '&additional=param'
38
+
39
+ const isValid = await verifyUrl(differentUrl, signature, SECRET_KEY)
40
+ expect(isValid).toBe(false)
41
+ })
42
+ })
@@ -0,0 +1,196 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ const BASE_URL = process.env.MOCKUP_RESOLVER_URL || 'http://localhost:8102'
4
+ const TEST_URL = 'https://example.com/image.jpg'
5
+ const TEST_ACCOUNT_ID = 'account123' // Test account ID to use
6
+
7
+ // Test data for our accounts
8
+ const TEST_ACCOUNTS = {
9
+ valid: {
10
+ accountId: TEST_ACCOUNT_ID,
11
+ apiKeys: {
12
+ valid: 'test-api-key-1',
13
+ invalid: 'invalid-api-key', // Should fail
14
+ dev: 'dev-api-key',
15
+ },
16
+ clientIds: {
17
+ valid: {
18
+ id: 'dev_client',
19
+ origin: 'http://localhost:3000',
20
+ },
21
+ },
22
+ },
23
+ invalid: {
24
+ accountId: 'invalid-account', // Should fail
25
+ apiKey: 'test-api-key-1',
26
+ clientId: 'dev_client',
27
+ },
28
+ }
29
+
30
+ interface SignResponse {
31
+ signature: string
32
+ urlWithSignature?: string
33
+ }
34
+
35
+ interface VerifyResponse {
36
+ valid: boolean
37
+ }
38
+
39
+ describe('Mockup Resolver Integration Tests', () => {
40
+ // Helper function to add the accountId parameter directly to the URL being signed
41
+ function addAccountIdToSignedUrl(url: string, accountId = TEST_ACCOUNT_ID): string {
42
+ return `${url}${url.includes('?') ? '&' : '?'}accountId=${accountId}`
43
+ }
44
+
45
+ it('should authenticate with valid API key', async () => {
46
+ console.log('🌸 🌸 🌸 BASE_URL:', BASE_URL)
47
+ const urlToSign = addAccountIdToSignedUrl(TEST_URL)
48
+ const response = await fetch(`${BASE_URL}/sign?url=${encodeURIComponent(urlToSign)}`, {
49
+ headers: {
50
+ 'x-api-key': TEST_ACCOUNTS.valid.apiKeys.valid,
51
+ },
52
+ })
53
+
54
+ expect(response.ok).toBe(true)
55
+ const data = (await response.json()) as SignResponse
56
+ expect(data.signature).toBeDefined()
57
+ expect(typeof data.signature).toBe('string')
58
+ expect(data.signature.length).toBeGreaterThan(0)
59
+ })
60
+
61
+ it('should reject invalid API key', async () => {
62
+ const urlToSign = addAccountIdToSignedUrl(TEST_URL)
63
+ const response = await fetch(`${BASE_URL}/sign?url=${encodeURIComponent(urlToSign)}`, {
64
+ headers: {
65
+ 'x-api-key': TEST_ACCOUNTS.valid.apiKeys.invalid,
66
+ },
67
+ })
68
+
69
+ expect(response.status).toBe(401)
70
+ })
71
+
72
+ it('should authenticate with valid client ID and origin', async () => {
73
+ const validClient = TEST_ACCOUNTS.valid.clientIds.valid
74
+ const urlToSign = addAccountIdToSignedUrl(TEST_URL)
75
+ const response = await fetch(
76
+ `${BASE_URL}/sign?url=${encodeURIComponent(urlToSign)}&clientId=${validClient.id}`,
77
+ {
78
+ headers: {
79
+ Origin: validClient.origin,
80
+ },
81
+ },
82
+ )
83
+
84
+ expect(response.ok).toBe(true)
85
+ const data = (await response.json()) as SignResponse
86
+ expect(data.signature).toBeDefined()
87
+ })
88
+
89
+ it('should reject invalid client ID', async () => {
90
+ const urlToSign = addAccountIdToSignedUrl(TEST_URL)
91
+ const response = await fetch(
92
+ `${BASE_URL}/sign?url=${encodeURIComponent(urlToSign)}&clientId=non-existent-client`,
93
+ {
94
+ headers: {
95
+ Origin: TEST_ACCOUNTS.valid.clientIds.valid.origin,
96
+ },
97
+ },
98
+ )
99
+
100
+ expect(response.status).toBe(401)
101
+ })
102
+
103
+ it('should reject requests with no authentication', async () => {
104
+ const urlToSign = addAccountIdToSignedUrl(TEST_URL)
105
+ const response = await fetch(`${BASE_URL}/sign?url=${encodeURIComponent(urlToSign)}`)
106
+
107
+ expect(response.status).toBe(401)
108
+ })
109
+
110
+ it('should require accountId parameter', async () => {
111
+ const response = await fetch(`${BASE_URL}/sign?url=${encodeURIComponent(TEST_URL)}`, {
112
+ headers: {
113
+ 'x-api-key': TEST_ACCOUNTS.valid.apiKeys.valid,
114
+ },
115
+ })
116
+
117
+ expect(response.status).toBe(401)
118
+ const errorData = (await response.json()) as { error: string }
119
+ expect(errorData.error).toContain('accountId in the URL')
120
+ })
121
+
122
+ it('should reject requests for invalid accounts', async () => {
123
+ const urlToSign = `${TEST_URL}${TEST_URL.includes('?') ? '&' : '?'}accountId=${
124
+ TEST_ACCOUNTS.invalid.accountId
125
+ }`
126
+ const response = await fetch(`${BASE_URL}/sign?url=${encodeURIComponent(urlToSign)}`, {
127
+ headers: {
128
+ 'x-api-key': TEST_ACCOUNTS.invalid.apiKey,
129
+ },
130
+ })
131
+
132
+ expect(response.status).toBe(401)
133
+ const errorData = (await response.json()) as { error: string }
134
+ expect(errorData.error).toContain('Unknown account')
135
+ })
136
+
137
+ it('should sign and verify URLs', async () => {
138
+ // First, get a signature
139
+ const urlToSign = addAccountIdToSignedUrl(TEST_URL)
140
+ const signResponse = await fetch(`${BASE_URL}/sign?url=${encodeURIComponent(urlToSign)}`, {
141
+ headers: {
142
+ 'x-api-key': TEST_ACCOUNTS.valid.apiKeys.valid,
143
+ },
144
+ })
145
+
146
+ expect(signResponse.ok).toBe(true)
147
+ const { signature } = (await signResponse.json()) as SignResponse
148
+ expect(signature).toBeDefined()
149
+
150
+ // Then verify it
151
+ const verifyResponse = await fetch(
152
+ `${BASE_URL}/verify?url=${encodeURIComponent(urlToSign)}&signature=${signature}`,
153
+ {
154
+ headers: {
155
+ 'x-api-key': TEST_ACCOUNTS.valid.apiKeys.valid,
156
+ },
157
+ },
158
+ )
159
+
160
+ expect(verifyResponse.ok).toBe(true)
161
+ const { valid } = (await verifyResponse.json()) as VerifyResponse
162
+ expect(valid).toBe(true)
163
+ })
164
+
165
+ it('should reject invalid signatures', async () => {
166
+ const urlToSign = addAccountIdToSignedUrl(TEST_URL)
167
+ const verifyResponse = await fetch(
168
+ `${BASE_URL}/verify?url=${encodeURIComponent(urlToSign)}&signature=deadbeef`,
169
+ {
170
+ headers: {
171
+ 'x-api-key': TEST_ACCOUNTS.valid.apiKeys.valid,
172
+ },
173
+ },
174
+ )
175
+
176
+ expect(verifyResponse.ok).toBe(true)
177
+ const { valid } = (await verifyResponse.json()) as VerifyResponse
178
+ expect(valid).toBe(false)
179
+ })
180
+
181
+ it('should handle CORS preflight requests', async () => {
182
+ const urlToSign = addAccountIdToSignedUrl(TEST_URL)
183
+ const response = await fetch(`${BASE_URL}/sign?url=${encodeURIComponent(urlToSign)}`, {
184
+ method: 'OPTIONS',
185
+ headers: {
186
+ Origin: TEST_ACCOUNTS.valid.clientIds.valid.origin,
187
+ 'Access-Control-Request-Method': 'GET',
188
+ 'Access-Control-Request-Headers': 'x-client-id, x-api-key',
189
+ },
190
+ })
191
+
192
+ expect(response.ok).toBe(true)
193
+ expect(response.headers.get('Access-Control-Allow-Headers')?.toLowerCase()).toContain('x-client-id')
194
+ expect(response.headers.get('Access-Control-Allow-Headers')?.toLowerCase()).toContain('x-api-key')
195
+ })
196
+ })