@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/index.ts ADDED
@@ -0,0 +1,1673 @@
1
+ // Remove Node.js crypto import and use Web Crypto API
2
+ // Web Crypto API is available globally in Cloudflare Workers
3
+
4
+ // Import Cloudflare-specific modules
5
+ import { DurableObject } from "cloudflare:workers";
6
+
7
+ // Add Cloudflare Workers types
8
+ /// <reference types="@cloudflare/workers-types" />
9
+
10
+ // Add TypeScript interface for DurableObjectId
11
+ interface DurableObjectId {
12
+ toString(): string;
13
+ equals(other: DurableObjectId): boolean;
14
+ }
15
+
16
+ // Add TypeScript interface to define the shape of our Durable Object stub
17
+ interface DurableObjectStub {
18
+ fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
19
+ }
20
+
21
+ // Add TypeScript interface to define the shape of our RateLimiter stub
22
+ interface RateLimiterStub extends DurableObjectStub {
23
+ checkRateLimit(
24
+ requestsPerSecond: number
25
+ ): Promise<{ allowed: boolean; retryAfter?: number }>;
26
+ checkDailyRateLimit(
27
+ dailyMaxRequests: number
28
+ ): Promise<{
29
+ allowed: boolean;
30
+ retryAfter?: number;
31
+ currentCount?: number;
32
+ dailyLimit?: number;
33
+ }>;
34
+ }
35
+
36
+ // Interface for environment bindings
37
+ interface Env {
38
+ URL_SIGNING_SECRET: string;
39
+ ACCOUNTS: KVNamespace; // Single KV store for all account data
40
+ API_RATE_LIMITER: {
41
+ idFromName(name: string): DurableObjectId;
42
+ get(id: DurableObjectId): RateLimiterStub;
43
+ };
44
+ // Resolve endpoint (ADR-0073 §10): catalog read + compositor base.
45
+ MEILISEARCH_HOST?: string;
46
+ MEILISEARCH_API_KEY?: string;
47
+ MEILISEARCH_INDEX?: string;
48
+ MOCKUP_BASE_URL?: string; // e.g. https://cdn.snowcone.app
49
+ // Account-config fallback source (ADR-0073 §1): when an account is not in
50
+ // ACCOUNTS KV, the signer fetches it from the backend's /kv-cache/api-key.
51
+ KV_CACHE_BASE_URL?: string; // backend base URL; defaults to http://localhost:4000 for local dev
52
+ KV_CACHE_SERVICE_TOKEN?: string; // Bearer service token — SECRET (wrangler secret put / process-compose --var). No source default.
53
+ }
54
+
55
+ // Type definitions for account data - updated format
56
+ interface AccountData {
57
+ accountId: string;
58
+ organizationId?: string;
59
+ mockupPrices?: { cached: number; uncached: number };
60
+ apiKeys: ApiKeyData[];
61
+ public: PublicData;
62
+ // ADR-0076 security-ladder additions (backend-synced into the ACCOUNTS KV).
63
+ // All optional — absence means "rung not enabled" (open by default).
64
+ /** L2: asset-source allowlist (hostname globs). Unset/empty = any asset. */
65
+ assetAllowlist?: string[];
66
+ /** L3: per-shop HMAC secret the resolver verifies the developer's `&s` against. */
67
+ l3Secret?: string;
68
+ /** L3: when true, the resolver REQUIRES a valid `&s` (signed URLs mandatory). */
69
+ requireSig?: boolean;
70
+ /** Explicit kill switch — a revoked key 403s regardless of any other config. */
71
+ revoked?: boolean;
72
+ }
73
+
74
+ interface ApiKeyData {
75
+ hash: string;
76
+ prefix: string;
77
+ rateLimit?: number;
78
+ scopes?: string[];
79
+ }
80
+
81
+ interface PublicData {
82
+ // NOTE: the page-origin / domain allowlist (formerly `allowedOrigins`) was
83
+ // removed — browser privacy controls strip/spoof Origin & Referer, so it could
84
+ // never be reliably enforced. Anti-theft now lives in the asset-source
85
+ // allowlist (L2, `assetAllowlist`) and signed URLs (L3). See ADR-0075/0076.
86
+ rateLimit?: number;
87
+ }
88
+
89
+ // Rate Limiter Durable Object - implements RPC pattern
90
+ export class RateLimiter extends DurableObject {
91
+ private nextAllowedTime: number = 0; // Initialize to 0, so first request sets it relative to Date.now()
92
+ static milliseconds_for_grace_period = 10000; // Allow user to spend up to 10 seconds of their limit upfront
93
+
94
+ // Daily limit state
95
+ private dailyRequestCount: number;
96
+ private currentDayMarker: string; // YYYY-MM-DD in UTC
97
+
98
+ private initialized: boolean = false;
99
+ private initializePromise: Promise<void> | null = null;
100
+
101
+ constructor(private state: DurableObjectState, env: Env) {
102
+ // Changed ctx to state and typed it
103
+ super(state, env);
104
+ // Initialize with default values, will be overwritten by storage if available
105
+ this.dailyRequestCount = 0;
106
+ this.currentDayMarker = "";
107
+ // Initialization logic will be called by methods needing this state.
108
+ }
109
+
110
+ private async ensureInitialized(): Promise<void> {
111
+ if (!this.initialized) {
112
+ if (!this.initializePromise) {
113
+ this.initializePromise = this._initialize();
114
+ }
115
+ await this.initializePromise;
116
+ }
117
+ }
118
+
119
+ private async _initialize(): Promise<void> {
120
+ try {
121
+ const stored = await this.state.storage.get([
122
+ "dailyRequestCount",
123
+ "currentDayMarker",
124
+ ]);
125
+ if (stored.has("dailyRequestCount")) {
126
+ this.dailyRequestCount = stored.get("dailyRequestCount") as number;
127
+ }
128
+ if (stored.has("currentDayMarker")) {
129
+ this.currentDayMarker = stored.get("currentDayMarker") as string;
130
+ }
131
+ console.log(
132
+ `RateLimiter DO (${this.state.id.toString()}): Initialized daily state. Count: ${
133
+ this.dailyRequestCount
134
+ }, Day: ${this.currentDayMarker}`
135
+ );
136
+ } catch (error) {
137
+ console.error(
138
+ `RateLimiter DO (${this.state.id.toString()}): Error during _initialize: ${error}`
139
+ );
140
+ // Keep default values if storage fails
141
+ } finally {
142
+ this.initialized = true;
143
+ this.initializePromise = null;
144
+ }
145
+ }
146
+
147
+ // Helper to calculate wait time without side effects
148
+ private _calculateCurrentWaitTime(requestsPerSecond: number): number {
149
+ const now = Date.now();
150
+ // Determine the baseline for nextAllowedTime:
151
+ // If nextAllowedTime is in the past, the effective nextAllowedTime for *this* check is 'now'.
152
+ // Otherwise, it's the future time already set.
153
+ const effectiveNextAllowedTime = Math.max(now, this.nextAllowedTime);
154
+
155
+ const timeUntilEffectiveNextAllowed = effectiveNextAllowedTime - now;
156
+
157
+ const millisToWait = Math.max(
158
+ 0,
159
+ timeUntilEffectiveNextAllowed - RateLimiter.milliseconds_for_grace_period
160
+ );
161
+ return millisToWait;
162
+ }
163
+
164
+ // Helper to consume a slot and advance nextAllowedTime
165
+ private _consumeSlot(requestsPerSecond: number): void {
166
+ const now = Date.now();
167
+ const millisecondsPerRequest = 1000 / requestsPerSecond; // Changed from 60000 / requestsPerMinute
168
+
169
+ // Advance nextAllowedTime from its current value (or 'now' if it's in the past),
170
+ // and add the duration of one request.
171
+ this.nextAllowedTime =
172
+ Math.max(now, this.nextAllowedTime) + millisecondsPerRequest;
173
+ }
174
+
175
+ // Method name and signature now match the example but keeps our dynamic rate limit.
176
+ // This method is assumed to consume a slot, matching its original behavior when called directly (e.g., via RPC).
177
+ async getMillisecondsToNextRequest(
178
+ requestsPerSecond: number = 1 // Changed from requestsPerMinute: number = 60
179
+ ): Promise<number> {
180
+ // First, calculate what the wait time *would* be based on the current state.
181
+ const millisToWait = this._calculateCurrentWaitTime(requestsPerSecond);
182
+ // Then, consume the slot, advancing nextAllowedTime for the next potential request.
183
+ this._consumeSlot(requestsPerSecond);
184
+ // Return the wait time that was calculated *before* this call consumed the slot.
185
+ return millisToWait;
186
+ }
187
+
188
+ // Keep our original method for backward compatibility (now correctly implemented)
189
+ // This method checks the rate limit and only consumes a slot if the request is allowed.
190
+ async checkRateLimit(
191
+ requestsPerSecond: number // Changed from requestsPerMinute
192
+ ): Promise<{ allowed: boolean; retryAfter?: number }> {
193
+ const millisToWait = this._calculateCurrentWaitTime(requestsPerSecond);
194
+
195
+ if (millisToWait > 0) {
196
+ // If waiting is required, the request is not allowed, and no slot is consumed.
197
+ return { allowed: false, retryAfter: millisToWait };
198
+ } else {
199
+ // If no waiting is required, the request is allowed. Consume a slot for this request.
200
+ this._consumeSlot(requestsPerSecond);
201
+ return { allowed: true };
202
+ }
203
+ }
204
+
205
+ // New methods for daily rate limiting
206
+ private getCurrentDayMarker(): string {
207
+ const now = new Date();
208
+ // Use UTC to avoid timezone issues with "day" rollovers
209
+ return `${now.getUTCFullYear()}-${(now.getUTCMonth() + 1)
210
+ .toString()
211
+ .padStart(2, "0")}-${now.getUTCDate().toString().padStart(2, "0")}`;
212
+ }
213
+
214
+ async checkDailyRateLimit(dailyMaxRequests: number): Promise<{
215
+ allowed: boolean;
216
+ retryAfter?: number;
217
+ currentCount?: number;
218
+ dailyLimit?: number;
219
+ }> {
220
+ await this.ensureInitialized(); // Ensure state is loaded
221
+
222
+ const todayMarker = this.getCurrentDayMarker();
223
+
224
+ if (this.currentDayMarker !== todayMarker) {
225
+ console.log(
226
+ `RateLimiter DO (${this.state.id.toString()}): New day detected. Old: ${
227
+ this.currentDayMarker
228
+ }, New: ${todayMarker}. Resetting daily count.`
229
+ );
230
+ this.currentDayMarker = todayMarker;
231
+ this.dailyRequestCount = 0; // Reset count first
232
+ try {
233
+ await this.state.storage.put({
234
+ currentDayMarker: this.currentDayMarker,
235
+ dailyRequestCount: this.dailyRequestCount,
236
+ });
237
+ } catch (error) {
238
+ console.error(
239
+ `RateLimiter DO (${this.state.id.toString()}): Error persisting daily state reset: ${error}`
240
+ );
241
+ // If storage fails, proceed with in-memory state for resilience
242
+ }
243
+ }
244
+
245
+ if (this.dailyRequestCount >= dailyMaxRequests) {
246
+ const now = new Date();
247
+ const tomorrow = new Date(now);
248
+ tomorrow.setUTCDate(now.getUTCDate() + 1);
249
+ tomorrow.setUTCHours(0, 0, 0, 0);
250
+ const retryAfter = tomorrow.getTime() - now.getTime();
251
+ console.log(
252
+ `RateLimiter DO (${this.state.id.toString()}): Daily limit EXCEEDED. Count: ${
253
+ this.dailyRequestCount
254
+ }/${dailyMaxRequests}.`
255
+ );
256
+ return {
257
+ allowed: false,
258
+ retryAfter,
259
+ currentCount: this.dailyRequestCount,
260
+ dailyLimit: dailyMaxRequests,
261
+ };
262
+ }
263
+
264
+ this.dailyRequestCount++;
265
+ try {
266
+ await this.state.storage.put("dailyRequestCount", this.dailyRequestCount);
267
+ // currentDayMarker is already up-to-date in memory and persisted if it was a new day.
268
+ } catch (error) {
269
+ console.error(
270
+ `RateLimiter DO (${this.state.id.toString()}): Error persisting daily count increment: ${error}`
271
+ );
272
+ // If storage fails, proceed with in-memory state for resilience
273
+ }
274
+ console.log(
275
+ `RateLimiter DO (${this.state.id.toString()}): Daily count updated. Count: ${
276
+ this.dailyRequestCount
277
+ }/${dailyMaxRequests}.`
278
+ );
279
+ return {
280
+ allowed: true,
281
+ currentCount: this.dailyRequestCount,
282
+ dailyLimit: dailyMaxRequests,
283
+ };
284
+ }
285
+ }
286
+
287
+ // Helper function to add CORS headers to a response
288
+ function addCorsHeaders(response: Response, request: Request): Response {
289
+ // Get the origin from the request
290
+ const origin = request.headers.get("Origin") || "*";
291
+
292
+ // Clone the response and add CORS headers
293
+ const corsResponse = new Response(response.body, response);
294
+ corsResponse.headers.set("Access-Control-Allow-Origin", origin);
295
+ corsResponse.headers.set(
296
+ "Access-Control-Allow-Methods",
297
+ "GET, POST, OPTIONS"
298
+ );
299
+ corsResponse.headers.set(
300
+ "Access-Control-Allow-Headers",
301
+ "Content-Type, X-API-Key, X-Client-ID"
302
+ );
303
+
304
+ return corsResponse;
305
+ }
306
+
307
+ // Helper function to hash an API key using SHA-256
308
+ async function hashApiKey(apiKey: string): Promise<string> {
309
+ // Convert string to bytes
310
+ const encoder = new TextEncoder();
311
+ const data = encoder.encode(apiKey);
312
+
313
+ // Calculate SHA-256 hash
314
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
315
+
316
+ // Convert to hex string
317
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
318
+ const hashHex = hashArray
319
+ .map((b) => b.toString(16).padStart(2, "0"))
320
+ .join("");
321
+
322
+ return hashHex;
323
+ }
324
+
325
+ // Authentication middleware
326
+ async function authenticate(
327
+ request: Request,
328
+ env: Env
329
+ ): Promise<{ authenticated: boolean; error?: string; accountId?: string }> {
330
+ console.log("\n🔐 Authentication attempt");
331
+
332
+ // Get the URL from the request query parameters
333
+ const requestUrl = new URL(request.url);
334
+ const urlParam = requestUrl.searchParams.get("url");
335
+
336
+ // If there's no URL parameter, we can't proceed
337
+ if (!urlParam) {
338
+ console.log("❌ Missing required url parameter");
339
+ return {
340
+ authenticated: false,
341
+ error: "Missing required url parameter",
342
+ };
343
+ }
344
+
345
+ // Parse the URL to sign/verify to extract accountId from it
346
+ let urlToProcess: URL;
347
+ try {
348
+ // If it's a relative URL, add a base for parsing
349
+ if (urlParam.startsWith("/")) {
350
+ urlToProcess = new URL(urlParam, "https://example.com");
351
+ } else {
352
+ urlToProcess = new URL(urlParam);
353
+ }
354
+ } catch (error) {
355
+ console.log(`❌ Invalid URL format: ${urlParam}`);
356
+ return {
357
+ authenticated: false,
358
+ error: "Invalid URL format in url parameter",
359
+ };
360
+ }
361
+
362
+ // Extract the shop id from the URL to sign/verify. Canonical param is `shop`
363
+ // (what the mockup-url builder + delivery emit); accept legacy `accountId`
364
+ // too. Local var name kept as `accountId` to limit blast radius downstream.
365
+ const accountId =
366
+ urlToProcess.searchParams.get("shop") ??
367
+ urlToProcess.searchParams.get("accountId");
368
+
369
+ // Validate accountId requirement
370
+ if (!accountId) {
371
+ console.log("❌ Missing required accountId in the URL to sign/verify");
372
+ return {
373
+ authenticated: false,
374
+ error: "Missing required accountId in the URL to sign/verify",
375
+ };
376
+ }
377
+
378
+ // Validate accountId length
379
+ if (accountId.length < 6) {
380
+ console.log(
381
+ `❌ Invalid accountId: ${accountId} (must be at least 6 characters)`
382
+ );
383
+ return {
384
+ authenticated: false,
385
+ error: "Invalid accountId: must be at least 6 characters",
386
+ };
387
+ }
388
+
389
+ console.log(`✅ Valid accountId format: ${accountId}`);
390
+
391
+ // Get account data from KV store
392
+ console.log(
393
+ `🔍 Looking up account data in KV store for accountId: ${accountId}`
394
+ );
395
+ let accountData: AccountData;
396
+ try {
397
+ // Directly get the specific account data by ID
398
+ const accountDataStr = await env.ACCOUNTS.get(accountId);
399
+ console.log(
400
+ `📦 KV store response for ${accountId}:`,
401
+ accountDataStr ? "Data found" : "No data found"
402
+ );
403
+
404
+ if (!accountDataStr) {
405
+ console.log(
406
+ `🤷 Account data not found in KV for ${accountId}. Fetching from source API...`
407
+ );
408
+ try {
409
+ // Account-config fallback source (ADR-0073 §1): both the backend URL
410
+ // and the service token are env-configured. The base URL defaults to
411
+ // localhost:4000 for local dev; the token is a SECRET with no source
412
+ // default (set via `wrangler secret put KV_CACHE_SERVICE_TOKEN` in prod,
413
+ // or process-compose `--var` locally — same as URL_SIGNING_SECRET).
414
+ const kvCacheBaseUrl = env.KV_CACHE_BASE_URL || "http://localhost:4000";
415
+ const kvCacheServiceToken = env.KV_CACHE_SERVICE_TOKEN;
416
+ if (!kvCacheServiceToken) {
417
+ console.log(
418
+ `❌ KV_CACHE_SERVICE_TOKEN not configured; cannot fetch account ${accountId} from the backend config source.`
419
+ );
420
+ return {
421
+ authenticated: false,
422
+ error:
423
+ "Account configuration source unavailable (signer not configured)",
424
+ };
425
+ }
426
+
427
+ const externalApiUrl = new URL(
428
+ `${kvCacheBaseUrl.replace(/\/+$/, "")}/kv-cache/api-key`
429
+ );
430
+ // Backend /kv-cache/api-key reads `shop` (was binding `shopId`; sending
431
+ // `accountId` was silently ignored, so cache-miss lookups failed).
432
+ externalApiUrl.searchParams.append("shop", accountId);
433
+
434
+ const response = await fetch(externalApiUrl.toString(), {
435
+ method: "GET",
436
+ headers: {
437
+ Authorization: `Bearer ${kvCacheServiceToken}`,
438
+ },
439
+ });
440
+
441
+ if (!response.ok) {
442
+ const errorText = await response.text();
443
+ console.log(
444
+ `❌ Failed to fetch account data from source API for ${accountId}. Status: ${response.status}, Body: ${errorText}`
445
+ );
446
+ return {
447
+ authenticated: false,
448
+ error: `Failed to retrieve account information for ${accountId}. API status: ${response.status}`,
449
+ };
450
+ }
451
+
452
+ // Fetch data as 'any' for more flexible initial parsing
453
+ const rawFetchedData = (await response.json()) as any;
454
+ console.log(
455
+ `✅ Successfully fetched account data from source API for ${accountId}`
456
+ );
457
+
458
+ // Validate core data structure
459
+ if (
460
+ !rawFetchedData ||
461
+ typeof rawFetchedData.accountId !== "string" ||
462
+ !Array.isArray(rawFetchedData.apiKeys) ||
463
+ typeof rawFetchedData.public !== "object" || // Ensure public is an object
464
+ rawFetchedData.public === null // And not null
465
+ ) {
466
+ console.log(
467
+ `❌ Invalid core data structure received from source API for ${accountId}. Data: ${JSON.stringify(
468
+ rawFetchedData
469
+ )}`
470
+ );
471
+ return {
472
+ authenticated: false,
473
+ error: "Invalid data structure from account information source.",
474
+ };
475
+ }
476
+
477
+ // Process apiKeys to ensure structure and 'scopes' field
478
+ const processedApiKeys: ApiKeyData[] = rawFetchedData.apiKeys
479
+ .map((key: any) => {
480
+ if (
481
+ typeof key.hash !== "string" ||
482
+ typeof key.prefix !== "string"
483
+ ) {
484
+ console.log(
485
+ `⚠️ Malformed API key object in fetched data for account ${accountId}, skipping. Key: ${JSON.stringify(
486
+ key
487
+ )}`
488
+ );
489
+ return null; // Mark for filtering
490
+ }
491
+ return {
492
+ hash: key.hash,
493
+ prefix: key.prefix,
494
+ rateLimit:
495
+ typeof key.rateLimit === "number" ? key.rateLimit : undefined,
496
+ scopes: Array.isArray(key.scopes) ? key.scopes : [], // Default to empty array if scopes is missing/invalid
497
+ };
498
+ })
499
+ .filter((key: ApiKeyData | null): key is ApiKeyData => key !== null);
500
+
501
+ const accountDataToStore: AccountData = {
502
+ accountId: rawFetchedData.accountId,
503
+ apiKeys: processedApiKeys,
504
+ public: rawFetchedData.public, // Assume PublicData structure is as expected or needs separate validation if complex
505
+ // ADR-0076 ladder fields — pass through when the backend supplies them.
506
+ assetAllowlist: Array.isArray(rawFetchedData.assetAllowlist)
507
+ ? rawFetchedData.assetAllowlist
508
+ : undefined,
509
+ l3Secret:
510
+ typeof rawFetchedData.l3Secret === "string"
511
+ ? rawFetchedData.l3Secret
512
+ : undefined,
513
+ requireSig: rawFetchedData.requireSig === true ? true : undefined,
514
+ revoked: rawFetchedData.revoked === true ? true : undefined,
515
+ };
516
+
517
+ // Store in KV for next time
518
+ await env.ACCOUNTS.put(accountId, JSON.stringify(accountDataToStore));
519
+ console.log(`💾 Stored processed account data in KV for ${accountId}`);
520
+ accountData = accountDataToStore; // Use the processed and validated data
521
+ } catch (apiError: any) {
522
+ console.error(
523
+ `💥 Error fetching account data from source API for ${accountId}:`,
524
+ apiError
525
+ );
526
+ return {
527
+ authenticated: false,
528
+ error: `Error fetching account information: ${
529
+ apiError.message || String(apiError)
530
+ }`,
531
+ };
532
+ }
533
+ } else {
534
+ // Parse account data from KV
535
+ accountData = JSON.parse(accountDataStr) as AccountData;
536
+ }
537
+
538
+ console.log(`📋 Account data ready for: ${accountId}`);
539
+
540
+ // Verify the accountId in the data matches the requested accountId
541
+ if (accountData.accountId !== accountId) {
542
+ console.log(
543
+ `❌ Account ID mismatch: requested ${accountId}, found ${accountData.accountId}`
544
+ );
545
+ return {
546
+ authenticated: false,
547
+ error: `Account ID mismatch`,
548
+ };
549
+ }
550
+ } catch (error: any) {
551
+ console.error("Error accessing KV store:", error);
552
+ return {
553
+ authenticated: false,
554
+ error: `Error accessing KV store: ${error.message || String(error)}`,
555
+ };
556
+ }
557
+
558
+ // Method 1: API Key Authentication (server-side)
559
+ const apiKey = request.headers.get("x-api-key");
560
+ if (apiKey) {
561
+ console.log("📝 Using API Key authentication (server-side)");
562
+
563
+ // Extract the prefix (first 8 characters)
564
+ const apiKeyPrefix = apiKey.substring(0, 8);
565
+ console.log(`🔑 API Key prefix: ${apiKeyPrefix}`);
566
+
567
+ // Find API key with matching prefix
568
+ const matchingApiKey = accountData.apiKeys.find(
569
+ (key) => key.prefix === apiKeyPrefix
570
+ );
571
+
572
+ if (!matchingApiKey) {
573
+ console.log(`❌ No API key found with prefix: ${apiKeyPrefix}`);
574
+ return {
575
+ authenticated: false,
576
+ error: "Invalid API key for this account",
577
+ };
578
+ }
579
+
580
+ // Calculate the hash of the provided API key
581
+ const calculatedHash = await hashApiKey(apiKey);
582
+
583
+ // Verify the hash matches the stored hash
584
+ if (calculatedHash !== matchingApiKey.hash) {
585
+ console.log(`❌ API key hash verification failed`);
586
+ return {
587
+ authenticated: false,
588
+ error: "Invalid API key for this account",
589
+ };
590
+ }
591
+
592
+ // Check for required scope
593
+ if (!matchingApiKey.scopes || !matchingApiKey.scopes.includes("mockups")) {
594
+ console.log(
595
+ `❌ API key for account ${accountId} does not have required 'mockups' scope. Found scopes: ${matchingApiKey.scopes}`
596
+ );
597
+ return {
598
+ authenticated: false,
599
+ error: "API key missing required scope: mockups",
600
+ };
601
+ }
602
+ console.log(`✅ API key has required 'mockups' scope.`);
603
+
604
+ console.log(`✅ API key verified for account: ${accountId}`);
605
+
606
+ // Check rate limit if defined for this API key
607
+ if (matchingApiKey.rateLimit) {
608
+ try {
609
+ // Create a unique ID for this API key's rate limiter
610
+ const rateLimiterId = env.API_RATE_LIMITER.idFromName(
611
+ `${accountId}:${apiKeyPrefix}`
612
+ );
613
+ const rateLimiter = env.API_RATE_LIMITER.get(rateLimiterId);
614
+
615
+ // Call the method directly on the Durable Object via RPC
616
+ const result = await rateLimiter.checkRateLimit(
617
+ matchingApiKey.rateLimit
618
+ );
619
+
620
+ if (!result.allowed) {
621
+ console.log(`❌ Rate limit exceeded for API key: ${apiKeyPrefix}`);
622
+ return {
623
+ authenticated: false,
624
+ error: `Rate limit exceeded. Try again in ${Math.ceil(
625
+ result.retryAfter! / 1000
626
+ )} seconds`,
627
+ };
628
+ }
629
+
630
+ console.log(`✅ Rate limit check passed for API key: ${apiKeyPrefix}`);
631
+ } catch (error) {
632
+ // If there's an error checking the rate limit, log it but continue (fail open)
633
+ console.error(`Error checking rate limit: ${error}`);
634
+ }
635
+ }
636
+
637
+ return { authenticated: true, accountId };
638
+ }
639
+
640
+ // Method 2: Public (client-side/web) access.
641
+ // The page-origin / domain allowlist that used to gate this path was removed —
642
+ // browsers strip/spoof Origin & Referer, so it was unenforceable. Public access
643
+ // is now governed by rate limits (below) plus the asset allowlist (L2) and
644
+ // signed URLs (L3) enforced at the resolver. See ADR-0075/0076.
645
+ console.log(`\n🔑 Using Public access (client-side/web), rate-limited by IP`);
646
+
647
+ // Get the client IP address (moved here to be available for both global and account-specific public rate limits)
648
+ const clientIp =
649
+ request.headers.get("CF-Connecting-IP") ||
650
+ request.headers.get("X-Forwarded-For") ||
651
+ "unknown-ip";
652
+
653
+ // Global IP Rate Limiter (handles both per-second and per-day)
654
+ const GLOBAL_IP_RATE_LIMIT_RPS = 20;
655
+ const GLOBAL_DAILY_IP_RATE_LIMIT = 50000; // New daily limit
656
+
657
+ try {
658
+ const globalRateLimiterId = env.API_RATE_LIMITER.idFromName(
659
+ `global:public:${clientIp}`
660
+ );
661
+ const globalRateLimiter = env.API_RATE_LIMITER.get(globalRateLimiterId);
662
+
663
+ // Check global per-second IP rate limit
664
+ const globalPerSecondRateLimitResult =
665
+ await globalRateLimiter.checkRateLimit(GLOBAL_IP_RATE_LIMIT_RPS);
666
+
667
+ if (!globalPerSecondRateLimitResult.allowed) {
668
+ console.log(
669
+ `❌ Global IP per-second rate limit exceeded for IP: ${clientIp}`
670
+ );
671
+ return {
672
+ authenticated: false,
673
+ error: `Global per-second rate limit exceeded. Try again in ${Math.ceil(
674
+ globalPerSecondRateLimitResult.retryAfter! / 1000
675
+ )} seconds`,
676
+ };
677
+ }
678
+ console.log(
679
+ `✅ Global IP per-second rate limit check passed for IP: ${clientIp}`
680
+ );
681
+
682
+ // Check global daily IP rate limit
683
+ const dailyRateLimitResult = await globalRateLimiter.checkDailyRateLimit(
684
+ GLOBAL_DAILY_IP_RATE_LIMIT
685
+ );
686
+
687
+ if (!dailyRateLimitResult.allowed) {
688
+ console.log(
689
+ `❌ Global daily IP rate limit exceeded for IP: ${clientIp}. Count: ${dailyRateLimitResult.currentCount}/${dailyRateLimitResult.dailyLimit}`
690
+ );
691
+ let retryMessage = "Global daily rate limit exceeded.";
692
+ if (dailyRateLimitResult.retryAfter) {
693
+ const totalSeconds = Math.floor(dailyRateLimitResult.retryAfter / 1000);
694
+ const hours = Math.floor(totalSeconds / 3600);
695
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
696
+ retryMessage += ` Try again in approximately ${hours}h ${minutes}m.`;
697
+ }
698
+ return {
699
+ authenticated: false,
700
+ error: retryMessage,
701
+ };
702
+ }
703
+ console.log(
704
+ `✅ Global daily IP rate limit check passed for IP: ${clientIp}. Count: ${dailyRateLimitResult.currentCount}/${dailyRateLimitResult.dailyLimit}`
705
+ );
706
+ } catch (error) {
707
+ console.error(
708
+ `Error checking global IP rate limits (per-second or daily): ${error}`
709
+ );
710
+ // Fail open for global rate limit errors to prevent service disruption if DO fails,
711
+ // but log the error. Account-specific limits will still apply.
712
+ }
713
+
714
+ // Check account-specific rate limit for public requests if defined
715
+ if (accountData.public.rateLimit) {
716
+ try {
717
+ // Client IP already determined above
718
+ // Create a unique ID for this IP's rate limiter under this account
719
+ const rateLimiterId = env.API_RATE_LIMITER.idFromName(
720
+ `${accountId}:public:${clientIp}`
721
+ );
722
+ const rateLimiter = env.API_RATE_LIMITER.get(rateLimiterId);
723
+
724
+ // Call the method directly on the Durable Object via RPC
725
+ const result = await rateLimiter.checkRateLimit(
726
+ accountData.public.rateLimit
727
+ );
728
+
729
+ if (!result.allowed) {
730
+ console.log(`❌ Rate limit exceeded for IP: ${clientIp}`);
731
+ return {
732
+ authenticated: false,
733
+ error: `Rate limit exceeded. Try again in ${Math.ceil(
734
+ result.retryAfter! / 1000
735
+ )} seconds`,
736
+ };
737
+ }
738
+
739
+ console.log(`✅ Rate limit check passed for IP: ${clientIp}`);
740
+ } catch (error) {
741
+ // If there's an error checking the rate limit, log it but continue (fail open)
742
+ console.error(`Error checking rate limit: ${error}`);
743
+ }
744
+ }
745
+
746
+ console.log("✅ Authentication successful");
747
+ return { authenticated: true, accountId };
748
+ }
749
+
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
+ // NOTE: `isOriginAllowed` (the page-origin / domain allowlist matcher) was
769
+ // 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.
772
+
773
+ export { signUrl, verifyUrl } from "./signing";
774
+ import { signUrl, verifyUrl } from "./signing";
775
+ import {
776
+ buildMockupUrl,
777
+ canonicalForSig,
778
+ signDevSig,
779
+ parsePublicUrl,
780
+ PARAMS,
781
+ type DesignElement,
782
+ type ImageAlignment,
783
+ } from "@snowcone-app/mockup-url";
784
+ import {
785
+ fetchProduct,
786
+ resolveDefaults,
787
+ resolveVariant,
788
+ } from "./resolve";
789
+
790
+ // ADR-0073 §10 — resolve + build + sign for `getMockupUrl(assetUrl, productCode)`.
791
+ // The BFF POSTs { accountId, productCode, assetUrl, variant?, mockupId?, placement?, width? }
792
+ // with x-api-key (or a browser with an allowed Origin). We auth (reusing the
793
+ // existing rate-limited authenticate()), resolve catalog defaults from
794
+ // Meilisearch (KV-cached), build the canonical URL, and sign it the SAME way
795
+ // /sign does (so it validates at rendercenter identically).
796
+ async function handleMockupUrl(request: Request, env: Env): Promise<Response> {
797
+ const json = (body: unknown, status = 200): Response =>
798
+ new Response(JSON.stringify(body), {
799
+ status,
800
+ headers: { "Content-Type": "application/json" },
801
+ });
802
+ // Structured error envelope (Stripe-style): `{ error: { code, message } }`.
803
+ // `code` is a stable machine string integrators branch on; `message` is
804
+ // human-facing and may change. Keep codes in sync with the SDK's typed error.
805
+ const err = (status: number, code: string, message: string): Response =>
806
+ json({ error: { code, message } }, status);
807
+
808
+ let body: {
809
+ accountId?: string;
810
+ productCode?: string;
811
+ assetUrl?: string;
812
+ variant?: string;
813
+ mockupId?: string;
814
+ placement?: string;
815
+ width?: number;
816
+ };
817
+ try {
818
+ body = (await request.json()) as typeof body;
819
+ } catch {
820
+ return err(400, "invalid_json", "Request body is not valid JSON");
821
+ }
822
+
823
+ const { accountId, productCode, assetUrl } = body;
824
+ if (!accountId || !productCode || !assetUrl) {
825
+ return err(
826
+ 400,
827
+ "missing_fields",
828
+ "Missing required fields: accountId, productCode, assetUrl"
829
+ );
830
+ }
831
+ // Default to 'dev-unsigned' to match the rendercenter verifier's default
832
+ // (services/rendercenter/api/src/config.ts) — so local dev works with no
833
+ // secret config and sigs validate. Production sets a real wrangler secret.
834
+ const signingSecret = env.URL_SIGNING_SECRET || "dev-unsigned";
835
+ const meiliHost = env.MEILISEARCH_HOST;
836
+ const meiliKey = env.MEILISEARCH_API_KEY;
837
+ const meiliIndex = env.MEILISEARCH_INDEX;
838
+ const mockupBaseUrl = env.MOCKUP_BASE_URL;
839
+ if (!meiliHost || !meiliKey || !meiliIndex || !mockupBaseUrl) {
840
+ return err(
841
+ 500,
842
+ "not_configured",
843
+ "Resolve endpoint not configured (Meilisearch / MOCKUP_BASE_URL)"
844
+ );
845
+ }
846
+
847
+ // Authenticate + rate-limit at mint time, reusing the existing path. We hand
848
+ // authenticate() a minimal accountId-bearing url so its account lookup +
849
+ // key/origin checks + rate limit all run before we touch the catalog.
850
+ //
851
+ // LOCAL DEV ONLY: when the signing secret is the dev default ('dev-unsigned'),
852
+ // skip the account lookup — there's no provisioned account/KV in a workspace,
853
+ // and the local BFF is trusted. This bypass is IMPOSSIBLE in production:
854
+ // production sets a real URL_SIGNING_SECRET (wrangler secret), so the branch
855
+ // below is never taken and full API-key + account auth always runs.
856
+ const isDevUnsigned = signingSecret === "dev-unsigned";
857
+ if (!isDevUnsigned) {
858
+ const authProbeUrl = `https://signer.internal/auth?url=${encodeURIComponent(
859
+ `https://i/mockup?shop=${encodeURIComponent(accountId)}`
860
+ )}`;
861
+ const authReq = new Request(authProbeUrl, { method: "GET", headers: request.headers });
862
+ const authResult = await authenticate(authReq, env);
863
+ if (!authResult.authenticated) {
864
+ const limited = authResult.error?.includes("Rate limit exceeded");
865
+ const missingScope = authResult.error?.includes("scope");
866
+ return err(
867
+ limited ? 429 : 401,
868
+ limited ? "rate_limited" : missingScope ? "missing_scope" : "unauthorized",
869
+ authResult.error ?? "Authentication failed"
870
+ );
871
+ }
872
+ }
873
+
874
+ // Resolve catalog defaults (Meilisearch, KV-cached).
875
+ const product = await fetchProduct(productCode, {
876
+ host: meiliHost,
877
+ apiKey: meiliKey,
878
+ index: meiliIndex,
879
+ }, env.ACCOUNTS);
880
+ if (!product) {
881
+ return err(404, "product_not_found", `Product not found: ${productCode}`);
882
+ }
883
+ const resolved = resolveDefaults(product, {
884
+ variant: body.variant,
885
+ mockupId: body.mockupId,
886
+ placement: body.placement,
887
+ });
888
+ if (!resolved) {
889
+ return err(
890
+ 422,
891
+ "unrenderable_product",
892
+ `Product ${productCode} has no renderable variant/mockup/placement`
893
+ );
894
+ }
895
+
896
+ // Build the canonical (unsigned) URL.
897
+ const unsigned = buildMockupUrl(
898
+ {
899
+ productId: product.id,
900
+ mockupId: resolved.mockupId,
901
+ variantId: resolved.variantId,
902
+ width: body.width ?? 1400,
903
+ design: [
904
+ {
905
+ type: "image",
906
+ imageUrl: assetUrl,
907
+ placement: resolved.placement.label,
908
+ width: resolved.placement.width,
909
+ height: resolved.placement.height,
910
+ alignment: "center",
911
+ },
912
+ ],
913
+ },
914
+ { mockupBaseUrl, shop: accountId }
915
+ );
916
+
917
+ // Sign the RELATIVE path+query, mirroring the rendercenter verifier
918
+ // (services/rendercenter/api/src/utils/url-verifier.ts `extractSignature`):
919
+ // it HMACs `path + "?" + URLSearchParams(query−seal).toString()` because Fastify
920
+ // sees only the relative request URL. Signing the absolute URL would not validate.
921
+ const urlObj = new URL(unsigned);
922
+ const sigParams = new URLSearchParams(urlObj.search);
923
+ sigParams.delete("seal");
924
+ const relative = `${urlObj.pathname}?${sigParams.toString()}`;
925
+ const sig = await signUrl(relative, signingSecret);
926
+ urlObj.searchParams.append("seal", sig);
927
+
928
+ return json({ url: urlObj.toString() });
929
+ }
930
+
931
+ // ───────────────────────────────────────────────────────────────────────────
932
+ // ADR-0076 — the public image-CDN resolver (img.snowcone.app).
933
+ //
934
+ // GET https://img.snowcone.app/{productCode}?asset=…&shop=…[&w&mockup&variant&placement&s]
935
+ // → 302 → cdn.snowcone.app/mockup?…&sig (relay-signed render URL)
936
+ //
937
+ // The developer's `shop` (Shop ID; legacy alias `key`) is a PUBLIC token
938
+ // (= shop.id by default). The resolver
939
+ // authorizes off that public token, runs the existing catalog resolve, builds
940
+ // the render URL FRESH (never forwarding the incoming query string), relay-signs
941
+ // it internally, and 302s. The developer never holds the relay secret. The only
942
+ // "secret" a developer ever uses is the optional per-shop L3 `&s`.
943
+ // ───────────────────────────────────────────────────────────────────────────
944
+
945
+ /**
946
+ * Load AccountData for a public `key` from the ACCOUNTS KV, with the same
947
+ * backend fallback the existing authenticate() uses. Returns null if the key is
948
+ * unknown or the backend can't supply it (treated as 404 upstream).
949
+ */
950
+ async function loadAccountByKey(
951
+ key: string,
952
+ env: Env
953
+ ): Promise<AccountData | null> {
954
+ let accountDataStr = await env.ACCOUNTS.get(key);
955
+ if (accountDataStr) {
956
+ try {
957
+ const parsed = JSON.parse(accountDataStr) as AccountData;
958
+ if (parsed.accountId === key) return parsed;
959
+ return parsed; // tolerate id/key shape; resolver only needs the config
960
+ } catch {
961
+ return null;
962
+ }
963
+ }
964
+
965
+ // LOCAL DEV: the worker runs with the 'dev-unsigned' signing secret and no
966
+ // KV_CACHE_SERVICE_TOKEN, so the backend lookup below would bail. Mirror the
967
+ // dev behavior of /mockups/url — grant a permissive, fully-open account so any
968
+ // key resolves locally (no assetAllowlist → L2 passes; no requireSig → L3 off).
969
+ // Gated strictly on the dev secret, so a real prod URL_SIGNING_SECRET always
970
+ // takes the authenticated path below.
971
+ if (!env.URL_SIGNING_SECRET || env.URL_SIGNING_SECRET === "dev-unsigned") {
972
+ return { accountId: key, apiKeys: [], public: {} };
973
+ }
974
+
975
+ // Fallback to the backend config source (mirrors authenticate()).
976
+ const kvCacheBaseUrl = env.KV_CACHE_BASE_URL || "http://localhost:4000";
977
+ const kvCacheServiceToken = env.KV_CACHE_SERVICE_TOKEN;
978
+ if (!kvCacheServiceToken) return null;
979
+ try {
980
+ const externalApiUrl = new URL(
981
+ `${kvCacheBaseUrl.replace(/\/+$/, "")}/kv-cache/api-key`
982
+ );
983
+ // Backend /kv-cache/api-key reads `shop` (legacy `accountId` was ignored).
984
+ externalApiUrl.searchParams.append("shop", key);
985
+ const response = await fetch(externalApiUrl.toString(), {
986
+ method: "GET",
987
+ headers: { Authorization: `Bearer ${kvCacheServiceToken}` },
988
+ });
989
+ if (!response.ok) return null;
990
+ const raw = (await response.json()) as any;
991
+ if (
992
+ !raw ||
993
+ typeof raw.accountId !== "string" ||
994
+ !Array.isArray(raw.apiKeys) ||
995
+ typeof raw.public !== "object" ||
996
+ raw.public === null
997
+ ) {
998
+ return null;
999
+ }
1000
+ const account: AccountData = {
1001
+ accountId: raw.accountId,
1002
+ apiKeys: Array.isArray(raw.apiKeys) ? raw.apiKeys : [],
1003
+ public: raw.public,
1004
+ assetAllowlist: Array.isArray(raw.assetAllowlist)
1005
+ ? raw.assetAllowlist
1006
+ : undefined,
1007
+ l3Secret: typeof raw.l3Secret === "string" ? raw.l3Secret : undefined,
1008
+ requireSig: raw.requireSig === true ? true : undefined,
1009
+ revoked: raw.revoked === true ? true : undefined,
1010
+ };
1011
+ // Cache for next time, keyed by the public token.
1012
+ await env.ACCOUNTS.put(key, JSON.stringify(account));
1013
+ return account;
1014
+ } catch {
1015
+ return null;
1016
+ }
1017
+ }
1018
+
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;
1031
+ }
1032
+
1033
+ async function handlePublicResolve(
1034
+ request: Request,
1035
+ env: Env,
1036
+ productCode: string
1037
+ ): Promise<Response> {
1038
+ // All resolver responses are uncacheable — the resolver must stay in the loop
1039
+ // for invalidation + per-request auth/rate (ADR-0076 §7). 4xx must never be
1040
+ // cached as the image.
1041
+ const NO_STORE = { "Cache-Control": "no-store" } as const;
1042
+ const errResp = (status: number, message: string): Response =>
1043
+ new Response(JSON.stringify({ error: message }), {
1044
+ status,
1045
+ headers: { "Content-Type": "application/json", ...NO_STORE },
1046
+ });
1047
+
1048
+ const reqUrl = new URL(request.url);
1049
+ const q = reqUrl.searchParams;
1050
+ // The full grammar: bare `asset=` (default placement) OR a multi-placement
1051
+ // design map (`asset.<key>`/`color.<key>`/`tile.<key>`/`align.<key>`) + variant
1052
+ // option picks (`opt.<attr>`).
1053
+ const parsed = parsePublicUrl(reqUrl);
1054
+ const asset = q.get(PARAMS.asset);
1055
+ const design = parsed.design ?? {};
1056
+ const optionPicks = parsed.options ?? {};
1057
+ const designKeys = Object.keys(design);
1058
+ const key = q.get(PARAMS.shop);
1059
+ const widthParam = q.get(PARAMS.width);
1060
+ const mockupOverride = q.get(PARAMS.mockup) ?? undefined;
1061
+ const variantOverride = q.get(PARAMS.variant) ?? undefined;
1062
+ const placementOverride = q.get(PARAMS.placement) ?? undefined;
1063
+ const aspectParam = q.get(PARAMS.aspect);
1064
+ const aspect: "16:9" | "2:3" | undefined =
1065
+ aspectParam === "2:3" ? "2:3" : aspectParam === "16:9" ? "16:9" : undefined;
1066
+
1067
+ 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>=");
1070
+ }
1071
+ if (!key) return errResp(400, "Missing required query param: shop");
1072
+
1073
+ // 1. Shop ID lookup → AccountData (404 unknown, 403 revoked).
1074
+ const account = await loadAccountByKey(key, env);
1075
+ if (!account) return errResp(404, "Unknown shop");
1076
+ if (account.revoked) return errResp(403, "Shop revoked");
1077
+
1078
+ const accountId = account.accountId;
1079
+
1080
+ // NOTE: the L1 page-origin / domain allowlist (Origin-then-Referer check) was
1081
+ // removed — browser privacy controls strip/spoof those headers, so it could
1082
+ // never be enforced. Anti-theft is the asset-source allowlist (L2, below) plus
1083
+ // signed URLs (L3). See ADR-0075/0076.
1084
+
1085
+ // Every image URL the design references (bare asset + per-placement srcs).
1086
+ const imageUrls: string[] = [];
1087
+ if (asset) imageUrls.push(asset);
1088
+ for (const k of designKeys) {
1089
+ const src = design[k].src;
1090
+ if (src) imageUrls.push(src);
1091
+ }
1092
+
1093
+ // 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
+ }
1105
+ }
1106
+ }
1107
+
1108
+ // 2c. L3 — required developer signature `s` over the canonical public URL.
1109
+ if (account.requireSig) {
1110
+ if (!account.l3Secret) {
1111
+ // Misconfigured: requireSig on but no secret to verify against. Fail closed.
1112
+ return errResp(403, "Signed URLs required but no L3 secret configured");
1113
+ }
1114
+ const provided = q.get(PARAMS.signature);
1115
+ if (!provided) return errResp(403, "Missing required signature");
1116
+ // canonicalForSig reads the RAW query verbatim — use the original URL string.
1117
+ const canonical = canonicalForSig(request.url);
1118
+ const expected = await signDevSig(canonical, account.l3Secret);
1119
+ let ok = expected.length === provided.length;
1120
+ if (ok) {
1121
+ let r = 0;
1122
+ for (let i = 0; i < expected.length; i++) {
1123
+ r |= expected.charCodeAt(i) ^ provided.charCodeAt(i);
1124
+ }
1125
+ ok = r === 0;
1126
+ }
1127
+ if (!ok) return errResp(403, "Invalid signature: s");
1128
+ }
1129
+
1130
+ // 3. Rate limit — reuse the existing per-account/IP public limiter.
1131
+ const clientIp =
1132
+ request.headers.get("CF-Connecting-IP") ||
1133
+ request.headers.get("X-Forwarded-For") ||
1134
+ "unknown-ip";
1135
+ // Global IP guard (same caps as authenticate()'s public path).
1136
+ try {
1137
+ const globalRl = env.API_RATE_LIMITER.get(
1138
+ env.API_RATE_LIMITER.idFromName(`global:public:${clientIp}`)
1139
+ );
1140
+ const perSec = await globalRl.checkRateLimit(20);
1141
+ if (!perSec.allowed) {
1142
+ const resp = errResp(429, "Rate limit exceeded");
1143
+ resp.headers.set(
1144
+ "Retry-After",
1145
+ String(Math.ceil((perSec.retryAfter ?? 1000) / 1000))
1146
+ );
1147
+ return resp;
1148
+ }
1149
+ const daily = await globalRl.checkDailyRateLimit(50000);
1150
+ if (!daily.allowed) {
1151
+ const resp = errResp(429, "Daily rate limit exceeded");
1152
+ if (daily.retryAfter) {
1153
+ resp.headers.set(
1154
+ "Retry-After",
1155
+ String(Math.ceil(daily.retryAfter / 1000))
1156
+ );
1157
+ }
1158
+ return resp;
1159
+ }
1160
+ } catch (e) {
1161
+ console.error(`Public resolve: global rate-limit error (fail open): ${e}`);
1162
+ }
1163
+ // Per-account public rate limit, if configured.
1164
+ if (account.public?.rateLimit) {
1165
+ try {
1166
+ const acctRl = env.API_RATE_LIMITER.get(
1167
+ env.API_RATE_LIMITER.idFromName(`${accountId}:public:${clientIp}`)
1168
+ );
1169
+ const result = await acctRl.checkRateLimit(account.public.rateLimit);
1170
+ if (!result.allowed) {
1171
+ const resp = errResp(429, "Rate limit exceeded");
1172
+ resp.headers.set(
1173
+ "Retry-After",
1174
+ String(Math.ceil((result.retryAfter ?? 1000) / 1000))
1175
+ );
1176
+ return resp;
1177
+ }
1178
+ } catch (e) {
1179
+ console.error(`Public resolve: account rate-limit error (fail open): ${e}`);
1180
+ }
1181
+ }
1182
+
1183
+ // 4. Resolve catalog config (Meilisearch, KV-cached).
1184
+ const meiliHost = env.MEILISEARCH_HOST;
1185
+ const meiliKey = env.MEILISEARCH_API_KEY;
1186
+ const meiliIndex = env.MEILISEARCH_INDEX;
1187
+ const mockupBaseUrl = env.MOCKUP_BASE_URL;
1188
+ if (!meiliHost || !meiliKey || !meiliIndex || !mockupBaseUrl) {
1189
+ return errResp(500, "Resolver not configured");
1190
+ }
1191
+ const product = await fetchProduct(
1192
+ productCode,
1193
+ { host: meiliHost, apiKey: meiliKey, index: meiliIndex },
1194
+ env.ACCOUNTS
1195
+ );
1196
+ if (!product) return errResp(404, `Product not found: ${productCode}`);
1197
+ // 4a. Resolve the variant from option picks (both catalog shapes) + the
1198
+ // render-only optionSelections rendercenter needs. resolveDefaults then supplies
1199
+ // the mockup scene and a default placement (for the bare-asset case).
1200
+ const vr = resolveVariant(product, optionPicks, variantOverride);
1201
+ if (!vr) {
1202
+ return errResp(422, `Product ${productCode} has no renderable combination`);
1203
+ }
1204
+ const scene = resolveDefaults(product, {
1205
+ variant: vr.variantId,
1206
+ mockupId: mockupOverride,
1207
+ placement: placementOverride,
1208
+ });
1209
+ if (!scene) {
1210
+ return errResp(422, `Product ${productCode} has no renderable combination`);
1211
+ }
1212
+
1213
+ // 4b. Build the design elements: a multi-placement map, or the single bare asset.
1214
+ const ALLOWED_TILES = [0.25, 0.5, 1, 2, 4];
1215
+ const ALIGNMENTS = new Set<string>([
1216
+ "center", "top", "far-top", "bottom", "far-bottom",
1217
+ "left", "far-left", "right", "far-right",
1218
+ ]);
1219
+ // Strict: the URL key must equal the placement's canonical catalog `key`
1220
+ // EXACTLY — no label/slug/case fallbacks. A wrong key fails loudly with
1221
+ // "Unknown placement" instead of being silently coerced, and this matches the
1222
+ // buy worker's strict `placementByKey.get(key)`, so any URL that previews is
1223
+ // guaranteed to also check out (no preview-works/buy-400s divergence).
1224
+ const findPlacement = (k: string) =>
1225
+ product.placements.find((p) => p.key === k);
1226
+
1227
+ const designElements: DesignElement[] = [];
1228
+ if (designKeys.length > 0) {
1229
+ for (const k of designKeys) {
1230
+ const fill = design[k];
1231
+ const pl = findPlacement(k);
1232
+ if (!pl) return errResp(400, `Unknown placement: ${k}`);
1233
+ if (fill.color) {
1234
+ designElements.push({
1235
+ type: "color",
1236
+ hex: fill.color,
1237
+ placement: pl.label,
1238
+ width: pl.width,
1239
+ height: pl.height,
1240
+ });
1241
+ } else if (fill.src) {
1242
+ const el: DesignElement = {
1243
+ type: "image",
1244
+ imageUrl: fill.src,
1245
+ placement: pl.label,
1246
+ width: pl.width,
1247
+ height: pl.height,
1248
+ alignment:
1249
+ fill.align && ALIGNMENTS.has(fill.align)
1250
+ ? (fill.align as ImageAlignment)
1251
+ : "center",
1252
+ };
1253
+ if (fill.tile !== undefined && ALLOWED_TILES.includes(fill.tile)) {
1254
+ el.tiles = fill.tile as 0.25 | 0.5 | 1 | 2 | 4;
1255
+ }
1256
+ designElements.push(el);
1257
+ }
1258
+ }
1259
+ } else if (asset) {
1260
+ designElements.push({
1261
+ type: "image",
1262
+ imageUrl: asset,
1263
+ placement: scene.placement.label,
1264
+ width: scene.placement.width,
1265
+ height: scene.placement.height,
1266
+ alignment: "center",
1267
+ });
1268
+ }
1269
+ if (designElements.length === 0) {
1270
+ return errResp(400, "Missing artwork: provide asset= or asset.<placement>=");
1271
+ }
1272
+ const MAX_ELEMENTS = 10; // mirrors rendercenter's shared MAX_ELEMENTS
1273
+ if (designElements.length > MAX_ELEMENTS) {
1274
+ return errResp(400, `Too many placements (max ${MAX_ELEMENTS})`);
1275
+ }
1276
+
1277
+ // 5. Build the render URL FRESH — never forward the incoming query string, so
1278
+ // the public `shop`/`signature` never leak onto the render URL (which carries
1279
+ // only the relay `seal`).
1280
+ let width = 1400;
1281
+ if (widthParam) {
1282
+ const parsedWidth = parseInt(widthParam, 10);
1283
+ if (Number.isFinite(parsedWidth) && parsedWidth > 0) width = parsedWidth;
1284
+ }
1285
+ const hasOptionSelections = Object.keys(vr.optionSelections).length > 0;
1286
+ const unsigned = buildMockupUrl(
1287
+ {
1288
+ productId: product.id,
1289
+ mockupId: scene.mockupId,
1290
+ variantId: vr.variantId,
1291
+ width,
1292
+ ...(aspect ? { aspect } : {}),
1293
+ ...(hasOptionSelections ? { optionSelections: vr.optionSelections } : {}),
1294
+ design: designElements,
1295
+ },
1296
+ { mockupBaseUrl, shop: accountId }
1297
+ );
1298
+
1299
+ // 6. Relay-sign internally (the SAME scheme rendercenter verifies — sign the
1300
+ // RELATIVE path+query minus seal). The developer never sees this secret.
1301
+ const signingSecret = env.URL_SIGNING_SECRET || "dev-unsigned";
1302
+ const urlObj = new URL(unsigned);
1303
+ const sigParams = new URLSearchParams(urlObj.search);
1304
+ sigParams.delete("seal");
1305
+ const relative = `${urlObj.pathname}?${sigParams.toString()}`;
1306
+ const sig = await signUrl(relative, signingSecret);
1307
+ urlObj.searchParams.append("seal", sig);
1308
+
1309
+ // 7. 302 to the relay-signed render URL, no-store on the REDIRECT.
1310
+ return new Response(null, {
1311
+ status: 302,
1312
+ headers: {
1313
+ Location: urlObj.toString(),
1314
+ ...NO_STORE,
1315
+ },
1316
+ });
1317
+ }
1318
+
1319
+ // Cloudflare Worker entry point
1320
+ export default {
1321
+ async fetch(request: Request, env: Env, ctx: any): Promise<Response> {
1322
+ // Add test endpoint
1323
+ const requestUrl = new URL(request.url);
1324
+ if (requestUrl.pathname === "/test-kv") {
1325
+ try {
1326
+ // Try to write a test key
1327
+ await env.ACCOUNTS.put("test-key", "test-value");
1328
+
1329
+ // Try to read all keys
1330
+ const keys = await env.ACCOUNTS.list();
1331
+
1332
+ // Try to read our test key
1333
+ const testValue = await env.ACCOUNTS.get("test-key");
1334
+
1335
+ // Try to read account123
1336
+ const account123 = await env.ACCOUNTS.get("account123");
1337
+
1338
+ return new Response(
1339
+ JSON.stringify({
1340
+ testWrite: "success",
1341
+ testRead: testValue,
1342
+ keys: keys,
1343
+ account123: account123,
1344
+ }),
1345
+ {
1346
+ headers: { "Content-Type": "application/json" },
1347
+ }
1348
+ );
1349
+ } catch (error: any) {
1350
+ return new Response(
1351
+ JSON.stringify({
1352
+ error: `KV test failed: ${error.message || String(error)}`,
1353
+ }),
1354
+ {
1355
+ status: 500,
1356
+ headers: { "Content-Type": "application/json" },
1357
+ }
1358
+ );
1359
+ }
1360
+ }
1361
+
1362
+ // Handle CORS preflight
1363
+ if (request.method === "OPTIONS") {
1364
+ return new Response(null, {
1365
+ headers: {
1366
+ "Access-Control-Allow-Origin": request.headers.get("Origin") || "*",
1367
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
1368
+ "Access-Control-Allow-Headers":
1369
+ "Content-Type, X-API-Key, X-Client-ID",
1370
+ },
1371
+ });
1372
+ }
1373
+
1374
+ const url = new URL(request.url);
1375
+
1376
+ // Agent legibility: a tiny pointer file so agents/crawlers landing on the
1377
+ // render origin can find the canonical docs and how to get a Shop ID.
1378
+ if (request.method === "GET" && url.pathname === "/llms.txt") {
1379
+ const body =
1380
+ "Snowcone render origin (img.snowcone.app).\n" +
1381
+ "Docs: https://developers.snowcone.app/llms.txt\n" +
1382
+ "Mint a shop: POST https://api.snowcone.app/shops/sandbox\n";
1383
+ return addCorsHeaders(
1384
+ new Response(body, {
1385
+ headers: { "Content-Type": "text/plain; charset=utf-8" },
1386
+ }),
1387
+ request,
1388
+ );
1389
+ }
1390
+
1391
+ // ADR-0076: the public image-CDN resolver on img.snowcone.app.
1392
+ // GET https://img.snowcone.app/{productCode}?asset=…&shop=…
1393
+ // Routed by Host (img.*) in production; in local dev (single host) we also
1394
+ // accept a GET to a non-reserved single-segment path carrying ?asset&shop
1395
+ // (or the legacy `key` alias), so the resolver is reachable without the
1396
+ // custom domain binding.
1397
+ 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]);
1411
+ return addCorsHeaders(
1412
+ await handlePublicResolve(request, env, productCode),
1413
+ request
1414
+ );
1415
+ }
1416
+
1417
+ // ADR-0073 §10: resolve (productCode → mockupId/gvid/placement) + build +
1418
+ // sign in one call, so a BFF passes only (assetUrl, productCode).
1419
+ if (url.pathname === "/mockups/url" && request.method === "POST") {
1420
+ return addCorsHeaders(await handleMockupUrl(request, env), request);
1421
+ }
1422
+
1423
+ // Parse the request URL
1424
+ if (url.pathname === "/sign" || url.pathname === "/verify") {
1425
+ // Authenticate the request
1426
+ const authResult = await authenticate(request, env);
1427
+ if (!authResult.authenticated) {
1428
+ const errorResponse = new Response(
1429
+ JSON.stringify({ error: authResult.error }),
1430
+ {
1431
+ status: authResult.error?.includes("Rate limit exceeded")
1432
+ ? 429
1433
+ : 401,
1434
+ headers: { "Content-Type": "application/json" },
1435
+ }
1436
+ );
1437
+ return addCorsHeaders(errorResponse, request);
1438
+ }
1439
+
1440
+ // require URL_SIGNING_SECRET
1441
+ if (!env.URL_SIGNING_SECRET) {
1442
+ const errorResponse = new Response("Missing URL_SIGNING_SECRET", {
1443
+ status: 500,
1444
+ headers: { "Content-Type": "application/json" },
1445
+ });
1446
+ return addCorsHeaders(errorResponse, request);
1447
+ }
1448
+
1449
+ const secretKey = env.URL_SIGNING_SECRET;
1450
+
1451
+ // Use the accountId that was extracted during authentication
1452
+ const accountId = authResult.accountId!;
1453
+
1454
+ if (url.pathname === "/sign") {
1455
+ // Get the URL to sign from the query parameter
1456
+ let urlToSign = url.searchParams.get("url");
1457
+ let isRelativeUrl = false;
1458
+
1459
+ if (!urlToSign) {
1460
+ const errorResponse = new Response("Missing URL parameter", {
1461
+ status: 400,
1462
+ });
1463
+ return addCorsHeaders(errorResponse, request);
1464
+ }
1465
+
1466
+ // Check if this is a relative URL (save this information for later)
1467
+ if (urlToSign.startsWith("/")) {
1468
+ isRelativeUrl = true;
1469
+ }
1470
+
1471
+ // Parse and validate the URL
1472
+ let urlObj: URL;
1473
+ try {
1474
+ // If it's a relative URL, add a dummy base for parsing purposes only
1475
+ if (isRelativeUrl) {
1476
+ console.log(
1477
+ "📝 Using temporary base URL for parsing a relative URL"
1478
+ );
1479
+ const baseUrl = "https://example.com";
1480
+ urlObj = new URL(urlToSign, baseUrl);
1481
+ } else {
1482
+ urlObj = new URL(urlToSign);
1483
+ }
1484
+ } catch (error) {
1485
+ console.error(`❌ Invalid URL format: ${urlToSign}`, error);
1486
+ const errorResponse = new Response(
1487
+ JSON.stringify({
1488
+ error:
1489
+ "Invalid URL format. The URL must be a valid absolute URL (with protocol) or a valid relative URL starting with /",
1490
+ }),
1491
+ {
1492
+ status: 400,
1493
+ headers: { "Content-Type": "application/json" },
1494
+ }
1495
+ );
1496
+ return addCorsHeaders(errorResponse, request);
1497
+ }
1498
+
1499
+ // Check if the URL should include accountId
1500
+ // We don't need to add it again - it should already be in the URL (validated by authenticate)
1501
+ // This is now just a check in case we want to override the behavior in the future
1502
+ const shouldIncludeAccountId =
1503
+ url.searchParams.get("includeAccountId") !== "false";
1504
+
1505
+ // We don't need to add accountId since it should already be in the URL
1506
+ // But we'll log a message if it doesn't match what we expect
1507
+ const urlShop =
1508
+ urlObj.searchParams.get("shop") ??
1509
+ urlObj.searchParams.get("accountId");
1510
+ if (shouldIncludeAccountId && urlShop !== accountId) {
1511
+ console.log(
1512
+ `⚠️ Warning: shop in URL (${urlShop}) doesn't match authenticated shop (${accountId})`
1513
+ );
1514
+ }
1515
+
1516
+ // Get the final URL string to sign (preserving the relative format if original was relative)
1517
+ let finalUrlToSign = isRelativeUrl
1518
+ ? urlObj.pathname + urlObj.search
1519
+ : urlObj.toString();
1520
+
1521
+ const signature = await signUrl(finalUrlToSign, secretKey);
1522
+
1523
+ // Construct the signed URL by adding the signature parameter
1524
+ urlObj.searchParams.append("seal", signature);
1525
+
1526
+ // Get the final URL with signature (preserving the relative format if original was relative)
1527
+ const urlWithSignature = isRelativeUrl
1528
+ ? urlObj.pathname + urlObj.search
1529
+ : urlObj.toString();
1530
+
1531
+ const response = new Response(
1532
+ JSON.stringify({
1533
+ signature,
1534
+ urlWithSignature,
1535
+ }),
1536
+ {
1537
+ headers: {
1538
+ "Content-Type": "application/json",
1539
+ },
1540
+ }
1541
+ );
1542
+ return addCorsHeaders(response, request);
1543
+ } else if (url.pathname === "/verify") {
1544
+ // Get URL and signature from query parameters
1545
+ let urlToVerify = url.searchParams.get("url");
1546
+ const signature = url.searchParams.get("signature");
1547
+ let isRelativeUrl = false;
1548
+
1549
+ if (!urlToVerify || !signature) {
1550
+ const errorResponse = new Response(
1551
+ "Missing URL or signature parameter",
1552
+ {
1553
+ status: 400,
1554
+ }
1555
+ );
1556
+ return addCorsHeaders(errorResponse, request);
1557
+ }
1558
+
1559
+ // Check if this is a relative URL (save this information for later)
1560
+ if (urlToVerify.startsWith("/")) {
1561
+ isRelativeUrl = true;
1562
+ }
1563
+
1564
+ // Parse and validate the URL
1565
+ let urlObj: URL;
1566
+ try {
1567
+ // If it's a relative URL, add a dummy base for parsing purposes only
1568
+ if (isRelativeUrl) {
1569
+ console.log(
1570
+ "📝 Using temporary base URL for parsing a relative URL"
1571
+ );
1572
+ const baseUrl = "https://example.com";
1573
+ urlObj = new URL(urlToVerify, baseUrl);
1574
+ } else {
1575
+ urlObj = new URL(urlToVerify);
1576
+ }
1577
+ } catch (error) {
1578
+ console.error(`❌ Invalid URL format: ${urlToVerify}`, error);
1579
+ const errorResponse = new Response(
1580
+ JSON.stringify({
1581
+ error:
1582
+ "Invalid URL format. The URL must be a valid absolute URL (with protocol) or a valid relative URL starting with /",
1583
+ }),
1584
+ {
1585
+ status: 400,
1586
+ headers: { "Content-Type": "application/json" },
1587
+ }
1588
+ );
1589
+ return addCorsHeaders(errorResponse, request);
1590
+ }
1591
+
1592
+ // The shop id should already be in the URL — this is a consistency check.
1593
+ const urlShopVerify =
1594
+ urlObj.searchParams.get("shop") ??
1595
+ urlObj.searchParams.get("accountId");
1596
+ if (urlShopVerify !== accountId) {
1597
+ console.log(
1598
+ `⚠️ Warning: shop in URL (${urlShopVerify}) doesn't match authenticated shop (${accountId})`
1599
+ );
1600
+ }
1601
+
1602
+ // Get the final URL string to verify (preserving the relative format if original was relative)
1603
+ let finalUrlToVerify = isRelativeUrl
1604
+ ? urlObj.pathname + urlObj.search
1605
+ : urlObj.toString();
1606
+
1607
+ const isValid = await verifyUrl(finalUrlToVerify, signature, secretKey);
1608
+ const response = new Response(JSON.stringify({ valid: isValid }), {
1609
+ headers: {
1610
+ "Content-Type": "application/json",
1611
+ },
1612
+ });
1613
+ return addCorsHeaders(response, request);
1614
+ }
1615
+ }
1616
+
1617
+ // Default route
1618
+ const response = new Response(
1619
+ JSON.stringify({
1620
+ message: "Mockup Resolver API",
1621
+ endpoints: [
1622
+ "/sign?url=<url-to-sign>",
1623
+ "/verify?url=<url-to-verify>&signature=<signature>",
1624
+ ],
1625
+ }),
1626
+ {
1627
+ headers: {
1628
+ "Content-Type": "application/json",
1629
+ },
1630
+ }
1631
+ );
1632
+ return addCorsHeaders(response, request);
1633
+ },
1634
+ };
1635
+
1636
+ // Example wrangler.toml configuration:
1637
+ /*
1638
+ name = "mockup-resolver"
1639
+ ...
1640
+ [vars]
1641
+ SECRET_KEY = "your-secret-key"
1642
+
1643
+ [[kv_namespaces]]
1644
+ binding = "ACCOUNTS"
1645
+ id = "your-kv-namespace-id-for-accounts"
1646
+
1647
+ [[durable_objects.bindings]]
1648
+ name = "API_RATE_LIMITER"
1649
+ class_name = "RateLimiter"
1650
+
1651
+ [[migrations]]
1652
+ tag = "v1"
1653
+ new_classes = ["RateLimiter"]
1654
+ */
1655
+
1656
+ // Example account data structure:
1657
+ /*
1658
+ {
1659
+ "accountId": "yFP34rCxcF",
1660
+ "apiKeys": [
1661
+ {
1662
+ "hash": "4241259ed7f5k4a69edp67579fd1c49634e1a32cf4e7ef43m41e25b83d7823d4",
1663
+ "prefix": "pq3b1q1H",
1664
+ "rateLimit": 60
1665
+ }
1666
+ ],
1667
+ "public": {
1668
+ "rateLimit": 100
1669
+ },
1670
+ "assetAllowlist": ["cdn.example.com", "*.example.org"],
1671
+ "requireSig": false
1672
+ }
1673
+ */