@snowcone-app/mockup-resolver 1.0.3 → 1.0.5
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 +14 -0
- package/dist/index.js +1278 -282
- package/package.json +2 -2
- package/src/asset-allowlist.ts +14 -68
- package/src/index.ts +375 -169
- package/src/public-params.ts +9 -1
- package/src/resolve.ts +143 -1
- package/test/public-params.test.ts +11 -2
- package/test/resolve.test.ts +169 -0
- package/wrangler.jsonc +7 -2
package/dist/index.js
CHANGED
|
@@ -1,48 +1,211 @@
|
|
|
1
1
|
// Remove Node.js crypto import and use Web Crypto API
|
|
2
2
|
// Web Crypto API is available globally in Cloudflare Workers
|
|
3
|
-
|
|
3
|
+
// Import Cloudflare-specific modules
|
|
4
|
+
import { DurableObject } from "cloudflare:workers";
|
|
5
|
+
// Rate Limiter Durable Object - implements RPC pattern
|
|
6
|
+
export class RateLimiter extends DurableObject {
|
|
7
|
+
state;
|
|
8
|
+
nextAllowedTime = 0; // Initialize to 0, so first request sets it relative to Date.now()
|
|
9
|
+
static milliseconds_for_grace_period = 10000; // Allow user to spend up to 10 seconds of their limit upfront
|
|
10
|
+
// Daily limit state
|
|
11
|
+
dailyRequestCount;
|
|
12
|
+
currentDayMarker; // YYYY-MM-DD in UTC
|
|
13
|
+
initialized = false;
|
|
14
|
+
initializePromise = null;
|
|
15
|
+
constructor(state, env) {
|
|
16
|
+
// Changed ctx to state and typed it
|
|
17
|
+
super(state, env);
|
|
18
|
+
this.state = state;
|
|
19
|
+
// Initialize with default values, will be overwritten by storage if available
|
|
20
|
+
this.dailyRequestCount = 0;
|
|
21
|
+
this.currentDayMarker = "";
|
|
22
|
+
// Initialization logic will be called by methods needing this state.
|
|
23
|
+
}
|
|
24
|
+
async ensureInitialized() {
|
|
25
|
+
if (!this.initialized) {
|
|
26
|
+
if (!this.initializePromise) {
|
|
27
|
+
this.initializePromise = this._initialize();
|
|
28
|
+
}
|
|
29
|
+
await this.initializePromise;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async _initialize() {
|
|
33
|
+
try {
|
|
34
|
+
const stored = await this.state.storage.get([
|
|
35
|
+
"dailyRequestCount",
|
|
36
|
+
"currentDayMarker",
|
|
37
|
+
]);
|
|
38
|
+
if (stored.has("dailyRequestCount")) {
|
|
39
|
+
this.dailyRequestCount = stored.get("dailyRequestCount");
|
|
40
|
+
}
|
|
41
|
+
if (stored.has("currentDayMarker")) {
|
|
42
|
+
this.currentDayMarker = stored.get("currentDayMarker");
|
|
43
|
+
}
|
|
44
|
+
console.log(`RateLimiter DO (${this.state.id.toString()}): Initialized daily state. Count: ${this.dailyRequestCount}, Day: ${this.currentDayMarker}`);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
console.error(`RateLimiter DO (${this.state.id.toString()}): Error during _initialize: ${error}`);
|
|
48
|
+
// Keep default values if storage fails
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
this.initialized = true;
|
|
52
|
+
this.initializePromise = null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// Helper to calculate wait time without side effects
|
|
56
|
+
_calculateCurrentWaitTime(requestsPerSecond) {
|
|
57
|
+
const now = Date.now();
|
|
58
|
+
// Determine the baseline for nextAllowedTime:
|
|
59
|
+
// If nextAllowedTime is in the past, the effective nextAllowedTime for *this* check is 'now'.
|
|
60
|
+
// Otherwise, it's the future time already set.
|
|
61
|
+
const effectiveNextAllowedTime = Math.max(now, this.nextAllowedTime);
|
|
62
|
+
const timeUntilEffectiveNextAllowed = effectiveNextAllowedTime - now;
|
|
63
|
+
const millisToWait = Math.max(0, timeUntilEffectiveNextAllowed - RateLimiter.milliseconds_for_grace_period);
|
|
64
|
+
return millisToWait;
|
|
65
|
+
}
|
|
66
|
+
// Helper to consume a slot and advance nextAllowedTime
|
|
67
|
+
_consumeSlot(requestsPerSecond) {
|
|
68
|
+
const now = Date.now();
|
|
69
|
+
const millisecondsPerRequest = 1000 / requestsPerSecond; // Changed from 60000 / requestsPerMinute
|
|
70
|
+
// Advance nextAllowedTime from its current value (or 'now' if it's in the past),
|
|
71
|
+
// and add the duration of one request.
|
|
72
|
+
this.nextAllowedTime =
|
|
73
|
+
Math.max(now, this.nextAllowedTime) + millisecondsPerRequest;
|
|
74
|
+
}
|
|
75
|
+
// Method name and signature now match the example but keeps our dynamic rate limit.
|
|
76
|
+
// This method is assumed to consume a slot, matching its original behavior when called directly (e.g., via RPC).
|
|
77
|
+
async getMillisecondsToNextRequest(requestsPerSecond = 1 // Changed from requestsPerMinute: number = 60
|
|
78
|
+
) {
|
|
79
|
+
// First, calculate what the wait time *would* be based on the current state.
|
|
80
|
+
const millisToWait = this._calculateCurrentWaitTime(requestsPerSecond);
|
|
81
|
+
// Then, consume the slot, advancing nextAllowedTime for the next potential request.
|
|
82
|
+
this._consumeSlot(requestsPerSecond);
|
|
83
|
+
// Return the wait time that was calculated *before* this call consumed the slot.
|
|
84
|
+
return millisToWait;
|
|
85
|
+
}
|
|
86
|
+
// Keep our original method for backward compatibility (now correctly implemented)
|
|
87
|
+
// This method checks the rate limit and only consumes a slot if the request is allowed.
|
|
88
|
+
async checkRateLimit(requestsPerSecond // Changed from requestsPerMinute
|
|
89
|
+
) {
|
|
90
|
+
const millisToWait = this._calculateCurrentWaitTime(requestsPerSecond);
|
|
91
|
+
if (millisToWait > 0) {
|
|
92
|
+
// If waiting is required, the request is not allowed, and no slot is consumed.
|
|
93
|
+
return { allowed: false, retryAfter: millisToWait };
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
// If no waiting is required, the request is allowed. Consume a slot for this request.
|
|
97
|
+
this._consumeSlot(requestsPerSecond);
|
|
98
|
+
return { allowed: true };
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// New methods for daily rate limiting
|
|
102
|
+
getCurrentDayMarker() {
|
|
103
|
+
const now = new Date();
|
|
104
|
+
// Use UTC to avoid timezone issues with "day" rollovers
|
|
105
|
+
return `${now.getUTCFullYear()}-${(now.getUTCMonth() + 1)
|
|
106
|
+
.toString()
|
|
107
|
+
.padStart(2, "0")}-${now.getUTCDate().toString().padStart(2, "0")}`;
|
|
108
|
+
}
|
|
109
|
+
async checkDailyRateLimit(dailyMaxRequests) {
|
|
110
|
+
await this.ensureInitialized(); // Ensure state is loaded
|
|
111
|
+
const todayMarker = this.getCurrentDayMarker();
|
|
112
|
+
if (this.currentDayMarker !== todayMarker) {
|
|
113
|
+
console.log(`RateLimiter DO (${this.state.id.toString()}): New day detected. Old: ${this.currentDayMarker}, New: ${todayMarker}. Resetting daily count.`);
|
|
114
|
+
this.currentDayMarker = todayMarker;
|
|
115
|
+
this.dailyRequestCount = 0; // Reset count first
|
|
116
|
+
try {
|
|
117
|
+
await this.state.storage.put({
|
|
118
|
+
currentDayMarker: this.currentDayMarker,
|
|
119
|
+
dailyRequestCount: this.dailyRequestCount,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
console.error(`RateLimiter DO (${this.state.id.toString()}): Error persisting daily state reset: ${error}`);
|
|
124
|
+
// If storage fails, proceed with in-memory state for resilience
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (this.dailyRequestCount >= dailyMaxRequests) {
|
|
128
|
+
const now = new Date();
|
|
129
|
+
const tomorrow = new Date(now);
|
|
130
|
+
tomorrow.setUTCDate(now.getUTCDate() + 1);
|
|
131
|
+
tomorrow.setUTCHours(0, 0, 0, 0);
|
|
132
|
+
const retryAfter = tomorrow.getTime() - now.getTime();
|
|
133
|
+
console.log(`RateLimiter DO (${this.state.id.toString()}): Daily limit EXCEEDED. Count: ${this.dailyRequestCount}/${dailyMaxRequests}.`);
|
|
134
|
+
return {
|
|
135
|
+
allowed: false,
|
|
136
|
+
retryAfter,
|
|
137
|
+
currentCount: this.dailyRequestCount,
|
|
138
|
+
dailyLimit: dailyMaxRequests,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
this.dailyRequestCount++;
|
|
142
|
+
try {
|
|
143
|
+
await this.state.storage.put("dailyRequestCount", this.dailyRequestCount);
|
|
144
|
+
// currentDayMarker is already up-to-date in memory and persisted if it was a new day.
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
console.error(`RateLimiter DO (${this.state.id.toString()}): Error persisting daily count increment: ${error}`);
|
|
148
|
+
// If storage fails, proceed with in-memory state for resilience
|
|
149
|
+
}
|
|
150
|
+
console.log(`RateLimiter DO (${this.state.id.toString()}): Daily count updated. Count: ${this.dailyRequestCount}/${dailyMaxRequests}.`);
|
|
151
|
+
return {
|
|
152
|
+
allowed: true,
|
|
153
|
+
currentCount: this.dailyRequestCount,
|
|
154
|
+
dailyLimit: dailyMaxRequests,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|
|
4
158
|
// Helper function to add CORS headers to a response
|
|
5
159
|
function addCorsHeaders(response, request) {
|
|
6
160
|
// Get the origin from the request
|
|
7
|
-
const origin = request.headers.get(
|
|
161
|
+
const origin = request.headers.get("Origin") || "*";
|
|
8
162
|
// Clone the response and add CORS headers
|
|
9
163
|
const corsResponse = new Response(response.body, response);
|
|
10
|
-
corsResponse.headers.set(
|
|
11
|
-
corsResponse.headers.set(
|
|
12
|
-
corsResponse.headers.set(
|
|
164
|
+
corsResponse.headers.set("Access-Control-Allow-Origin", origin);
|
|
165
|
+
corsResponse.headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
166
|
+
corsResponse.headers.set("Access-Control-Allow-Headers", "Content-Type, X-API-Key, X-Client-ID");
|
|
167
|
+
// This reflects the request Origin into ACAO, so shared caches MUST key on
|
|
168
|
+
// Origin — otherwise a cached entry for origin A (or a no-Origin request) is
|
|
169
|
+
// replayed to origin B and the crossorigin <img> fails (CORS poisoning).
|
|
170
|
+
// Preserve any upstream Vary rather than clobbering it.
|
|
171
|
+
const prevVary = corsResponse.headers.get("Vary");
|
|
172
|
+
corsResponse.headers.set("Vary", prevVary && !/\borigin\b/i.test(prevVary) ? `${prevVary}, Origin` : prevVary || "Origin");
|
|
13
173
|
return corsResponse;
|
|
14
174
|
}
|
|
175
|
+
// Helper function to hash an API key using SHA-256
|
|
176
|
+
async function hashApiKey(apiKey) {
|
|
177
|
+
// Convert string to bytes
|
|
178
|
+
const encoder = new TextEncoder();
|
|
179
|
+
const data = encoder.encode(apiKey);
|
|
180
|
+
// Calculate SHA-256 hash
|
|
181
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
182
|
+
// Convert to hex string
|
|
183
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
184
|
+
const hashHex = hashArray
|
|
185
|
+
.map((b) => b.toString(16).padStart(2, "0"))
|
|
186
|
+
.join("");
|
|
187
|
+
return hashHex;
|
|
188
|
+
}
|
|
15
189
|
// Authentication middleware
|
|
16
190
|
async function authenticate(request, env) {
|
|
17
|
-
console.log(
|
|
191
|
+
console.log("\n🔐 Authentication attempt");
|
|
18
192
|
// Get the URL from the request query parameters
|
|
19
193
|
const requestUrl = new URL(request.url);
|
|
20
|
-
const urlParam = requestUrl.searchParams.get(
|
|
21
|
-
// Check for backward compatibility - accountId in request URL
|
|
22
|
-
const legacyAccountId = requestUrl.searchParams.get('accountId');
|
|
23
|
-
if (legacyAccountId) {
|
|
24
|
-
console.log(`📝 Using legacy accountId from request parameter: ${legacyAccountId}`);
|
|
25
|
-
}
|
|
194
|
+
const urlParam = requestUrl.searchParams.get("url");
|
|
26
195
|
// If there's no URL parameter, we can't proceed
|
|
27
196
|
if (!urlParam) {
|
|
28
|
-
|
|
29
|
-
// let it pass and the worker will handle the authentication logic itself
|
|
30
|
-
if (legacyAccountId) {
|
|
31
|
-
console.log(`✅ Using legacy accountId parameter: ${legacyAccountId}`);
|
|
32
|
-
return { authenticated: true, accountId: legacyAccountId };
|
|
33
|
-
}
|
|
34
|
-
console.log('❌ Missing required url parameter');
|
|
197
|
+
console.log("❌ Missing required url parameter");
|
|
35
198
|
return {
|
|
36
199
|
authenticated: false,
|
|
37
|
-
error:
|
|
200
|
+
error: "Missing required url parameter",
|
|
38
201
|
};
|
|
39
202
|
}
|
|
40
203
|
// Parse the URL to sign/verify to extract accountId from it
|
|
41
204
|
let urlToProcess;
|
|
42
205
|
try {
|
|
43
206
|
// If it's a relative URL, add a base for parsing
|
|
44
|
-
if (urlParam.startsWith(
|
|
45
|
-
urlToProcess = new URL(urlParam,
|
|
207
|
+
if (urlParam.startsWith("/")) {
|
|
208
|
+
urlToProcess = new URL(urlParam, "https://example.com");
|
|
46
209
|
}
|
|
47
210
|
else {
|
|
48
211
|
urlToProcess = new URL(urlParam);
|
|
@@ -52,23 +215,20 @@ async function authenticate(request, env) {
|
|
|
52
215
|
console.log(`❌ Invalid URL format: ${urlParam}`);
|
|
53
216
|
return {
|
|
54
217
|
authenticated: false,
|
|
55
|
-
error:
|
|
218
|
+
error: "Invalid URL format in url parameter",
|
|
56
219
|
};
|
|
57
220
|
}
|
|
58
|
-
// Extract
|
|
59
|
-
|
|
60
|
-
//
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
console.log(`📝 Using legacy accountId since it's not in the URL to sign: ${legacyAccountId}`);
|
|
64
|
-
accountId = legacyAccountId;
|
|
65
|
-
}
|
|
221
|
+
// Extract the shop id from the URL to sign/verify. Canonical param is `shop`
|
|
222
|
+
// (what the mockup-url builder + delivery emit); accept legacy `accountId`
|
|
223
|
+
// too. Local var name kept as `accountId` to limit blast radius downstream.
|
|
224
|
+
const accountId = urlToProcess.searchParams.get("shop") ??
|
|
225
|
+
urlToProcess.searchParams.get("accountId");
|
|
66
226
|
// Validate accountId requirement
|
|
67
227
|
if (!accountId) {
|
|
68
|
-
console.log(
|
|
228
|
+
console.log("❌ Missing required accountId in the URL to sign/verify");
|
|
69
229
|
return {
|
|
70
230
|
authenticated: false,
|
|
71
|
-
error:
|
|
231
|
+
error: "Missing required accountId in the URL to sign/verify",
|
|
72
232
|
};
|
|
73
233
|
}
|
|
74
234
|
// Validate accountId length
|
|
@@ -76,296 +236,1127 @@ async function authenticate(request, env) {
|
|
|
76
236
|
console.log(`❌ Invalid accountId: ${accountId} (must be at least 6 characters)`);
|
|
77
237
|
return {
|
|
78
238
|
authenticated: false,
|
|
79
|
-
error:
|
|
239
|
+
error: "Invalid accountId: must be at least 6 characters",
|
|
80
240
|
};
|
|
81
241
|
}
|
|
82
242
|
console.log(`✅ Valid accountId format: ${accountId}`);
|
|
83
243
|
// Get account data from KV store
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
244
|
+
console.log(`🔍 Looking up account data in KV store for accountId: ${accountId}`);
|
|
245
|
+
let accountData;
|
|
246
|
+
try {
|
|
247
|
+
// Directly get the specific account data by ID
|
|
248
|
+
const accountDataStr = await env.ACCOUNTS.get(accountId);
|
|
249
|
+
console.log(`📦 KV store response for ${accountId}:`, accountDataStr ? "Data found" : "No data found");
|
|
250
|
+
if (!accountDataStr) {
|
|
251
|
+
console.log(`🤷 Account data not found in KV for ${accountId}. Fetching from source API...`);
|
|
252
|
+
try {
|
|
253
|
+
// Account-config fallback source (ADR-0073 §1): both the backend URL
|
|
254
|
+
// and the service token are env-configured. The base URL defaults to
|
|
255
|
+
// localhost:4000 for local dev; the token is a SECRET with no source
|
|
256
|
+
// default (set via `wrangler secret put KV_CACHE_SERVICE_TOKEN` in prod,
|
|
257
|
+
// or process-compose `--var` locally — same as URL_SIGNING_SECRET).
|
|
258
|
+
const kvCacheBaseUrl = env.KV_CACHE_BASE_URL || "http://localhost:4000";
|
|
259
|
+
const kvCacheServiceToken = env.KV_CACHE_SERVICE_TOKEN;
|
|
260
|
+
if (!kvCacheServiceToken) {
|
|
261
|
+
console.log(`❌ KV_CACHE_SERVICE_TOKEN not configured; cannot fetch account ${accountId} from the backend config source.`);
|
|
262
|
+
return {
|
|
263
|
+
authenticated: false,
|
|
264
|
+
error: "Account configuration source unavailable (signer not configured)",
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
const externalApiUrl = new URL(`${kvCacheBaseUrl.replace(/\/+$/, "")}/kv-cache/api-key`);
|
|
268
|
+
// Backend /kv-cache/api-key reads `shop` (was binding `shopId`; sending
|
|
269
|
+
// `accountId` was silently ignored, so cache-miss lookups failed).
|
|
270
|
+
externalApiUrl.searchParams.append("shop", accountId);
|
|
271
|
+
const response = await fetch(externalApiUrl.toString(), {
|
|
272
|
+
method: "GET",
|
|
273
|
+
headers: {
|
|
274
|
+
Authorization: `Bearer ${kvCacheServiceToken}`,
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
if (!response.ok) {
|
|
278
|
+
const errorText = await response.text();
|
|
279
|
+
console.log(`❌ Failed to fetch account data from source API for ${accountId}. Status: ${response.status}, Body: ${errorText}`);
|
|
280
|
+
return {
|
|
281
|
+
authenticated: false,
|
|
282
|
+
error: `Failed to retrieve account information for ${accountId}. API status: ${response.status}`,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
// Fetch data as 'any' for more flexible initial parsing
|
|
286
|
+
const rawFetchedData = (await response.json());
|
|
287
|
+
console.log(`✅ Successfully fetched account data from source API for ${accountId}`);
|
|
288
|
+
// Validate core data structure
|
|
289
|
+
if (!rawFetchedData ||
|
|
290
|
+
typeof rawFetchedData.accountId !== "string" ||
|
|
291
|
+
!Array.isArray(rawFetchedData.apiKeys) ||
|
|
292
|
+
typeof rawFetchedData.public !== "object" || // Ensure public is an object
|
|
293
|
+
rawFetchedData.public === null // And not null
|
|
294
|
+
) {
|
|
295
|
+
console.log(`❌ Invalid core data structure received from source API for ${accountId}. Data: ${JSON.stringify(rawFetchedData)}`);
|
|
296
|
+
return {
|
|
297
|
+
authenticated: false,
|
|
298
|
+
error: "Invalid data structure from account information source.",
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
// Process apiKeys to ensure structure and 'scopes' field
|
|
302
|
+
const processedApiKeys = rawFetchedData.apiKeys
|
|
303
|
+
.map((key) => {
|
|
304
|
+
if (typeof key.hash !== "string" ||
|
|
305
|
+
typeof key.prefix !== "string") {
|
|
306
|
+
console.log(`⚠️ Malformed API key object in fetched data for account ${accountId}, skipping. Key: ${JSON.stringify(key)}`);
|
|
307
|
+
return null; // Mark for filtering
|
|
308
|
+
}
|
|
309
|
+
return {
|
|
310
|
+
hash: key.hash,
|
|
311
|
+
prefix: key.prefix,
|
|
312
|
+
rateLimit: typeof key.rateLimit === "number" ? key.rateLimit : undefined,
|
|
313
|
+
scopes: Array.isArray(key.scopes) ? key.scopes : [], // Default to empty array if scopes is missing/invalid
|
|
314
|
+
};
|
|
315
|
+
})
|
|
316
|
+
.filter((key) => key !== null);
|
|
317
|
+
const accountDataToStore = {
|
|
318
|
+
accountId: rawFetchedData.accountId,
|
|
319
|
+
apiKeys: processedApiKeys,
|
|
320
|
+
public: rawFetchedData.public, // Assume PublicData structure is as expected or needs separate validation if complex
|
|
321
|
+
// ADR-0076 ladder fields — pass through when the backend supplies them.
|
|
322
|
+
assetAllowlist: Array.isArray(rawFetchedData.assetAllowlist)
|
|
323
|
+
? rawFetchedData.assetAllowlist
|
|
324
|
+
: undefined,
|
|
325
|
+
l3Secret: typeof rawFetchedData.l3Secret === "string"
|
|
326
|
+
? rawFetchedData.l3Secret
|
|
327
|
+
: undefined,
|
|
328
|
+
requireSig: rawFetchedData.requireSig === true ? true : undefined,
|
|
329
|
+
revoked: rawFetchedData.revoked === true ? true : undefined,
|
|
330
|
+
};
|
|
331
|
+
// Store in KV for next time
|
|
332
|
+
await env.ACCOUNTS.put(accountId, JSON.stringify(accountDataToStore));
|
|
333
|
+
console.log(`💾 Stored processed account data in KV for ${accountId}`);
|
|
334
|
+
accountData = accountDataToStore; // Use the processed and validated data
|
|
335
|
+
}
|
|
336
|
+
catch (apiError) {
|
|
337
|
+
console.error(`💥 Error fetching account data from source API for ${accountId}:`, apiError);
|
|
338
|
+
return {
|
|
339
|
+
authenticated: false,
|
|
340
|
+
error: `Error fetching account information: ${apiError.message || String(apiError)}`,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
else {
|
|
345
|
+
// Parse account data from KV
|
|
346
|
+
accountData = JSON.parse(accountDataStr);
|
|
347
|
+
}
|
|
348
|
+
console.log(`📋 Account data ready for: ${accountId}`);
|
|
349
|
+
// Verify the accountId in the data matches the requested accountId
|
|
350
|
+
if (accountData.accountId !== accountId) {
|
|
351
|
+
console.log(`❌ Account ID mismatch: requested ${accountId}, found ${accountData.accountId}`);
|
|
352
|
+
return {
|
|
353
|
+
authenticated: false,
|
|
354
|
+
error: `Account ID mismatch`,
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
catch (error) {
|
|
359
|
+
console.error("Error accessing KV store:", error);
|
|
87
360
|
return {
|
|
88
361
|
authenticated: false,
|
|
89
|
-
error:
|
|
362
|
+
error: `Error accessing KV store: ${error.message || String(error)}`,
|
|
90
363
|
};
|
|
91
364
|
}
|
|
92
|
-
// Parse account data
|
|
93
|
-
const accountData = JSON.parse(accountDataStr);
|
|
94
365
|
// Method 1: API Key Authentication (server-side)
|
|
95
|
-
const apiKey = request.headers.get(
|
|
366
|
+
const apiKey = request.headers.get("x-api-key");
|
|
96
367
|
if (apiKey) {
|
|
97
|
-
console.log(
|
|
98
|
-
//
|
|
99
|
-
|
|
100
|
-
|
|
368
|
+
console.log("📝 Using API Key authentication (server-side)");
|
|
369
|
+
// Extract the prefix (first 8 characters)
|
|
370
|
+
const apiKeyPrefix = apiKey.substring(0, 8);
|
|
371
|
+
console.log(`🔑 API Key prefix: ${apiKeyPrefix}`);
|
|
372
|
+
// Find API key with matching prefix
|
|
373
|
+
const matchingApiKey = accountData.apiKeys.find((key) => key.prefix === apiKeyPrefix);
|
|
374
|
+
if (!matchingApiKey) {
|
|
375
|
+
console.log(`❌ No API key found with prefix: ${apiKeyPrefix}`);
|
|
376
|
+
return {
|
|
377
|
+
authenticated: false,
|
|
378
|
+
error: "Invalid API key for this account",
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
// Calculate the hash of the provided API key
|
|
382
|
+
const calculatedHash = await hashApiKey(apiKey);
|
|
383
|
+
// Verify the hash matches the stored hash
|
|
384
|
+
if (calculatedHash !== matchingApiKey.hash) {
|
|
385
|
+
console.log(`❌ API key hash verification failed`);
|
|
101
386
|
return {
|
|
102
387
|
authenticated: false,
|
|
103
|
-
error:
|
|
388
|
+
error: "Invalid API key for this account",
|
|
104
389
|
};
|
|
105
390
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
391
|
+
// Check for required scope
|
|
392
|
+
if (!matchingApiKey.scopes || !matchingApiKey.scopes.includes("mockups")) {
|
|
393
|
+
console.log(`❌ API key for account ${accountId} does not have required 'mockups' scope. Found scopes: ${matchingApiKey.scopes}`);
|
|
394
|
+
return {
|
|
395
|
+
authenticated: false,
|
|
396
|
+
error: "API key missing required scope: mockups",
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
console.log(`✅ API key has required 'mockups' scope.`);
|
|
400
|
+
console.log(`✅ API key verified for account: ${accountId}`);
|
|
401
|
+
// Check rate limit if defined for this API key
|
|
402
|
+
if (matchingApiKey.rateLimit) {
|
|
403
|
+
try {
|
|
404
|
+
// Create a unique ID for this API key's rate limiter
|
|
405
|
+
const rateLimiterId = env.API_RATE_LIMITER.idFromName(`${accountId}:${apiKeyPrefix}`);
|
|
406
|
+
const rateLimiter = env.API_RATE_LIMITER.get(rateLimiterId);
|
|
407
|
+
// Call the method directly on the Durable Object via RPC
|
|
408
|
+
const result = await rateLimiter.checkRateLimit(matchingApiKey.rateLimit);
|
|
409
|
+
if (!result.allowed) {
|
|
410
|
+
console.log(`❌ Rate limit exceeded for API key: ${apiKeyPrefix}`);
|
|
411
|
+
return {
|
|
412
|
+
authenticated: false,
|
|
413
|
+
error: `Rate limit exceeded. Try again in ${Math.ceil(result.retryAfter / 1000)} seconds`,
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
console.log(`✅ Rate limit check passed for API key: ${apiKeyPrefix}`);
|
|
417
|
+
}
|
|
418
|
+
catch (error) {
|
|
419
|
+
// If there's an error checking the rate limit, log it but continue (fail open)
|
|
420
|
+
console.error(`Error checking rate limit: ${error}`);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
110
423
|
return { authenticated: true, accountId };
|
|
111
424
|
}
|
|
112
|
-
// Method 2:
|
|
113
|
-
//
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
console.log(
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
425
|
+
// Method 2: Public (client-side/web) access.
|
|
426
|
+
// The page-origin / domain allowlist that used to gate this path was removed —
|
|
427
|
+
// browsers strip/spoof Origin & Referer, so it was unenforceable. Public access
|
|
428
|
+
// is now governed by rate limits (below) plus the asset allowlist (L2) and
|
|
429
|
+
// signed URLs (L3) enforced at the resolver. See ADR-0075/0076.
|
|
430
|
+
console.log(`\n🔑 Using Public access (client-side/web), rate-limited by IP`);
|
|
431
|
+
// Get the client IP address (moved here to be available for both global and account-specific public rate limits)
|
|
432
|
+
const clientIp = request.headers.get("CF-Connecting-IP") ||
|
|
433
|
+
request.headers.get("X-Forwarded-For") ||
|
|
434
|
+
"unknown-ip";
|
|
435
|
+
// Global IP Rate Limiter (handles both per-second and per-day)
|
|
436
|
+
const GLOBAL_IP_RATE_LIMIT_RPS = 20;
|
|
437
|
+
const GLOBAL_DAILY_IP_RATE_LIMIT = 50000; // New daily limit
|
|
438
|
+
try {
|
|
439
|
+
const globalRateLimiterId = env.API_RATE_LIMITER.idFromName(`global:public:${clientIp}`);
|
|
440
|
+
const globalRateLimiter = env.API_RATE_LIMITER.get(globalRateLimiterId);
|
|
441
|
+
// Check global per-second IP rate limit
|
|
442
|
+
const globalPerSecondRateLimitResult = await globalRateLimiter.checkRateLimit(GLOBAL_IP_RATE_LIMIT_RPS);
|
|
443
|
+
if (!globalPerSecondRateLimitResult.allowed) {
|
|
444
|
+
console.log(`❌ Global IP per-second rate limit exceeded for IP: ${clientIp}`);
|
|
445
|
+
return {
|
|
446
|
+
authenticated: false,
|
|
447
|
+
error: `Global per-second rate limit exceeded. Try again in ${Math.ceil(globalPerSecondRateLimitResult.retryAfter / 1000)} seconds`,
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
console.log(`✅ Global IP per-second rate limit check passed for IP: ${clientIp}`);
|
|
451
|
+
// Check global daily IP rate limit
|
|
452
|
+
const dailyRateLimitResult = await globalRateLimiter.checkDailyRateLimit(GLOBAL_DAILY_IP_RATE_LIMIT);
|
|
453
|
+
if (!dailyRateLimitResult.allowed) {
|
|
454
|
+
console.log(`❌ Global daily IP rate limit exceeded for IP: ${clientIp}. Count: ${dailyRateLimitResult.currentCount}/${dailyRateLimitResult.dailyLimit}`);
|
|
455
|
+
let retryMessage = "Global daily rate limit exceeded.";
|
|
456
|
+
if (dailyRateLimitResult.retryAfter) {
|
|
457
|
+
const totalSeconds = Math.floor(dailyRateLimitResult.retryAfter / 1000);
|
|
458
|
+
const hours = Math.floor(totalSeconds / 3600);
|
|
459
|
+
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
460
|
+
retryMessage += ` Try again in approximately ${hours}h ${minutes}m.`;
|
|
461
|
+
}
|
|
462
|
+
return {
|
|
463
|
+
authenticated: false,
|
|
464
|
+
error: retryMessage,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
console.log(`✅ Global daily IP rate limit check passed for IP: ${clientIp}. Count: ${dailyRateLimitResult.currentCount}/${dailyRateLimitResult.dailyLimit}`);
|
|
125
468
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
authenticated: false,
|
|
131
|
-
error: 'Unknown clientId for this account',
|
|
132
|
-
};
|
|
469
|
+
catch (error) {
|
|
470
|
+
console.error(`Error checking global IP rate limits (per-second or daily): ${error}`);
|
|
471
|
+
// Fail open for global rate limit errors to prevent service disruption if DO fails,
|
|
472
|
+
// but log the error. Account-specific limits will still apply.
|
|
133
473
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
474
|
+
// Check account-specific rate limit for public requests if defined
|
|
475
|
+
if (accountData.public.rateLimit) {
|
|
476
|
+
try {
|
|
477
|
+
// Client IP already determined above
|
|
478
|
+
// Create a unique ID for this IP's rate limiter under this account
|
|
479
|
+
const rateLimiterId = env.API_RATE_LIMITER.idFromName(`${accountId}:public:${clientIp}`);
|
|
480
|
+
const rateLimiter = env.API_RATE_LIMITER.get(rateLimiterId);
|
|
481
|
+
// Call the method directly on the Durable Object via RPC
|
|
482
|
+
const result = await rateLimiter.checkRateLimit(accountData.public.rateLimit);
|
|
483
|
+
if (!result.allowed) {
|
|
484
|
+
console.log(`❌ Rate limit exceeded for IP: ${clientIp}`);
|
|
485
|
+
return {
|
|
486
|
+
authenticated: false,
|
|
487
|
+
error: `Rate limit exceeded. Try again in ${Math.ceil(result.retryAfter / 1000)} seconds`,
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
console.log(`✅ Rate limit check passed for IP: ${clientIp}`);
|
|
491
|
+
}
|
|
492
|
+
catch (error) {
|
|
493
|
+
// If there's an error checking the rate limit, log it but continue (fail open)
|
|
494
|
+
console.error(`Error checking rate limit: ${error}`);
|
|
495
|
+
}
|
|
146
496
|
}
|
|
147
|
-
|
|
148
|
-
// if (clientData.rateLimit) { ... }
|
|
149
|
-
console.log('✅ Authentication successful');
|
|
497
|
+
console.log("✅ Authentication successful");
|
|
150
498
|
return { authenticated: true, accountId };
|
|
151
499
|
}
|
|
152
|
-
//
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
500
|
+
// NOTE: `isOriginAllowed` (the page-origin / domain allowlist matcher) was
|
|
501
|
+
// removed alongside the `allowedOrigins` config — see the PublicData comment
|
|
502
|
+
// above. `globToRegExp` moved to ./asset-allowlist (pure module, unit-tested
|
|
503
|
+
// in the default test glob) along with the L2 check; the asset-source
|
|
504
|
+
// allowlist (L2) still uses it.
|
|
505
|
+
export { signUrl, verifyUrl } from "./signing";
|
|
506
|
+
import { signUrl, verifyUrl } from "./signing";
|
|
507
|
+
import { checkAssetUrls } from "./asset-allowlist";
|
|
508
|
+
import { fetchDesign } from "./design-ref";
|
|
509
|
+
import { buildMockupUrl, canonicalForSig, normalizeBgColor, signDevSig, parsePublicUrl, PARAMS, } from "@snowcone-app/mockup-url";
|
|
510
|
+
import { assembleArtwork, fetchProduct, looksLikeResolveRequest, resolveAlbumPagePlacement, resolveDefaults, resolveVariant, } from "./resolve";
|
|
511
|
+
import { rejectUnknownPublicParams } from "./public-params";
|
|
512
|
+
// ADR-0073 §10 — resolve + build + sign for `getMockupUrl(assetUrl, productCode)`.
|
|
513
|
+
// The BFF POSTs { accountId, productCode, assetUrl, variant?, mockupId?, placement?, width? }
|
|
514
|
+
// with x-api-key (or a browser with an allowed Origin). We auth (reusing the
|
|
515
|
+
// existing rate-limited authenticate()), resolve catalog defaults from
|
|
516
|
+
// Meilisearch (KV-cached), build the canonical URL, and sign it the SAME way
|
|
517
|
+
// /sign does (so it validates at rendercenter identically).
|
|
518
|
+
async function handleMockupUrl(request, env) {
|
|
519
|
+
const json = (body, status = 200) => new Response(JSON.stringify(body), {
|
|
520
|
+
status,
|
|
521
|
+
headers: { "Content-Type": "application/json" },
|
|
522
|
+
});
|
|
523
|
+
// Structured error envelope (Stripe-style): `{ error: { code, message } }`.
|
|
524
|
+
// `code` is a stable machine string integrators branch on; `message` is
|
|
525
|
+
// human-facing and may change. Keep codes in sync with the SDK's typed error.
|
|
526
|
+
const err = (status, code, message) => json({ error: { code, message } }, status);
|
|
527
|
+
let body;
|
|
166
528
|
try {
|
|
167
|
-
|
|
168
|
-
console.log(`🌐 Parsed origin URL - hostname: ${originUrl.hostname}, protocol: ${originUrl.protocol}`);
|
|
529
|
+
body = (await request.json());
|
|
169
530
|
}
|
|
170
|
-
catch
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
531
|
+
catch {
|
|
532
|
+
return err(400, "invalid_json", "Request body is not valid JSON");
|
|
533
|
+
}
|
|
534
|
+
const { accountId, productCode, assetUrl } = body;
|
|
535
|
+
if (!accountId || !productCode || !assetUrl) {
|
|
536
|
+
return err(400, "missing_fields", "Missing required fields: accountId, productCode, assetUrl");
|
|
537
|
+
}
|
|
538
|
+
// Default to 'dev-unsigned' to match the rendercenter verifier's default
|
|
539
|
+
// (services/rendercenter/api/src/config.ts) — so local dev works with no
|
|
540
|
+
// secret config and sigs validate. Production sets a real wrangler secret.
|
|
541
|
+
const signingSecret = env.URL_SIGNING_SECRET || "dev-unsigned";
|
|
542
|
+
const meiliHost = env.MEILISEARCH_HOST;
|
|
543
|
+
const meiliKey = env.MEILISEARCH_API_KEY;
|
|
544
|
+
const meiliIndex = env.MEILISEARCH_INDEX;
|
|
545
|
+
const mockupBaseUrl = env.MOCKUP_BASE_URL;
|
|
546
|
+
if (!meiliHost || !meiliKey || !meiliIndex || !mockupBaseUrl) {
|
|
547
|
+
return err(500, "not_configured", "Resolve endpoint not configured (Meilisearch / MOCKUP_BASE_URL)");
|
|
548
|
+
}
|
|
549
|
+
// Authenticate + rate-limit at mint time, reusing the existing path. We hand
|
|
550
|
+
// authenticate() a minimal accountId-bearing url so its account lookup +
|
|
551
|
+
// key/origin checks + rate limit all run before we touch the catalog.
|
|
552
|
+
//
|
|
553
|
+
// LOCAL DEV ONLY: when the signing secret is the dev default ('dev-unsigned'),
|
|
554
|
+
// skip the account lookup — there's no provisioned account/KV in a workspace,
|
|
555
|
+
// and the local BFF is trusted. This bypass is IMPOSSIBLE in production:
|
|
556
|
+
// production sets a real URL_SIGNING_SECRET (wrangler secret), so the branch
|
|
557
|
+
// below is never taken and full API-key + account auth always runs.
|
|
558
|
+
const isDevUnsigned = signingSecret === "dev-unsigned";
|
|
559
|
+
if (!isDevUnsigned) {
|
|
560
|
+
const authProbeUrl = `https://signer.internal/auth?url=${encodeURIComponent(`https://i/mockup?shop=${encodeURIComponent(accountId)}`)}`;
|
|
561
|
+
const authReq = new Request(authProbeUrl, { method: "GET", headers: request.headers });
|
|
562
|
+
const authResult = await authenticate(authReq, env);
|
|
563
|
+
if (!authResult.authenticated) {
|
|
564
|
+
const limited = authResult.error?.includes("Rate limit exceeded");
|
|
565
|
+
const missingScope = authResult.error?.includes("scope");
|
|
566
|
+
return err(limited ? 429 : 401, limited ? "rate_limited" : missingScope ? "missing_scope" : "unauthorized", authResult.error ?? "Authentication failed");
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
// Resolve catalog defaults (Meilisearch, KV-cached).
|
|
570
|
+
const product = await fetchProduct(productCode, {
|
|
571
|
+
host: meiliHost,
|
|
572
|
+
apiKey: meiliKey,
|
|
573
|
+
index: meiliIndex,
|
|
574
|
+
}, env.ACCOUNTS);
|
|
575
|
+
if (!product) {
|
|
576
|
+
return err(404, "product_not_found", `Product not found: ${productCode}`);
|
|
577
|
+
}
|
|
578
|
+
const resolved = resolveDefaults(product, {
|
|
579
|
+
variant: body.variant,
|
|
580
|
+
mockupId: body.mockupId,
|
|
581
|
+
placement: body.placement,
|
|
582
|
+
});
|
|
583
|
+
if (!resolved) {
|
|
584
|
+
return err(422, "unrenderable_product", `Product ${productCode} has no renderable variant/mockup/placement`);
|
|
585
|
+
}
|
|
586
|
+
// Build the canonical (unsigned) URL.
|
|
587
|
+
const unsigned = buildMockupUrl({
|
|
588
|
+
productId: product.id,
|
|
589
|
+
mockupId: resolved.mockupId,
|
|
590
|
+
variantId: resolved.variantId,
|
|
591
|
+
width: body.width ?? 1400,
|
|
592
|
+
design: [
|
|
593
|
+
{
|
|
594
|
+
type: "image",
|
|
595
|
+
imageUrl: assetUrl,
|
|
596
|
+
placement: resolved.placement.label,
|
|
597
|
+
width: resolved.placement.width,
|
|
598
|
+
height: resolved.placement.height,
|
|
599
|
+
alignment: "center",
|
|
600
|
+
},
|
|
601
|
+
],
|
|
602
|
+
}, { mockupBaseUrl, shop: accountId });
|
|
603
|
+
// Sign the RELATIVE path+query, mirroring the rendercenter verifier
|
|
604
|
+
// (services/rendercenter/api/src/utils/url-verifier.ts `extractSignature`):
|
|
605
|
+
// it HMACs `path + "?" + URLSearchParams(query−seal).toString()` because Fastify
|
|
606
|
+
// sees only the relative request URL. Signing the absolute URL would not validate.
|
|
607
|
+
const urlObj = new URL(unsigned);
|
|
608
|
+
const sigParams = new URLSearchParams(urlObj.search);
|
|
609
|
+
sigParams.delete("seal");
|
|
610
|
+
const relative = `${urlObj.pathname}?${sigParams.toString()}`;
|
|
611
|
+
const sig = await signUrl(relative, signingSecret);
|
|
612
|
+
urlObj.searchParams.append("seal", sig);
|
|
613
|
+
return json({ url: urlObj.toString() });
|
|
614
|
+
}
|
|
615
|
+
// ───────────────────────────────────────────────────────────────────────────
|
|
616
|
+
// ADR-0076 — the public image-CDN resolver (img.snowcone.app).
|
|
617
|
+
//
|
|
618
|
+
// GET https://img.snowcone.app/{productCode}?asset=…&shop=…[&w&mockup&variant&placement&s]
|
|
619
|
+
// → 302 → cdn.snowcone.app/mockup?…&sig (relay-signed render URL)
|
|
620
|
+
//
|
|
621
|
+
// The developer's `shop` (Shop ID; legacy alias `key`) is a PUBLIC token
|
|
622
|
+
// (= shop.id by default). The resolver
|
|
623
|
+
// authorizes off that public token, runs the existing catalog resolve, builds
|
|
624
|
+
// the render URL FRESH (never forwarding the incoming query string), relay-signs
|
|
625
|
+
// it internally, and 302s. The developer never holds the relay secret. The only
|
|
626
|
+
// "secret" a developer ever uses is the optional per-shop L3 `&s`.
|
|
627
|
+
// ───────────────────────────────────────────────────────────────────────────
|
|
628
|
+
/**
|
|
629
|
+
* Load AccountData for a public `key` from the ACCOUNTS KV, with the same
|
|
630
|
+
* backend fallback the existing authenticate() uses. Returns null if the key is
|
|
631
|
+
* unknown or the backend can't supply it (treated as 404 upstream).
|
|
632
|
+
*/
|
|
633
|
+
async function loadAccountByKey(key, env) {
|
|
634
|
+
let accountDataStr = await env.ACCOUNTS.get(key);
|
|
635
|
+
if (accountDataStr) {
|
|
636
|
+
try {
|
|
637
|
+
const parsed = JSON.parse(accountDataStr);
|
|
638
|
+
if (parsed.accountId === key)
|
|
639
|
+
return parsed;
|
|
640
|
+
return parsed; // tolerate id/key shape; resolver only needs the config
|
|
641
|
+
}
|
|
642
|
+
catch {
|
|
643
|
+
return null;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
// LOCAL DEV: the worker runs with the 'dev-unsigned' signing secret and no
|
|
647
|
+
// KV_CACHE_SERVICE_TOKEN, so the backend lookup below would bail. Mirror the
|
|
648
|
+
// dev behavior of /mockups/url — grant a permissive, fully-open account so any
|
|
649
|
+
// key resolves locally (no assetAllowlist → L2 passes; no requireSig → L3 off).
|
|
650
|
+
// Gated strictly on the dev secret, so a real prod URL_SIGNING_SECRET always
|
|
651
|
+
// takes the authenticated path below.
|
|
652
|
+
if (!env.URL_SIGNING_SECRET || env.URL_SIGNING_SECRET === "dev-unsigned") {
|
|
653
|
+
return { accountId: key, apiKeys: [], public: {} };
|
|
654
|
+
}
|
|
655
|
+
// Fallback to the backend config source (mirrors authenticate()).
|
|
656
|
+
const kvCacheBaseUrl = env.KV_CACHE_BASE_URL || "http://localhost:4000";
|
|
657
|
+
const kvCacheServiceToken = env.KV_CACHE_SERVICE_TOKEN;
|
|
658
|
+
if (!kvCacheServiceToken)
|
|
659
|
+
return null;
|
|
660
|
+
try {
|
|
661
|
+
const externalApiUrl = new URL(`${kvCacheBaseUrl.replace(/\/+$/, "")}/kv-cache/api-key`);
|
|
662
|
+
// Backend /kv-cache/api-key reads `shop` (legacy `accountId` was ignored).
|
|
663
|
+
externalApiUrl.searchParams.append("shop", key);
|
|
664
|
+
const response = await fetch(externalApiUrl.toString(), {
|
|
665
|
+
method: "GET",
|
|
666
|
+
headers: { Authorization: `Bearer ${kvCacheServiceToken}` },
|
|
667
|
+
});
|
|
668
|
+
if (!response.ok)
|
|
669
|
+
return null;
|
|
670
|
+
const raw = (await response.json());
|
|
671
|
+
if (!raw ||
|
|
672
|
+
typeof raw.accountId !== "string" ||
|
|
673
|
+
!Array.isArray(raw.apiKeys) ||
|
|
674
|
+
typeof raw.public !== "object" ||
|
|
675
|
+
raw.public === null) {
|
|
676
|
+
return null;
|
|
677
|
+
}
|
|
678
|
+
const account = {
|
|
679
|
+
accountId: raw.accountId,
|
|
680
|
+
apiKeys: Array.isArray(raw.apiKeys) ? raw.apiKeys : [],
|
|
681
|
+
public: raw.public,
|
|
682
|
+
assetAllowlist: Array.isArray(raw.assetAllowlist)
|
|
683
|
+
? raw.assetAllowlist
|
|
684
|
+
: undefined,
|
|
685
|
+
l3Secret: typeof raw.l3Secret === "string" ? raw.l3Secret : undefined,
|
|
686
|
+
requireSig: raw.requireSig === true ? true : undefined,
|
|
687
|
+
revoked: raw.revoked === true ? true : undefined,
|
|
688
|
+
};
|
|
689
|
+
// Cache for next time, keyed by the public token.
|
|
690
|
+
await env.ACCOUNTS.put(key, JSON.stringify(account));
|
|
691
|
+
return account;
|
|
692
|
+
}
|
|
693
|
+
catch {
|
|
694
|
+
return null;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
// ───────────────────────────────────────────────────────────────────────────
|
|
698
|
+
// "Blank item" affordance (the homepage's bottom-of-page blanks, but available
|
|
699
|
+
// to every shop out of the box). A reserved asset VALUE — `asset=default` (or
|
|
700
|
+
// `asset.<key>=default`) — that the resolver substitutes server-side for the
|
|
701
|
+
// transparent /_blank.png this worker serves itself (below). So a blank item
|
|
702
|
+
// needs no hosting, no allowlist entry, and no per-shop setup.
|
|
703
|
+
//
|
|
704
|
+
// Because the resolver INJECTS this asset, it is exempt from the L2 asset-origin
|
|
705
|
+
// allowlist by provenance — L2 polices developer-supplied hosts (anti-theft),
|
|
706
|
+
// and the house placeholder is not developer-supplied. The "no artwork" contract
|
|
707
|
+
// is unchanged: omitting artwork entirely still 400s; `default` is an explicit
|
|
708
|
+
// opt-in. (Asset-origin allowlist context: ADR-0076.)
|
|
709
|
+
//
|
|
710
|
+
// Per-shop branding (resolving `default` to the shop's own mark instead of the
|
|
711
|
+
// transparent blank) is a future addition — the same URL would then render
|
|
712
|
+
// branding with no caller change. Not built yet.
|
|
713
|
+
const DEFAULT_ASSET_TOKEN = "default";
|
|
714
|
+
const isDefaultToken = (v) => v === DEFAULT_ASSET_TOKEN;
|
|
715
|
+
// A 1×1 fully-transparent PNG (68 bytes), served at /_blank.png. Generated as an
|
|
716
|
+
// 8-bit RGBA PNG with a single transparent pixel; rendercenter composites it to
|
|
717
|
+
// nothing, so the placement contributes zero pixels → a bare (blank) mockup.
|
|
718
|
+
const BLANK_PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNgAAIAAAUAAen63NgAAAAASUVORK5CYII=";
|
|
719
|
+
const BLANK_PNG_PATH = "/_blank.png";
|
|
720
|
+
/** Decode a base64 string to bytes (Workers-safe; no Buffer). */
|
|
721
|
+
function base64ToBytes(b64) {
|
|
722
|
+
const bin = atob(b64);
|
|
723
|
+
const out = new Uint8Array(bin.length);
|
|
724
|
+
for (let i = 0; i < bin.length; i++)
|
|
725
|
+
out[i] = bin.charCodeAt(i);
|
|
726
|
+
return out;
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* The URL the `default` token resolves to: this worker's own transparent
|
|
730
|
+
* `/_blank.png` on the request's host (img.snowcone.app in prod, the workspace
|
|
731
|
+
* host in dev) — no separate hosting to keep in sync. (A per-shop brand override
|
|
732
|
+
* would branch here in future.)
|
|
733
|
+
*
|
|
734
|
+
* Scheme is forced to https: both prod and the local dev proxy (caddy/traefik on
|
|
735
|
+
* *.img.lvh.me) serve the resolver over https ONLY. Behind that TLS-terminating
|
|
736
|
+
* proxy the worker sees the request as http, so deriving the scheme from
|
|
737
|
+
* request.url would inject an http asset URL the renderer can't fetch.
|
|
738
|
+
*/
|
|
739
|
+
function houseAssetUrl(request) {
|
|
740
|
+
return `https://${new URL(request.url).host}${BLANK_PNG_PATH}`;
|
|
741
|
+
}
|
|
742
|
+
// L2 hostname matching + exempt-origin logic live in ./asset-allowlist
|
|
743
|
+
// (pure module) so they run under the default unit-test glob.
|
|
744
|
+
async function handlePublicResolve(request, env, productCode) {
|
|
745
|
+
// All resolver responses are uncacheable — the resolver must stay in the loop
|
|
746
|
+
// for invalidation + per-request auth/rate (ADR-0076 §7). 4xx must never be
|
|
747
|
+
// cached as the image.
|
|
748
|
+
const NO_STORE = { "Cache-Control": "no-store" };
|
|
749
|
+
// `code` is a stable machine-readable error code (the `E_*` family, ADR-0089 /
|
|
750
|
+
// canvas error house style) included alongside the human message so agents
|
|
751
|
+
// branch on the code, not the prose. Omitted for the legacy untyped 400s.
|
|
752
|
+
const errResp = (status, message, code) => new Response(JSON.stringify(code ? { error: message, code } : { error: message }), {
|
|
753
|
+
status,
|
|
754
|
+
headers: { "Content-Type": "application/json", ...NO_STORE },
|
|
755
|
+
});
|
|
756
|
+
const reqUrl = new URL(request.url);
|
|
757
|
+
const q = reqUrl.searchParams;
|
|
758
|
+
// Strict params FIRST: any query key outside the public grammar 400s loudly
|
|
759
|
+
// (naming the key + the allowed grammar) instead of being silently ignored —
|
|
760
|
+
// a hand-edited `view=<sceneId>` used to render the default scene with zero
|
|
761
|
+
// feedback. Predicate lives in @snowcone-app/mockup-url (grammar SSOT).
|
|
762
|
+
const badParams = rejectUnknownPublicParams(reqUrl);
|
|
763
|
+
if (badParams)
|
|
764
|
+
return badParams;
|
|
765
|
+
// The full grammar: bare `asset=` (default placement) OR a multi-placement
|
|
766
|
+
// design map (`asset.<key>`/`color.<key>`/`tile.<key>`/`align.<key>`) + variant
|
|
767
|
+
// option picks (`opt.<attr>`).
|
|
768
|
+
const parsed = parsePublicUrl(reqUrl);
|
|
769
|
+
const asset = q.get(PARAMS.asset);
|
|
770
|
+
const design = parsed.design ?? {};
|
|
771
|
+
const optionPicks = parsed.options ?? {};
|
|
772
|
+
const designKeys = Object.keys(design);
|
|
773
|
+
// Catalog design reference (ADR-0086): `design=<pairingId|slug>` renders a
|
|
774
|
+
// published catalog design as-is — resolver-injected components, free tier.
|
|
775
|
+
const designRef = parsed.designRef;
|
|
776
|
+
const key = q.get(PARAMS.shop);
|
|
777
|
+
const widthParam = q.get(PARAMS.width);
|
|
778
|
+
const mockupOverride = q.get(PARAMS.mockup) ?? undefined;
|
|
779
|
+
const variantOverride = q.get(PARAMS.variant) ?? undefined;
|
|
780
|
+
const placementOverride = q.get(PARAMS.placement) ?? undefined;
|
|
781
|
+
const pageParam = q.get(PARAMS.page) ?? undefined;
|
|
782
|
+
const aspectParam = q.get(PARAMS.aspect);
|
|
783
|
+
const aspect = aspectParam === "2:3" ? "2:3" : aspectParam === "16:9" ? "16:9" : undefined;
|
|
784
|
+
// Per-render background override (`bg=`): painted behind the mockup, visible
|
|
785
|
+
// only through scene transparency. Validated here (via the grammar SSOT) so a
|
|
786
|
+
// malformed color fails loudly at the edge, and required in CANONICAL form
|
|
787
|
+
// (lowercase, no '#') because the URL is the cache key — accepting spelling
|
|
788
|
+
// variants would cache the same pixels under multiple entries. When ABSENT
|
|
789
|
+
// the render server falls back to the shop's configured default
|
|
790
|
+
// (`mockup_bg_color`), else transparent; the reserved `bg=transparent` token
|
|
791
|
+
// suppresses that default for this one render (forwarded verbatim — the
|
|
792
|
+
// render server skips its shop-default fallback for it).
|
|
793
|
+
const bg = q.get(PARAMS.bg) ?? undefined;
|
|
794
|
+
if (bg !== undefined) {
|
|
795
|
+
const canonical = normalizeBgColor(bg);
|
|
796
|
+
if (canonical === null) {
|
|
797
|
+
return errResp(400, `bg= must be a 6-digit hex color (e.g. bg=f5f0ea) or bg=transparent, got "${bg}". ` +
|
|
798
|
+
"Omit it to use the shop's configured default background.");
|
|
799
|
+
}
|
|
800
|
+
if (canonical !== bg) {
|
|
801
|
+
return errResp(400, `bg= must be the canonical lowercase form without '#' — use bg=${canonical}. ` +
|
|
802
|
+
"(URLs are cache keys, so one value must always be one spelling.)");
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
if (!productCode)
|
|
806
|
+
return errResp(400, "Missing productCode in path");
|
|
807
|
+
if (!asset && designKeys.length === 0 && !designRef) {
|
|
808
|
+
return errResp(400, "Missing artwork: provide asset=, asset.<placement>=, or design=<catalog design>");
|
|
809
|
+
}
|
|
810
|
+
// Free = the design as published (ADR-0086): a catalog reference cannot be
|
|
811
|
+
// combined with developer-supplied artwork params.
|
|
812
|
+
if (designRef && (asset || designKeys.length > 0)) {
|
|
813
|
+
return errResp(400, "design= renders the catalog design as published and cannot be combined " +
|
|
814
|
+
"with asset=, asset.<placement>=, or color.<placement>= — drop those " +
|
|
815
|
+
"params, or drop design= to render your own artwork (billable)");
|
|
816
|
+
}
|
|
817
|
+
// page=N (ADR-0086 §5): syntax checks up front; the album-block semantics
|
|
818
|
+
// need the catalog doc, so they run after the product fetch below.
|
|
819
|
+
if (pageParam !== undefined && !/^[1-9][0-9]*$/.test(pageParam)) {
|
|
820
|
+
return errResp(400, "page= must be a positive integer");
|
|
821
|
+
}
|
|
822
|
+
if (pageParam !== undefined && placementOverride !== undefined) {
|
|
823
|
+
return errResp(400, "page= and placement= are mutually exclusive — page=N already selects " +
|
|
824
|
+
"the album's repeating page placement");
|
|
825
|
+
}
|
|
826
|
+
if (!key)
|
|
827
|
+
return errResp(400, "Missing required query param: shop");
|
|
828
|
+
// 1. Shop ID lookup → AccountData (404 unknown, 403 revoked).
|
|
829
|
+
const account = await loadAccountByKey(key, env);
|
|
830
|
+
if (!account)
|
|
831
|
+
return errResp(404, "Unknown shop");
|
|
832
|
+
if (account.revoked)
|
|
833
|
+
return errResp(403, "Shop revoked");
|
|
834
|
+
const accountId = account.accountId;
|
|
835
|
+
// NOTE: the L1 page-origin / domain allowlist (Origin-then-Referer check) was
|
|
836
|
+
// removed — browser privacy controls strip/spoof those headers, so it could
|
|
837
|
+
// never be enforced. Anti-theft is the asset-source allowlist (L2, below) plus
|
|
838
|
+
// signed URLs (L3). See ADR-0075/0076.
|
|
839
|
+
// The asset the reserved `default` token resolves to (the transparent
|
|
840
|
+
// /_blank.png this worker serves). Computed once; injected below.
|
|
841
|
+
const house = houseAssetUrl(request);
|
|
842
|
+
// Every DEVELOPER-supplied image URL the design references (bare asset +
|
|
843
|
+
// per-placement srcs). Reserved `default` tokens are EXCLUDED — they are
|
|
844
|
+
// platform-injected (resolved to `house`), so they bypass L2 by provenance.
|
|
845
|
+
const imageUrls = [];
|
|
846
|
+
if (asset && !isDefaultToken(asset))
|
|
847
|
+
imageUrls.push(asset);
|
|
848
|
+
for (const k of designKeys) {
|
|
849
|
+
const src = design[k].src;
|
|
850
|
+
if (src && !isDefaultToken(src))
|
|
851
|
+
imageUrls.push(src);
|
|
852
|
+
}
|
|
853
|
+
// 2b. L2 — asset-source allowlist (checked for EVERY image URL's hostname).
|
|
854
|
+
// Catalog designs (`design=`) never reach this check: their components are
|
|
855
|
+
// resolver-injected (bypass by provenance, like the `default` token), and
|
|
856
|
+
// the grammar forbids combining design= with developer asset params — so
|
|
857
|
+
// imageUrls is empty for catalog renders and no origin is ever exempted.
|
|
858
|
+
{
|
|
859
|
+
const verdict = checkAssetUrls(imageUrls, account.assetAllowlist);
|
|
860
|
+
if (!verdict.ok) {
|
|
861
|
+
return errResp(verdict.status, verdict.message);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
// 2c. L3 — required developer signature `s` over the canonical public URL.
|
|
865
|
+
if (account.requireSig) {
|
|
866
|
+
if (!account.l3Secret) {
|
|
867
|
+
// Misconfigured: requireSig on but no secret to verify against. Fail closed.
|
|
868
|
+
return errResp(403, "Signed URLs required but no L3 secret configured");
|
|
869
|
+
}
|
|
870
|
+
const provided = q.get(PARAMS.signature);
|
|
871
|
+
if (!provided)
|
|
872
|
+
return errResp(403, "Missing required signature");
|
|
873
|
+
// canonicalForSig reads the RAW query verbatim — use the original URL string.
|
|
874
|
+
const canonical = canonicalForSig(request.url);
|
|
875
|
+
const expected = await signDevSig(canonical, account.l3Secret);
|
|
876
|
+
let ok = expected.length === provided.length;
|
|
877
|
+
if (ok) {
|
|
878
|
+
let r = 0;
|
|
879
|
+
for (let i = 0; i < expected.length; i++) {
|
|
880
|
+
r |= expected.charCodeAt(i) ^ provided.charCodeAt(i);
|
|
206
881
|
}
|
|
207
|
-
|
|
208
|
-
|
|
882
|
+
ok = r === 0;
|
|
883
|
+
}
|
|
884
|
+
if (!ok)
|
|
885
|
+
return errResp(403, "Invalid signature: s");
|
|
886
|
+
}
|
|
887
|
+
// 3. Rate limit — reuse the existing per-account/IP public limiter.
|
|
888
|
+
const clientIp = request.headers.get("CF-Connecting-IP") ||
|
|
889
|
+
request.headers.get("X-Forwarded-For") ||
|
|
890
|
+
"unknown-ip";
|
|
891
|
+
// Global IP guard (same caps as authenticate()'s public path).
|
|
892
|
+
try {
|
|
893
|
+
const globalRl = env.API_RATE_LIMITER.get(env.API_RATE_LIMITER.idFromName(`global:public:${clientIp}`));
|
|
894
|
+
const perSec = await globalRl.checkRateLimit(20);
|
|
895
|
+
if (!perSec.allowed) {
|
|
896
|
+
const resp = errResp(429, "Rate limit exceeded");
|
|
897
|
+
resp.headers.set("Retry-After", String(Math.ceil((perSec.retryAfter ?? 1000) / 1000)));
|
|
898
|
+
return resp;
|
|
899
|
+
}
|
|
900
|
+
const daily = await globalRl.checkDailyRateLimit(50000);
|
|
901
|
+
if (!daily.allowed) {
|
|
902
|
+
const resp = errResp(429, "Daily rate limit exceeded");
|
|
903
|
+
if (daily.retryAfter) {
|
|
904
|
+
resp.headers.set("Retry-After", String(Math.ceil(daily.retryAfter / 1000)));
|
|
209
905
|
}
|
|
906
|
+
return resp;
|
|
210
907
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
908
|
+
}
|
|
909
|
+
catch (e) {
|
|
910
|
+
console.error(`Public resolve: global rate-limit error (fail open): ${e}`);
|
|
911
|
+
}
|
|
912
|
+
// Per-account public rate limit, if configured.
|
|
913
|
+
if (account.public?.rateLimit) {
|
|
914
|
+
try {
|
|
915
|
+
const acctRl = env.API_RATE_LIMITER.get(env.API_RATE_LIMITER.idFromName(`${accountId}:public:${clientIp}`));
|
|
916
|
+
const result = await acctRl.checkRateLimit(account.public.rateLimit);
|
|
917
|
+
if (!result.allowed) {
|
|
918
|
+
const resp = errResp(429, "Rate limit exceeded");
|
|
919
|
+
resp.headers.set("Retry-After", String(Math.ceil((result.retryAfter ?? 1000) / 1000)));
|
|
920
|
+
return resp;
|
|
222
921
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
922
|
+
}
|
|
923
|
+
catch (e) {
|
|
924
|
+
console.error(`Public resolve: account rate-limit error (fail open): ${e}`);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
// 4. Resolve catalog config (Meilisearch, KV-cached).
|
|
928
|
+
const meiliHost = env.MEILISEARCH_HOST;
|
|
929
|
+
const meiliKey = env.MEILISEARCH_API_KEY;
|
|
930
|
+
const meiliIndex = env.MEILISEARCH_INDEX;
|
|
931
|
+
const mockupBaseUrl = env.MOCKUP_BASE_URL;
|
|
932
|
+
if (!meiliHost || !meiliKey || !meiliIndex || !mockupBaseUrl) {
|
|
933
|
+
return errResp(500, "Resolver not configured");
|
|
934
|
+
}
|
|
935
|
+
const product = await fetchProduct(productCode, { host: meiliHost, apiKey: meiliKey, index: meiliIndex }, env.ACCOUNTS);
|
|
936
|
+
if (!product)
|
|
937
|
+
return errResp(404, `Product not found: ${productCode}`);
|
|
938
|
+
// 4-design. Resolve the catalog reference (ADR-0086). Membership in the
|
|
939
|
+
// designs index IS the license check — a miss is a loud 404, never a
|
|
940
|
+
// fallback to URL-mode.
|
|
941
|
+
let catalogDesign = null;
|
|
942
|
+
if (designRef) {
|
|
943
|
+
const designsIndex = env.MEILISEARCH_DESIGNS_INDEX;
|
|
944
|
+
if (!designsIndex)
|
|
945
|
+
return errResp(500, "Designs catalog not configured");
|
|
946
|
+
catalogDesign = await fetchDesign(designRef, { host: meiliHost, apiKey: meiliKey, index: designsIndex }, env.ACCOUNTS);
|
|
947
|
+
if (!catalogDesign) {
|
|
948
|
+
return errResp(404, `Design not found in catalog: ${designRef}`);
|
|
949
|
+
}
|
|
950
|
+
if (catalogDesign.productId !== productCode) {
|
|
951
|
+
return errResp(400, `Design ${designRef} belongs to product ${catalogDesign.productId} — ` +
|
|
952
|
+
`use https://img.snowcone.app/${catalogDesign.productId}?design=…`);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
// 4-page. Album page selection (ADR-0086 §5): page=N maps to the wire key
|
|
956
|
+
// `<pagePlacement>_N`, which resolves to the GEOMETRY of the repeating page
|
|
957
|
+
// placement — the catalog never enumerates page_1..page_100. Only album
|
|
958
|
+
// products accept page=; everything else fails loudly.
|
|
959
|
+
let pagePlacement = null;
|
|
960
|
+
if (pageParam !== undefined) {
|
|
961
|
+
if (!product.album) {
|
|
962
|
+
return errResp(400, `page= is only valid for album products — ${productCode} has no album block`);
|
|
963
|
+
}
|
|
964
|
+
const pageNum = Number(pageParam);
|
|
965
|
+
if (pageNum > product.album.pageExtent.max) {
|
|
966
|
+
return errResp(400, `page=${pageNum} is out of range for ${productCode} ` +
|
|
967
|
+
`(pages 1–${product.album.pageExtent.max})`);
|
|
968
|
+
}
|
|
969
|
+
pagePlacement = resolveAlbumPagePlacement(product, `${product.album.pagePlacement}_${pageNum}`);
|
|
970
|
+
if (!pagePlacement) {
|
|
971
|
+
// Catalog drift: the album block names a placement the doc no longer has.
|
|
972
|
+
return errResp(422, `Album page placement "${product.album.pagePlacement}" no longer exists: ${productCode}`);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
// 4a. Resolve the variant from option picks (both catalog shapes) + the
|
|
976
|
+
// render-only optionSelections rendercenter needs. resolveDefaults then supplies
|
|
977
|
+
// the mockup scene and a default placement (for the bare-asset case).
|
|
978
|
+
const vr = resolveVariant(product, optionPicks, variantOverride);
|
|
979
|
+
if (!vr) {
|
|
980
|
+
return errResp(422, `Product ${productCode} has no renderable combination`);
|
|
981
|
+
}
|
|
982
|
+
const scene = resolveDefaults(product, {
|
|
983
|
+
variant: vr.variantId,
|
|
984
|
+
mockupId: mockupOverride,
|
|
985
|
+
placement: placementOverride,
|
|
986
|
+
});
|
|
987
|
+
if (!scene) {
|
|
988
|
+
return errResp(422, `Product ${productCode} has no renderable combination`);
|
|
989
|
+
}
|
|
990
|
+
// page=N selects which album page feeds the scene: the resolved default
|
|
991
|
+
// placement becomes the repeating page placement's geometry.
|
|
992
|
+
if (pagePlacement)
|
|
993
|
+
scene.placement = pagePlacement;
|
|
994
|
+
// 4b. Build the design elements: one base broadcast across every placement
|
|
995
|
+
// plus per-placement overrides (ADR-0089), or a catalog design verbatim.
|
|
996
|
+
//
|
|
997
|
+
// Strict: the URL key must equal the placement's canonical catalog `key`
|
|
998
|
+
// EXACTLY — no label/slug/case fallbacks. A wrong key fails loudly with
|
|
999
|
+
// "Unknown placement" instead of being silently coerced, and this matches the
|
|
1000
|
+
// buy worker's strict `placementByKey.get(key)`, so any URL that previews is
|
|
1001
|
+
// guaranteed to also check out (no preview-works/buy-400s divergence).
|
|
1002
|
+
// Album products additionally accept the expanded page keys (`page_N` →
|
|
1003
|
+
// the repeating placement's geometry, ADR-0086); null for everything else,
|
|
1004
|
+
// so non-album products behave exactly as before.
|
|
1005
|
+
const findPlacement = (k) => product.placements.find((p) => p.key === k) ??
|
|
1006
|
+
resolveAlbumPagePlacement(product, k);
|
|
1007
|
+
const designElements = [];
|
|
1008
|
+
if (catalogDesign) {
|
|
1009
|
+
// Catalog design: render its published components verbatim. Per-placement
|
|
1010
|
+
// assets when present (keys are this product's wire keys — the doc was
|
|
1011
|
+
// built from the same catalog placements), else the bare flattened asset.
|
|
1012
|
+
if (catalogDesign.assets && Object.keys(catalogDesign.assets).length > 0) {
|
|
1013
|
+
for (const k of Object.keys(catalogDesign.assets)) {
|
|
1014
|
+
const pl = findPlacement(k);
|
|
1015
|
+
if (!pl) {
|
|
1016
|
+
// Catalog/doc drift (placement renamed since the sync) — fail loudly.
|
|
1017
|
+
return errResp(422, `Catalog design placement no longer exists: ${k}`);
|
|
229
1018
|
}
|
|
1019
|
+
designElements.push({
|
|
1020
|
+
type: "image",
|
|
1021
|
+
imageUrl: catalogDesign.assets[k],
|
|
1022
|
+
placement: pl.label,
|
|
1023
|
+
width: pl.width,
|
|
1024
|
+
height: pl.height,
|
|
1025
|
+
alignment: "center",
|
|
1026
|
+
});
|
|
230
1027
|
}
|
|
231
1028
|
}
|
|
1029
|
+
else if (catalogDesign.asset) {
|
|
1030
|
+
designElements.push({
|
|
1031
|
+
type: "image",
|
|
1032
|
+
imageUrl: catalogDesign.asset,
|
|
1033
|
+
placement: scene.placement.label,
|
|
1034
|
+
width: scene.placement.width,
|
|
1035
|
+
height: scene.placement.height,
|
|
1036
|
+
alignment: "center",
|
|
1037
|
+
});
|
|
1038
|
+
}
|
|
232
1039
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
return hexSignature;
|
|
254
|
-
}
|
|
255
|
-
export async function verifyUrl(url, signature, secretKey) {
|
|
256
|
-
const expectedSignature = await signUrl(url, secretKey);
|
|
257
|
-
// Constant-time comparison to prevent timing attacks
|
|
258
|
-
if (expectedSignature.length !== signature.length) {
|
|
259
|
-
return false;
|
|
1040
|
+
else {
|
|
1041
|
+
// ADR-0089 base+override: the scalar `asset=` SEEDS every placement (each
|
|
1042
|
+
// with ITS OWN geometry), then each `asset.<key>=` OVERRIDES the base on
|
|
1043
|
+
// that one placement. `default` blanks (house) at either scope. An unknown
|
|
1044
|
+
// override key fails loudly (E_PLACEMENT_NOT_FOUND, listing valid keys).
|
|
1045
|
+
// The base broadcast fans out across `product.placements` directly — it no
|
|
1046
|
+
// longer rides the single default-placement resolution.
|
|
1047
|
+
const assembled = assembleArtwork(product, {
|
|
1048
|
+
asset,
|
|
1049
|
+
design,
|
|
1050
|
+
house,
|
|
1051
|
+
findPlacement,
|
|
1052
|
+
});
|
|
1053
|
+
if (!assembled.ok) {
|
|
1054
|
+
return errResp(assembled.status, assembled.message, assembled.code);
|
|
1055
|
+
}
|
|
1056
|
+
designElements.push(...assembled.elements);
|
|
1057
|
+
}
|
|
1058
|
+
if (designElements.length === 0) {
|
|
1059
|
+
return errResp(400, "Missing artwork: provide asset= or asset.<placement>=");
|
|
260
1060
|
}
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
1061
|
+
const MAX_ELEMENTS = 10; // mirrors rendercenter's shared MAX_ELEMENTS
|
|
1062
|
+
if (designElements.length > MAX_ELEMENTS) {
|
|
1063
|
+
return errResp(400, `Too many placements (max ${MAX_ELEMENTS})`);
|
|
264
1064
|
}
|
|
265
|
-
|
|
1065
|
+
// 5. Build the render URL FRESH — never forward the incoming query string, so
|
|
1066
|
+
// the public `shop`/`signature` never leak onto the render URL (which carries
|
|
1067
|
+
// only the relay `seal`).
|
|
1068
|
+
let width = 1400;
|
|
1069
|
+
if (widthParam) {
|
|
1070
|
+
const parsedWidth = parseInt(widthParam, 10);
|
|
1071
|
+
if (Number.isFinite(parsedWidth) && parsedWidth > 0)
|
|
1072
|
+
width = parsedWidth;
|
|
1073
|
+
}
|
|
1074
|
+
const hasOptionSelections = Object.keys(vr.optionSelections).length > 0;
|
|
1075
|
+
const unsigned = buildMockupUrl({
|
|
1076
|
+
productId: product.id,
|
|
1077
|
+
mockupId: scene.mockupId,
|
|
1078
|
+
variantId: vr.variantId,
|
|
1079
|
+
width,
|
|
1080
|
+
...(aspect ? { aspect } : {}),
|
|
1081
|
+
...(bg ? { bg } : {}),
|
|
1082
|
+
...(hasOptionSelections ? { optionSelections: vr.optionSelections } : {}),
|
|
1083
|
+
design: designElements,
|
|
1084
|
+
}, { mockupBaseUrl, shop: accountId });
|
|
1085
|
+
// 6. Relay-sign internally (the SAME scheme rendercenter verifies — sign the
|
|
1086
|
+
// RELATIVE path+query minus seal). The developer never sees this secret.
|
|
1087
|
+
const signingSecret = env.URL_SIGNING_SECRET || "dev-unsigned";
|
|
1088
|
+
const urlObj = new URL(unsigned);
|
|
1089
|
+
// Catalog provenance (ADR-0086): rendercenter zero-bills `catalog=` renders
|
|
1090
|
+
// and records the pairingId. Trustworthy because it is under the seal — only
|
|
1091
|
+
// this resolver mints it, and only after the membership check above.
|
|
1092
|
+
if (catalogDesign) {
|
|
1093
|
+
urlObj.searchParams.append("catalog", catalogDesign.pairingId);
|
|
1094
|
+
}
|
|
1095
|
+
const sigParams = new URLSearchParams(urlObj.search);
|
|
1096
|
+
sigParams.delete("seal");
|
|
1097
|
+
const relative = `${urlObj.pathname}?${sigParams.toString()}`;
|
|
1098
|
+
const sig = await signUrl(relative, signingSecret);
|
|
1099
|
+
urlObj.searchParams.append("seal", sig);
|
|
1100
|
+
// 7. 302 to the relay-signed render URL, no-store on the REDIRECT.
|
|
1101
|
+
return new Response(null, {
|
|
1102
|
+
status: 302,
|
|
1103
|
+
headers: {
|
|
1104
|
+
Location: urlObj.toString(),
|
|
1105
|
+
...NO_STORE,
|
|
1106
|
+
},
|
|
1107
|
+
});
|
|
266
1108
|
}
|
|
267
1109
|
// Cloudflare Worker entry point
|
|
268
1110
|
export default {
|
|
269
1111
|
async fetch(request, env, ctx) {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
1112
|
+
// SECURITY: the former unauthenticated `/test-kv` debug endpoint was removed.
|
|
1113
|
+
// It dumped/enumerated/wrote the ACCOUNTS KV (account configs, key hashes,
|
|
1114
|
+
// L3 secrets) with no auth, live in production. Nothing depends on it; do
|
|
1115
|
+
// not reintroduce a KV-dumping route without auth + a non-prod gate.
|
|
1116
|
+
// Handle CORS preflight
|
|
1117
|
+
if (request.method === "OPTIONS") {
|
|
1118
|
+
return new Response(null, {
|
|
1119
|
+
headers: {
|
|
1120
|
+
"Access-Control-Allow-Origin": request.headers.get("Origin") || "*",
|
|
1121
|
+
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
1122
|
+
"Access-Control-Allow-Headers": "Content-Type, X-API-Key, X-Client-ID",
|
|
1123
|
+
// Reflected Origin → cache must vary by Origin (see CORS notes above).
|
|
1124
|
+
Vary: "Origin",
|
|
1125
|
+
},
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
const url = new URL(request.url);
|
|
1129
|
+
// Agent legibility: a tiny pointer file so agents/crawlers landing on the
|
|
1130
|
+
// render origin can find the canonical docs and how to get a Shop ID.
|
|
1131
|
+
if (request.method === "GET" && url.pathname === "/llms.txt") {
|
|
1132
|
+
const body = "Snowcone render origin (img.snowcone.app).\n" +
|
|
1133
|
+
"Docs: https://developers.snowcone.app/llms.txt\n" +
|
|
1134
|
+
"Mint a shop: POST https://api.snowcone.app/shops/sandbox\n";
|
|
1135
|
+
return addCorsHeaders(new Response(body, {
|
|
1136
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
1137
|
+
}), request);
|
|
1138
|
+
}
|
|
1139
|
+
// The transparent house placeholder the `asset=default` token resolves to
|
|
1140
|
+
// (see DEFAULT_ASSET_TOKEN). Served by this worker so the "blank item"
|
|
1141
|
+
// affordance deploys atomically with no external hosting to keep in sync.
|
|
1142
|
+
// Immutable → long cache.
|
|
1143
|
+
if (request.method === "GET" && url.pathname === BLANK_PNG_PATH) {
|
|
1144
|
+
return addCorsHeaders(new Response(base64ToBytes(BLANK_PNG_BASE64), {
|
|
1145
|
+
headers: {
|
|
1146
|
+
"Content-Type": "image/png",
|
|
1147
|
+
"Cache-Control": "public, max-age=31536000, immutable",
|
|
1148
|
+
},
|
|
1149
|
+
}), request);
|
|
1150
|
+
}
|
|
1151
|
+
// ADR-0076: the public image-CDN resolver on img.snowcone.app.
|
|
1152
|
+
// GET https://img.snowcone.app/{productCode}?asset=…&shop=…
|
|
1153
|
+
// Routed by Host (img.*) in production; in local dev (single host) we also
|
|
1154
|
+
// accept a GET to a non-reserved single-segment path carrying ?asset&shop
|
|
1155
|
+
// (or the legacy `key` alias), so the resolver is reachable without the
|
|
1156
|
+
// custom domain binding.
|
|
1157
|
+
const host = (request.headers.get("Host") || url.host || "").toLowerCase();
|
|
1158
|
+
if (looksLikeResolveRequest(request.method, host, url)) {
|
|
1159
|
+
const productCode = decodeURIComponent(url.pathname.split("/").filter(Boolean)[0]);
|
|
1160
|
+
return addCorsHeaders(await handlePublicResolve(request, env, productCode), request);
|
|
1161
|
+
}
|
|
1162
|
+
// ADR-0073 §10: resolve (productCode → mockupId/gvid/placement) + build +
|
|
1163
|
+
// sign in one call, so a BFF passes only (assetUrl, productCode).
|
|
1164
|
+
if (url.pathname === "/mockups/url" && request.method === "POST") {
|
|
1165
|
+
return addCorsHeaders(await handleMockupUrl(request, env), request);
|
|
1166
|
+
}
|
|
1167
|
+
// Parse the request URL
|
|
1168
|
+
if (url.pathname === "/sign" || url.pathname === "/verify") {
|
|
1169
|
+
// Authenticate the request
|
|
1170
|
+
const authResult = await authenticate(request, env);
|
|
1171
|
+
if (!authResult.authenticated) {
|
|
1172
|
+
const errorResponse = new Response(JSON.stringify({ error: authResult.error }), {
|
|
1173
|
+
status: authResult.error?.includes("Rate limit exceeded")
|
|
1174
|
+
? 429
|
|
1175
|
+
: 401,
|
|
1176
|
+
headers: { "Content-Type": "application/json" },
|
|
1177
|
+
});
|
|
1178
|
+
return addCorsHeaders(errorResponse, request);
|
|
274
1179
|
}
|
|
275
|
-
//
|
|
1180
|
+
// require URL_SIGNING_SECRET
|
|
276
1181
|
if (!env.URL_SIGNING_SECRET) {
|
|
277
|
-
|
|
278
|
-
return addCorsHeaders(new Response(JSON.stringify({ error: 'Internal server error' }), {
|
|
279
|
-
status: 500,
|
|
280
|
-
headers: { 'Content-Type': 'application/json' },
|
|
281
|
-
}), request);
|
|
282
|
-
}
|
|
283
|
-
if (!env.ACCOUNTS) {
|
|
284
|
-
console.error('Missing required environment variable: ACCOUNTS');
|
|
285
|
-
return addCorsHeaders(new Response(JSON.stringify({ error: 'Internal server error' }), {
|
|
1182
|
+
const errorResponse = new Response("Missing URL_SIGNING_SECRET", {
|
|
286
1183
|
status: 500,
|
|
287
|
-
headers: {
|
|
288
|
-
})
|
|
1184
|
+
headers: { "Content-Type": "application/json" },
|
|
1185
|
+
});
|
|
1186
|
+
return addCorsHeaders(errorResponse, request);
|
|
289
1187
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
1188
|
+
const secretKey = env.URL_SIGNING_SECRET;
|
|
1189
|
+
// Use the accountId that was extracted during authentication
|
|
1190
|
+
const accountId = authResult.accountId;
|
|
1191
|
+
if (url.pathname === "/sign") {
|
|
1192
|
+
// SECURITY: /sign mints the internal RELAY `seal` (URL_SIGNING_SECRET)
|
|
1193
|
+
// that rendercenter trusts — the SAME credential handlePublicResolve
|
|
1194
|
+
// produces only AFTER the L2 asset-origin allowlist and L3 requireSig
|
|
1195
|
+
// checks. Signing here does NOT re-run those checks (an authenticated
|
|
1196
|
+
// integrator is trusted to sign its own renders, like /mockups/url), so
|
|
1197
|
+
// this endpoint must never be reachable with only a PUBLIC shop id —
|
|
1198
|
+
// otherwise it is an open signing oracle that launders a disallowed
|
|
1199
|
+
// origin/host past L2/L3. Require a real API-key credential: with the
|
|
1200
|
+
// x-api-key header present, authenticate() above took Method 1 (hash +
|
|
1201
|
+
// 'mockups' scope, validated against THIS shop) — the rate-limited
|
|
1202
|
+
// public fallback (Method 2) can no longer satisfy /sign.
|
|
1203
|
+
//
|
|
1204
|
+
// Gated to production the same way handleMockupUrl/loadAccountByKey are:
|
|
1205
|
+
// local dev runs with the 'dev-unsigned' secret (seals are worthless
|
|
1206
|
+
// off-box) and has no provisioned API keys, so the dev flow is unchanged.
|
|
1207
|
+
const isDevUnsigned = !env.URL_SIGNING_SECRET || env.URL_SIGNING_SECRET === "dev-unsigned";
|
|
1208
|
+
if (!isDevUnsigned && !request.headers.get("x-api-key")) {
|
|
1209
|
+
const errorResponse = new Response(JSON.stringify({
|
|
1210
|
+
error: "The /sign endpoint requires an API key with the 'mockups' scope (X-API-Key header). A public shop id is not sufficient.",
|
|
1211
|
+
}), {
|
|
1212
|
+
status: 401,
|
|
1213
|
+
headers: { "Content-Type": "application/json" },
|
|
1214
|
+
});
|
|
1215
|
+
return addCorsHeaders(errorResponse, request);
|
|
1216
|
+
}
|
|
1217
|
+
// Get the URL to sign from the query parameter
|
|
1218
|
+
let urlToSign = url.searchParams.get("url");
|
|
1219
|
+
let isRelativeUrl = false;
|
|
1220
|
+
if (!urlToSign) {
|
|
1221
|
+
const errorResponse = new Response("Missing URL parameter", {
|
|
1222
|
+
status: 400,
|
|
1223
|
+
});
|
|
1224
|
+
return addCorsHeaders(errorResponse, request);
|
|
1225
|
+
}
|
|
1226
|
+
// Check if this is a relative URL (save this information for later)
|
|
1227
|
+
if (urlToSign.startsWith("/")) {
|
|
1228
|
+
isRelativeUrl = true;
|
|
1229
|
+
}
|
|
1230
|
+
// Parse and validate the URL
|
|
1231
|
+
let urlObj;
|
|
1232
|
+
try {
|
|
1233
|
+
// If it's a relative URL, add a dummy base for parsing purposes only
|
|
1234
|
+
if (isRelativeUrl) {
|
|
1235
|
+
console.log("📝 Using temporary base URL for parsing a relative URL");
|
|
1236
|
+
const baseUrl = "https://example.com";
|
|
1237
|
+
urlObj = new URL(urlToSign, baseUrl);
|
|
302
1238
|
}
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
return addCorsHeaders(new Response(JSON.stringify({ error: 'Missing url parameter' }), {
|
|
306
|
-
status: 400,
|
|
307
|
-
headers: { 'Content-Type': 'application/json' },
|
|
308
|
-
}), request);
|
|
1239
|
+
else {
|
|
1240
|
+
urlObj = new URL(urlToSign);
|
|
309
1241
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
1242
|
+
}
|
|
1243
|
+
catch (error) {
|
|
1244
|
+
console.error(`❌ Invalid URL format: ${urlToSign}`, error);
|
|
1245
|
+
const errorResponse = new Response(JSON.stringify({
|
|
1246
|
+
error: "Invalid URL format. The URL must be a valid absolute URL (with protocol) or a valid relative URL starting with /",
|
|
315
1247
|
}), {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
},
|
|
1248
|
+
status: 400,
|
|
1249
|
+
headers: { "Content-Type": "application/json" },
|
|
319
1250
|
});
|
|
320
|
-
return addCorsHeaders(
|
|
1251
|
+
return addCorsHeaders(errorResponse, request);
|
|
321
1252
|
}
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
1253
|
+
// Check if the URL should include accountId
|
|
1254
|
+
// We don't need to add it again - it should already be in the URL (validated by authenticate)
|
|
1255
|
+
// This is now just a check in case we want to override the behavior in the future
|
|
1256
|
+
const shouldIncludeAccountId = url.searchParams.get("includeAccountId") !== "false";
|
|
1257
|
+
// We don't need to add accountId since it should already be in the URL
|
|
1258
|
+
// But we'll log a message if it doesn't match what we expect
|
|
1259
|
+
const urlShop = urlObj.searchParams.get("shop") ??
|
|
1260
|
+
urlObj.searchParams.get("accountId");
|
|
1261
|
+
if (shouldIncludeAccountId && urlShop !== accountId) {
|
|
1262
|
+
console.log(`⚠️ Warning: shop in URL (${urlShop}) doesn't match authenticated shop (${accountId})`);
|
|
1263
|
+
}
|
|
1264
|
+
// Get the final URL string to sign (preserving the relative format if original was relative)
|
|
1265
|
+
let finalUrlToSign = isRelativeUrl
|
|
1266
|
+
? urlObj.pathname + urlObj.search
|
|
1267
|
+
: urlObj.toString();
|
|
1268
|
+
const signature = await signUrl(finalUrlToSign, secretKey);
|
|
1269
|
+
// Construct the signed URL by adding the signature parameter
|
|
1270
|
+
urlObj.searchParams.append("seal", signature);
|
|
1271
|
+
// Get the final URL with signature (preserving the relative format if original was relative)
|
|
1272
|
+
const urlWithSignature = isRelativeUrl
|
|
1273
|
+
? urlObj.pathname + urlObj.search
|
|
1274
|
+
: urlObj.toString();
|
|
1275
|
+
const response = new Response(JSON.stringify({
|
|
1276
|
+
signature,
|
|
1277
|
+
urlWithSignature,
|
|
1278
|
+
}), {
|
|
1279
|
+
headers: {
|
|
1280
|
+
"Content-Type": "application/json",
|
|
1281
|
+
},
|
|
1282
|
+
});
|
|
1283
|
+
return addCorsHeaders(response, request);
|
|
1284
|
+
}
|
|
1285
|
+
else if (url.pathname === "/verify") {
|
|
1286
|
+
// Get URL and signature from query parameters
|
|
1287
|
+
let urlToVerify = url.searchParams.get("url");
|
|
1288
|
+
const signature = url.searchParams.get("signature");
|
|
1289
|
+
let isRelativeUrl = false;
|
|
1290
|
+
if (!urlToVerify || !signature) {
|
|
1291
|
+
const errorResponse = new Response("Missing URL or signature parameter", {
|
|
1292
|
+
status: 400,
|
|
334
1293
|
});
|
|
335
|
-
return addCorsHeaders(
|
|
1294
|
+
return addCorsHeaders(errorResponse, request);
|
|
336
1295
|
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
1296
|
+
// Check if this is a relative URL (save this information for later)
|
|
1297
|
+
if (urlToVerify.startsWith("/")) {
|
|
1298
|
+
isRelativeUrl = true;
|
|
1299
|
+
}
|
|
1300
|
+
// Parse and validate the URL
|
|
1301
|
+
let urlObj;
|
|
1302
|
+
try {
|
|
1303
|
+
// If it's a relative URL, add a dummy base for parsing purposes only
|
|
1304
|
+
if (isRelativeUrl) {
|
|
1305
|
+
console.log("📝 Using temporary base URL for parsing a relative URL");
|
|
1306
|
+
const baseUrl = "https://example.com";
|
|
1307
|
+
urlObj = new URL(urlToVerify, baseUrl);
|
|
1308
|
+
}
|
|
1309
|
+
else {
|
|
1310
|
+
urlObj = new URL(urlToVerify);
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
catch (error) {
|
|
1314
|
+
console.error(`❌ Invalid URL format: ${urlToVerify}`, error);
|
|
1315
|
+
const errorResponse = new Response(JSON.stringify({
|
|
1316
|
+
error: "Invalid URL format. The URL must be a valid absolute URL (with protocol) or a valid relative URL starting with /",
|
|
345
1317
|
}), {
|
|
346
|
-
|
|
1318
|
+
status: 400,
|
|
1319
|
+
headers: { "Content-Type": "application/json" },
|
|
347
1320
|
});
|
|
348
|
-
return addCorsHeaders(
|
|
1321
|
+
return addCorsHeaders(errorResponse, request);
|
|
1322
|
+
}
|
|
1323
|
+
// The shop id should already be in the URL — this is a consistency check.
|
|
1324
|
+
const urlShopVerify = urlObj.searchParams.get("shop") ??
|
|
1325
|
+
urlObj.searchParams.get("accountId");
|
|
1326
|
+
if (urlShopVerify !== accountId) {
|
|
1327
|
+
console.log(`⚠️ Warning: shop in URL (${urlShopVerify}) doesn't match authenticated shop (${accountId})`);
|
|
349
1328
|
}
|
|
1329
|
+
// Get the final URL string to verify (preserving the relative format if original was relative)
|
|
1330
|
+
let finalUrlToVerify = isRelativeUrl
|
|
1331
|
+
? urlObj.pathname + urlObj.search
|
|
1332
|
+
: urlObj.toString();
|
|
1333
|
+
const isValid = await verifyUrl(finalUrlToVerify, signature, secretKey);
|
|
1334
|
+
const response = new Response(JSON.stringify({ valid: isValid }), {
|
|
1335
|
+
headers: {
|
|
1336
|
+
"Content-Type": "application/json",
|
|
1337
|
+
},
|
|
1338
|
+
});
|
|
1339
|
+
return addCorsHeaders(response, request);
|
|
350
1340
|
}
|
|
351
1341
|
}
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
}
|
|
363
|
-
}
|
|
1342
|
+
// Default route
|
|
1343
|
+
const response = new Response(JSON.stringify({
|
|
1344
|
+
message: "Mockup Resolver API",
|
|
1345
|
+
endpoints: [
|
|
1346
|
+
"/sign?url=<url-to-sign>",
|
|
1347
|
+
"/verify?url=<url-to-verify>&signature=<signature>",
|
|
1348
|
+
],
|
|
1349
|
+
}), {
|
|
1350
|
+
headers: {
|
|
1351
|
+
"Content-Type": "application/json",
|
|
1352
|
+
},
|
|
1353
|
+
});
|
|
1354
|
+
return addCorsHeaders(response, request);
|
|
364
1355
|
},
|
|
365
1356
|
};
|
|
366
1357
|
// Example wrangler.toml configuration:
|
|
367
1358
|
/*
|
|
368
|
-
name = "
|
|
1359
|
+
name = "mockup-resolver"
|
|
369
1360
|
...
|
|
370
1361
|
[vars]
|
|
371
1362
|
SECRET_KEY = "your-secret-key"
|
|
@@ -373,25 +1364,30 @@ SECRET_KEY = "your-secret-key"
|
|
|
373
1364
|
[[kv_namespaces]]
|
|
374
1365
|
binding = "ACCOUNTS"
|
|
375
1366
|
id = "your-kv-namespace-id-for-accounts"
|
|
1367
|
+
|
|
1368
|
+
[[durable_objects.bindings]]
|
|
1369
|
+
name = "API_RATE_LIMITER"
|
|
1370
|
+
class_name = "RateLimiter"
|
|
1371
|
+
|
|
1372
|
+
[[migrations]]
|
|
1373
|
+
tag = "v1"
|
|
1374
|
+
new_classes = ["RateLimiter"]
|
|
376
1375
|
*/
|
|
377
1376
|
// Example account data structure:
|
|
378
1377
|
/*
|
|
379
1378
|
{
|
|
380
|
-
"
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
"
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
}
|
|
1379
|
+
"accountId": "yFP34rCxcF",
|
|
1380
|
+
"apiKeys": [
|
|
1381
|
+
{
|
|
1382
|
+
"hash": "4241259ed7f5k4a69edp67579fd1c49634e1a32cf4e7ef43m41e25b83d7823d4",
|
|
1383
|
+
"prefix": "pq3b1q1H",
|
|
1384
|
+
"rateLimit": 60
|
|
1385
|
+
}
|
|
1386
|
+
],
|
|
1387
|
+
"public": {
|
|
1388
|
+
"rateLimit": 100
|
|
1389
|
+
},
|
|
1390
|
+
"assetAllowlist": ["cdn.example.com", "*.example.org"],
|
|
1391
|
+
"requireSig": false
|
|
396
1392
|
}
|
|
397
1393
|
*/
|