@snowcone-app/mockup-resolver 1.0.4 → 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 +7 -0
- package/dist/index.js +1278 -282
- package/package.json +2 -2
- package/src/asset-allowlist.ts +14 -68
- package/src/index.ts +304 -118
- package/src/public-params.ts +9 -1
- package/wrangler.jsonc +5 -0
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@snowcone-app/mockup-resolver",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.5",
|
|
4
4
|
"description": "URL signing and verification Cloudflare Worker",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"author": "",
|
|
7
7
|
"license": "ISC",
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@snowcone-app/mockup-url": "0.3.
|
|
9
|
+
"@snowcone-app/mockup-url": "0.3.1"
|
|
10
10
|
},
|
|
11
11
|
"devDependencies": {
|
|
12
12
|
"@cloudflare/workers-types": "^4.20250303.0",
|
package/src/asset-allowlist.ts
CHANGED
|
@@ -1,70 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* L2 asset-source allowlist (ADR-0076 security ladder)
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* L2 asset-source allowlist (ADR-0076 security ladder).
|
|
3
|
+
*
|
|
4
|
+
* The implementation moved to `@snowcone-app/mockup-url/asset-allowlist` so
|
|
5
|
+
* the backend publish/listing guard enforces the EXACT same origin-matching
|
|
6
|
+
* as this worker (QA finding 0013: a published design whose asset origin
|
|
7
|
+
* fails this check renders a blank catalog card; the guard refuses it at
|
|
8
|
+
* publish time instead). This module stays as the worker-local entry point —
|
|
9
|
+
* src/index.ts and the unit tests import from here.
|
|
5
10
|
*/
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
if (char === "*") {
|
|
13
|
-
regexString += ".*?"; // Non-greedy match for any characters
|
|
14
|
-
} else if (/[.+\[\]?^${}()|\-\\]/.test(char)) {
|
|
15
|
-
// Corrected regex for special characters
|
|
16
|
-
regexString += "\\" + char; // Escape them
|
|
17
|
-
} else {
|
|
18
|
-
regexString += char;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
regexString += "$";
|
|
22
|
-
return new RegExp(regexString, "i"); // Added 'i' flag for case-insensitive matching
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/** Check a hostname against a glob allowlist (reuses globToRegExp). */
|
|
26
|
-
export function isHostAllowed(host: string, allowlist: string[]): boolean {
|
|
27
|
-
if (allowlist.length === 0) return true; // unset = any
|
|
28
|
-
for (const pattern of allowlist) {
|
|
29
|
-
if (pattern === "*") return true;
|
|
30
|
-
try {
|
|
31
|
-
if (globToRegExp(pattern).test(host)) return true;
|
|
32
|
-
} catch {
|
|
33
|
-
// skip malformed pattern
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
return false;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export type AssetAllowlistVerdict =
|
|
40
|
-
| { ok: true }
|
|
41
|
-
| { ok: false; status: 400 | 403; message: string };
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Run the L2 check over every developer-supplied image URL. No origin is ever
|
|
45
|
-
* exempt: catalog designs render by reference (`design=`, ADR-0086) with
|
|
46
|
-
* resolver-injected components, so they never pass through this check — the
|
|
47
|
-
* old EXEMPT_ASSET_ORIGINS escape hatch is gone.
|
|
48
|
-
*/
|
|
49
|
-
export function checkAssetUrls(
|
|
50
|
-
imageUrls: string[],
|
|
51
|
-
allowlist: string[] | undefined
|
|
52
|
-
): AssetAllowlistVerdict {
|
|
53
|
-
if (!allowlist || allowlist.length === 0) return { ok: true };
|
|
54
|
-
for (const imageUrl of imageUrls) {
|
|
55
|
-
let assetHost: string;
|
|
56
|
-
try {
|
|
57
|
-
assetHost = new URL(imageUrl).hostname;
|
|
58
|
-
} catch {
|
|
59
|
-
return { ok: false, status: 400, message: "Invalid asset URL" };
|
|
60
|
-
}
|
|
61
|
-
if (!isHostAllowed(assetHost, allowlist)) {
|
|
62
|
-
return {
|
|
63
|
-
ok: false,
|
|
64
|
-
status: 403,
|
|
65
|
-
message: "Asset source not allowed for this shop",
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return { ok: true };
|
|
70
|
-
}
|
|
11
|
+
export {
|
|
12
|
+
globToRegExp,
|
|
13
|
+
isHostAllowed,
|
|
14
|
+
checkAssetUrls,
|
|
15
|
+
type AssetAllowlistVerdict,
|
|
16
|
+
} from "@snowcone-app/mockup-url/asset-allowlist";
|
package/src/index.ts
CHANGED
|
@@ -31,11 +31,25 @@ interface RateLimiterStub extends DurableObjectStub {
|
|
|
31
31
|
currentCount?: number;
|
|
32
32
|
dailyLimit?: number;
|
|
33
33
|
}>;
|
|
34
|
+
checkPublicLimits(
|
|
35
|
+
requestsPerSecond: number,
|
|
36
|
+
dailyMaxRequests: number
|
|
37
|
+
): Promise<{
|
|
38
|
+
allowed: boolean;
|
|
39
|
+
scope?: "second" | "day";
|
|
40
|
+
retryAfter?: number;
|
|
41
|
+
currentCount?: number;
|
|
42
|
+
dailyLimit?: number;
|
|
43
|
+
}>;
|
|
34
44
|
}
|
|
35
45
|
|
|
36
46
|
// Interface for environment bindings
|
|
37
47
|
interface Env {
|
|
38
48
|
URL_SIGNING_SECRET: string;
|
|
49
|
+
/** ADR-0096: service binding to the render edge (mockup-edge-cache) — the
|
|
50
|
+
* resolver calls it in-process after sealing and streams bytes back.
|
|
51
|
+
* One client leg; the 302 hop is retired. */
|
|
52
|
+
RENDER_EDGE: Fetcher;
|
|
39
53
|
ACCOUNTS: KVNamespace; // Single KV store for all account data
|
|
40
54
|
API_RATE_LIMITER: {
|
|
41
55
|
idFromName(name: string): DurableObjectId;
|
|
@@ -298,6 +312,40 @@ export class RateLimiter extends DurableObject {
|
|
|
298
312
|
dailyLimit: dailyMaxRequests,
|
|
299
313
|
};
|
|
300
314
|
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Per-second + daily check in ONE DO round-trip. The resolver used to
|
|
318
|
+
* await checkRateLimit() then checkDailyRateLimit() back-to-back — two
|
|
319
|
+
* cross-region RPCs to this same object on every public request. Same
|
|
320
|
+
* semantics as the sequential pair (per-second slot is consumed even
|
|
321
|
+
* when the daily check then blocks, matching the old call order).
|
|
322
|
+
*/
|
|
323
|
+
async checkPublicLimits(
|
|
324
|
+
requestsPerSecond: number,
|
|
325
|
+
dailyMaxRequests: number
|
|
326
|
+
): Promise<{
|
|
327
|
+
allowed: boolean;
|
|
328
|
+
scope?: "second" | "day";
|
|
329
|
+
retryAfter?: number;
|
|
330
|
+
currentCount?: number;
|
|
331
|
+
dailyLimit?: number;
|
|
332
|
+
}> {
|
|
333
|
+
const perSec = await this.checkRateLimit(requestsPerSecond);
|
|
334
|
+
if (!perSec.allowed) {
|
|
335
|
+
return { allowed: false, scope: "second", retryAfter: perSec.retryAfter };
|
|
336
|
+
}
|
|
337
|
+
const daily = await this.checkDailyRateLimit(dailyMaxRequests);
|
|
338
|
+
if (!daily.allowed) {
|
|
339
|
+
return {
|
|
340
|
+
allowed: false,
|
|
341
|
+
scope: "day",
|
|
342
|
+
retryAfter: daily.retryAfter,
|
|
343
|
+
currentCount: daily.currentCount,
|
|
344
|
+
dailyLimit: daily.dailyLimit,
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
return { allowed: true };
|
|
348
|
+
}
|
|
301
349
|
}
|
|
302
350
|
|
|
303
351
|
// Helper function to add CORS headers to a response
|
|
@@ -348,6 +396,42 @@ async function hashApiKey(apiKey: string): Promise<string> {
|
|
|
348
396
|
}
|
|
349
397
|
|
|
350
398
|
// Authentication middleware
|
|
399
|
+
/**
|
|
400
|
+
* Per-isolate burst absorber for the public rate-limit DO (ADR-0096).
|
|
401
|
+
*
|
|
402
|
+
* A Durable Object is single-threaded per key, so N parallel renders from
|
|
403
|
+
* one IP serialize N RPCs (~100ms each — measured as the lab's ~600ms
|
|
404
|
+
* "queued" at 5-way concurrency). After one ALLOWED verdict we grant up to
|
|
405
|
+
* the per-second limit locally for the rest of that 1s window and fire the
|
|
406
|
+
* DO check asynchronously (fire-and-forget: its side effect is the counter
|
|
407
|
+
* increment). Enforcement slack is bounded by one window per isolate —
|
|
408
|
+
* invisible at a 20rps limit — while burst latency drops to ~0. A DENIED
|
|
409
|
+
* verdict is cached for its window too, so hammering stays cheap.
|
|
410
|
+
*/
|
|
411
|
+
const publicLimitBurstCache = new Map<
|
|
412
|
+
string,
|
|
413
|
+
{ windowEnd: number; used: number; allowed: boolean }
|
|
414
|
+
>();
|
|
415
|
+
|
|
416
|
+
/** grant = allowed locally (skip the DO await); deny = cached denial;
|
|
417
|
+
* miss = no fresh window — do the authoritative DO round-trip. */
|
|
418
|
+
function burstAllow(key: string, rps: number): "grant" | "deny" | "miss" {
|
|
419
|
+
const entry = publicLimitBurstCache.get(key);
|
|
420
|
+
const nowMs = Date.now();
|
|
421
|
+
if (!entry || nowMs >= entry.windowEnd) return "miss";
|
|
422
|
+
if (!entry.allowed) return "deny";
|
|
423
|
+
if (entry.used < rps) {
|
|
424
|
+
entry.used++;
|
|
425
|
+
return "grant";
|
|
426
|
+
}
|
|
427
|
+
return "miss";
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function burstRecord(key: string, allowed: boolean): void {
|
|
431
|
+
if (publicLimitBurstCache.size > 10_000) publicLimitBurstCache.clear();
|
|
432
|
+
publicLimitBurstCache.set(key, { windowEnd: Date.now() + 1000, used: 1, allowed });
|
|
433
|
+
}
|
|
434
|
+
|
|
351
435
|
async function authenticate(
|
|
352
436
|
request: Request,
|
|
353
437
|
env: Env
|
|
@@ -685,37 +769,53 @@ async function authenticate(
|
|
|
685
769
|
);
|
|
686
770
|
const globalRateLimiter = env.API_RATE_LIMITER.get(globalRateLimiterId);
|
|
687
771
|
|
|
688
|
-
//
|
|
689
|
-
|
|
690
|
-
|
|
772
|
+
// Burst absorber: same-window repeats from this isolate skip the
|
|
773
|
+
// serialized DO round-trip (see publicLimitBurstCache doc). Grants do
|
|
774
|
+
// NOT return early — the account-specific limit below still applies.
|
|
775
|
+
const globalBurstKey = `g:${clientIp}`;
|
|
776
|
+
const globalGrant = burstAllow(globalBurstKey, GLOBAL_IP_RATE_LIMIT_RPS);
|
|
777
|
+
let globalVerdict: Awaited<ReturnType<RateLimiterStub["checkPublicLimits"]>>;
|
|
778
|
+
if (globalGrant === "grant") {
|
|
779
|
+
// Record the hit in the DO without waiting on it — the RPC's side
|
|
780
|
+
// effect is the per-second/daily counter increment.
|
|
781
|
+
void globalRateLimiter
|
|
782
|
+
.checkPublicLimits(GLOBAL_IP_RATE_LIMIT_RPS, GLOBAL_DAILY_IP_RATE_LIMIT)
|
|
783
|
+
.catch(() => {});
|
|
784
|
+
globalVerdict = { allowed: true } as Awaited<
|
|
785
|
+
ReturnType<RateLimiterStub["checkPublicLimits"]>
|
|
786
|
+
>;
|
|
787
|
+
} else if (globalGrant === "deny") {
|
|
788
|
+
globalVerdict = { allowed: false, scope: "second", retryAfter: 1000 } as Awaited<
|
|
789
|
+
ReturnType<RateLimiterStub["checkPublicLimits"]>
|
|
790
|
+
>;
|
|
791
|
+
} else {
|
|
792
|
+
// Per-second + daily in ONE DO round-trip (was two sequential RPCs to
|
|
793
|
+
// the same object — pure added latency on every public request).
|
|
794
|
+
globalVerdict = await globalRateLimiter.checkPublicLimits(
|
|
795
|
+
GLOBAL_IP_RATE_LIMIT_RPS,
|
|
796
|
+
GLOBAL_DAILY_IP_RATE_LIMIT
|
|
797
|
+
);
|
|
798
|
+
burstRecord(globalBurstKey, globalVerdict.allowed);
|
|
799
|
+
}
|
|
691
800
|
|
|
692
|
-
if (!
|
|
801
|
+
if (!globalVerdict.allowed && globalVerdict.scope === "second") {
|
|
693
802
|
console.log(
|
|
694
803
|
`❌ Global IP per-second rate limit exceeded for IP: ${clientIp}`
|
|
695
804
|
);
|
|
696
805
|
return {
|
|
697
806
|
authenticated: false,
|
|
698
807
|
error: `Global per-second rate limit exceeded. Try again in ${Math.ceil(
|
|
699
|
-
|
|
808
|
+
globalVerdict.retryAfter! / 1000
|
|
700
809
|
)} seconds`,
|
|
701
810
|
};
|
|
702
811
|
}
|
|
703
|
-
|
|
704
|
-
`✅ Global IP per-second rate limit check passed for IP: ${clientIp}`
|
|
705
|
-
);
|
|
706
|
-
|
|
707
|
-
// Check global daily IP rate limit
|
|
708
|
-
const dailyRateLimitResult = await globalRateLimiter.checkDailyRateLimit(
|
|
709
|
-
GLOBAL_DAILY_IP_RATE_LIMIT
|
|
710
|
-
);
|
|
711
|
-
|
|
712
|
-
if (!dailyRateLimitResult.allowed) {
|
|
812
|
+
if (!globalVerdict.allowed) {
|
|
713
813
|
console.log(
|
|
714
|
-
`❌ Global daily IP rate limit exceeded for IP: ${clientIp}. Count: ${
|
|
814
|
+
`❌ Global daily IP rate limit exceeded for IP: ${clientIp}. Count: ${globalVerdict.currentCount}/${globalVerdict.dailyLimit}`
|
|
715
815
|
);
|
|
716
816
|
let retryMessage = "Global daily rate limit exceeded.";
|
|
717
|
-
if (
|
|
718
|
-
const totalSeconds = Math.floor(
|
|
817
|
+
if (globalVerdict.retryAfter) {
|
|
818
|
+
const totalSeconds = Math.floor(globalVerdict.retryAfter / 1000);
|
|
719
819
|
const hours = Math.floor(totalSeconds / 3600);
|
|
720
820
|
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
721
821
|
retryMessage += ` Try again in approximately ${hours}h ${minutes}m.`;
|
|
@@ -726,7 +826,7 @@ async function authenticate(
|
|
|
726
826
|
};
|
|
727
827
|
}
|
|
728
828
|
console.log(
|
|
729
|
-
`✅ Global
|
|
829
|
+
`✅ Global IP rate limit checks passed for IP: ${clientIp}`
|
|
730
830
|
);
|
|
731
831
|
} catch (error) {
|
|
732
832
|
console.error(
|
|
@@ -746,10 +846,28 @@ async function authenticate(
|
|
|
746
846
|
);
|
|
747
847
|
const rateLimiter = env.API_RATE_LIMITER.get(rateLimiterId);
|
|
748
848
|
|
|
749
|
-
//
|
|
750
|
-
|
|
751
|
-
|
|
849
|
+
// Same burst absorber as the global limiter: the account DO is the
|
|
850
|
+
// SECOND serialized RPC on this path — under N-way one-IP bursts the
|
|
851
|
+
// two together were the lab's ~600ms "queued".
|
|
852
|
+
const acctBurstKey = `${accountId}:${clientIp}`;
|
|
853
|
+
const acctRps = Math.max(
|
|
854
|
+
1,
|
|
855
|
+
Number((accountData.public.rateLimit as { requestsPerSecond?: number }).requestsPerSecond) || 5
|
|
752
856
|
);
|
|
857
|
+
const acctGrant = burstAllow(acctBurstKey, acctRps);
|
|
858
|
+
let result: Awaited<ReturnType<RateLimiterStub["checkRateLimit"]>>;
|
|
859
|
+
if (acctGrant === "grant") {
|
|
860
|
+
void rateLimiter.checkRateLimit(accountData.public.rateLimit).catch(() => {});
|
|
861
|
+
result = { allowed: true } as Awaited<ReturnType<RateLimiterStub["checkRateLimit"]>>;
|
|
862
|
+
} else if (acctGrant === "deny") {
|
|
863
|
+
result = { allowed: false, retryAfter: 1000 } as Awaited<
|
|
864
|
+
ReturnType<RateLimiterStub["checkRateLimit"]>
|
|
865
|
+
>;
|
|
866
|
+
} else {
|
|
867
|
+
// Call the method directly on the Durable Object via RPC
|
|
868
|
+
result = await rateLimiter.checkRateLimit(accountData.public.rateLimit);
|
|
869
|
+
burstRecord(acctBurstKey, result.allowed);
|
|
870
|
+
}
|
|
753
871
|
|
|
754
872
|
if (!result.allowed) {
|
|
755
873
|
console.log(`❌ Rate limit exceeded for IP: ${clientIp}`);
|
|
@@ -1105,6 +1223,7 @@ async function handlePublicResolve(
|
|
|
1105
1223
|
}
|
|
1106
1224
|
);
|
|
1107
1225
|
|
|
1226
|
+
const t0 = Date.now(); // Server-Timing base — emitted on the success 302
|
|
1108
1227
|
const reqUrl = new URL(request.url);
|
|
1109
1228
|
const q = reqUrl.searchParams;
|
|
1110
1229
|
|
|
@@ -1195,7 +1314,9 @@ async function handlePublicResolve(
|
|
|
1195
1314
|
if (!key) return errResp(400, "Missing required query param: shop");
|
|
1196
1315
|
|
|
1197
1316
|
// 1. Shop ID lookup → AccountData (404 unknown, 403 revoked).
|
|
1317
|
+
const tAcct = Date.now();
|
|
1198
1318
|
const account = await loadAccountByKey(key, env);
|
|
1319
|
+
const acctMs = Date.now() - tAcct;
|
|
1199
1320
|
if (!account) return errResp(404, "Unknown shop");
|
|
1200
1321
|
if (account.revoked) return errResp(403, "Shop revoked");
|
|
1201
1322
|
|
|
@@ -1254,60 +1375,20 @@ async function handlePublicResolve(
|
|
|
1254
1375
|
if (!ok) return errResp(403, "Invalid signature: s");
|
|
1255
1376
|
}
|
|
1256
1377
|
|
|
1257
|
-
// 3. Rate
|
|
1378
|
+
// 3+4. Rate limits and product fetch, OVERLAPPED. Each limiter DO lives in
|
|
1379
|
+
// exactly one location, so awaiting them serially stacked up to three
|
|
1380
|
+
// cross-region round-trips ahead of the redirect (~200ms warm, plus
|
|
1381
|
+
// hibernation wake when cold — the docs-click latency). Now the global
|
|
1382
|
+
// per-second + daily checks share ONE RPC (checkPublicLimits), the
|
|
1383
|
+
// per-account limiter runs in parallel with it, and the read-only product
|
|
1384
|
+
// fetch starts concurrently so its latency hides behind the DO hop.
|
|
1385
|
+
// Enforcement is unchanged: every limit verdict is awaited before any
|
|
1386
|
+
// response is built; when a limit blocks, the product result is discarded.
|
|
1258
1387
|
const clientIp =
|
|
1259
1388
|
request.headers.get("CF-Connecting-IP") ||
|
|
1260
1389
|
request.headers.get("X-Forwarded-For") ||
|
|
1261
1390
|
"unknown-ip";
|
|
1262
|
-
// Global IP guard (same caps as authenticate()'s public path).
|
|
1263
|
-
try {
|
|
1264
|
-
const globalRl = env.API_RATE_LIMITER.get(
|
|
1265
|
-
env.API_RATE_LIMITER.idFromName(`global:public:${clientIp}`)
|
|
1266
|
-
);
|
|
1267
|
-
const perSec = await globalRl.checkRateLimit(20);
|
|
1268
|
-
if (!perSec.allowed) {
|
|
1269
|
-
const resp = errResp(429, "Rate limit exceeded");
|
|
1270
|
-
resp.headers.set(
|
|
1271
|
-
"Retry-After",
|
|
1272
|
-
String(Math.ceil((perSec.retryAfter ?? 1000) / 1000))
|
|
1273
|
-
);
|
|
1274
|
-
return resp;
|
|
1275
|
-
}
|
|
1276
|
-
const daily = await globalRl.checkDailyRateLimit(50000);
|
|
1277
|
-
if (!daily.allowed) {
|
|
1278
|
-
const resp = errResp(429, "Daily rate limit exceeded");
|
|
1279
|
-
if (daily.retryAfter) {
|
|
1280
|
-
resp.headers.set(
|
|
1281
|
-
"Retry-After",
|
|
1282
|
-
String(Math.ceil(daily.retryAfter / 1000))
|
|
1283
|
-
);
|
|
1284
|
-
}
|
|
1285
|
-
return resp;
|
|
1286
|
-
}
|
|
1287
|
-
} catch (e) {
|
|
1288
|
-
console.error(`Public resolve: global rate-limit error (fail open): ${e}`);
|
|
1289
|
-
}
|
|
1290
|
-
// Per-account public rate limit, if configured.
|
|
1291
|
-
if (account.public?.rateLimit) {
|
|
1292
|
-
try {
|
|
1293
|
-
const acctRl = env.API_RATE_LIMITER.get(
|
|
1294
|
-
env.API_RATE_LIMITER.idFromName(`${accountId}:public:${clientIp}`)
|
|
1295
|
-
);
|
|
1296
|
-
const result = await acctRl.checkRateLimit(account.public.rateLimit);
|
|
1297
|
-
if (!result.allowed) {
|
|
1298
|
-
const resp = errResp(429, "Rate limit exceeded");
|
|
1299
|
-
resp.headers.set(
|
|
1300
|
-
"Retry-After",
|
|
1301
|
-
String(Math.ceil((result.retryAfter ?? 1000) / 1000))
|
|
1302
|
-
);
|
|
1303
|
-
return resp;
|
|
1304
|
-
}
|
|
1305
|
-
} catch (e) {
|
|
1306
|
-
console.error(`Public resolve: account rate-limit error (fail open): ${e}`);
|
|
1307
|
-
}
|
|
1308
|
-
}
|
|
1309
1391
|
|
|
1310
|
-
// 4. Resolve catalog config (Meilisearch, KV-cached).
|
|
1311
1392
|
const meiliHost = env.MEILISEARCH_HOST;
|
|
1312
1393
|
const meiliKey = env.MEILISEARCH_API_KEY;
|
|
1313
1394
|
const meiliIndex = env.MEILISEARCH_INDEX;
|
|
@@ -1315,12 +1396,79 @@ async function handlePublicResolve(
|
|
|
1315
1396
|
if (!meiliHost || !meiliKey || !meiliIndex || !mockupBaseUrl) {
|
|
1316
1397
|
return errResp(500, "Resolver not configured");
|
|
1317
1398
|
}
|
|
1318
|
-
|
|
1399
|
+
|
|
1400
|
+
const tLimits = Date.now();
|
|
1401
|
+
const productPromise = fetchProduct(
|
|
1319
1402
|
productCode,
|
|
1320
1403
|
{ host: meiliHost, apiKey: meiliKey, index: meiliIndex },
|
|
1321
1404
|
env.ACCOUNTS
|
|
1322
1405
|
);
|
|
1406
|
+
// Detached guard: when a limit blocks below, this promise is never awaited —
|
|
1407
|
+
// without a no-op catch, a fetch failure there would surface as an unhandled
|
|
1408
|
+
// rejection. The real `await productPromise` further down still rethrows.
|
|
1409
|
+
productPromise.catch(() => {});
|
|
1410
|
+
|
|
1411
|
+
type LimitVerdict = {
|
|
1412
|
+
allowed: boolean;
|
|
1413
|
+
scope?: "second" | "day";
|
|
1414
|
+
retryAfter?: number;
|
|
1415
|
+
};
|
|
1416
|
+
const globalCheck: Promise<LimitVerdict> = (async () => {
|
|
1417
|
+
try {
|
|
1418
|
+
const globalRl = env.API_RATE_LIMITER.get(
|
|
1419
|
+
env.API_RATE_LIMITER.idFromName(`global:public:${clientIp}`)
|
|
1420
|
+
);
|
|
1421
|
+
return await globalRl.checkPublicLimits(20, 50000);
|
|
1422
|
+
} catch (e) {
|
|
1423
|
+
console.error(`Public resolve: global rate-limit error (fail open): ${e}`);
|
|
1424
|
+
return { allowed: true };
|
|
1425
|
+
}
|
|
1426
|
+
})();
|
|
1427
|
+
const acctCheck: Promise<LimitVerdict> = (async () => {
|
|
1428
|
+
if (!account.public?.rateLimit) return { allowed: true };
|
|
1429
|
+
try {
|
|
1430
|
+
const acctRl = env.API_RATE_LIMITER.get(
|
|
1431
|
+
env.API_RATE_LIMITER.idFromName(`${accountId}:public:${clientIp}`)
|
|
1432
|
+
);
|
|
1433
|
+
return await acctRl.checkRateLimit(account.public.rateLimit);
|
|
1434
|
+
} catch (e) {
|
|
1435
|
+
console.error(`Public resolve: account rate-limit error (fail open): ${e}`);
|
|
1436
|
+
return { allowed: true };
|
|
1437
|
+
}
|
|
1438
|
+
})();
|
|
1439
|
+
const [globalVerdict, acctVerdict] = await Promise.all([
|
|
1440
|
+
globalCheck,
|
|
1441
|
+
acctCheck,
|
|
1442
|
+
]);
|
|
1443
|
+
if (!globalVerdict.allowed) {
|
|
1444
|
+
const resp = errResp(
|
|
1445
|
+
429,
|
|
1446
|
+
globalVerdict.scope === "day"
|
|
1447
|
+
? "Daily rate limit exceeded"
|
|
1448
|
+
: "Rate limit exceeded"
|
|
1449
|
+
);
|
|
1450
|
+
if (globalVerdict.retryAfter) {
|
|
1451
|
+
resp.headers.set(
|
|
1452
|
+
"Retry-After",
|
|
1453
|
+
String(Math.ceil(globalVerdict.retryAfter / 1000))
|
|
1454
|
+
);
|
|
1455
|
+
}
|
|
1456
|
+
return resp;
|
|
1457
|
+
}
|
|
1458
|
+
if (!acctVerdict.allowed) {
|
|
1459
|
+
const resp = errResp(429, "Rate limit exceeded");
|
|
1460
|
+
resp.headers.set(
|
|
1461
|
+
"Retry-After",
|
|
1462
|
+
String(Math.ceil((acctVerdict.retryAfter ?? 1000) / 1000))
|
|
1463
|
+
);
|
|
1464
|
+
return resp;
|
|
1465
|
+
}
|
|
1466
|
+
const limitsMs = Date.now() - tLimits;
|
|
1467
|
+
|
|
1468
|
+
const tProduct = Date.now();
|
|
1469
|
+
const product = await productPromise;
|
|
1323
1470
|
if (!product) return errResp(404, `Product not found: ${productCode}`);
|
|
1471
|
+
const productMs = Date.now() - tProduct;
|
|
1324
1472
|
|
|
1325
1473
|
// 4-design. Resolve the catalog reference (ADR-0086). Membership in the
|
|
1326
1474
|
// designs index IS the license check — a miss is a loud 404, never a
|
|
@@ -1501,64 +1649,71 @@ async function handlePublicResolve(
|
|
|
1501
1649
|
if (catalogDesign) {
|
|
1502
1650
|
urlObj.searchParams.append("catalog", catalogDesign.pairingId);
|
|
1503
1651
|
}
|
|
1652
|
+
// Operator debug passthrough (ADR-0096): with the 302 retired, the client
|
|
1653
|
+
// never learns the sealed URL, so the lab's full-waterfall replay re-fetches
|
|
1654
|
+
// the PUBLIC url with debug=<RENDER_DEBUG_SECRET>. Forward it onto the
|
|
1655
|
+
// sealed URL — INSIDE the signature (appended before signing), so seal
|
|
1656
|
+
// verification still holds — and the render edge/box gate it exactly as
|
|
1657
|
+
// before (wrong value = no stages, edge debug-branch bypasses R2).
|
|
1658
|
+
const debugParam = q.get("debug");
|
|
1659
|
+
if (debugParam) {
|
|
1660
|
+
urlObj.searchParams.append("debug", debugParam);
|
|
1661
|
+
}
|
|
1504
1662
|
const sigParams = new URLSearchParams(urlObj.search);
|
|
1505
1663
|
sigParams.delete("seal");
|
|
1506
1664
|
const relative = `${urlObj.pathname}?${sigParams.toString()}`;
|
|
1507
1665
|
const sig = await signUrl(relative, signingSecret);
|
|
1508
1666
|
urlObj.searchParams.append("seal", sig);
|
|
1509
1667
|
|
|
1510
|
-
// 7.
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1668
|
+
// 7. Single-leg render (ADR-0096, retired the 302): call the render edge
|
|
1669
|
+
// over the service binding with the sealed URL and stream its bytes back.
|
|
1670
|
+
// Worker-to-worker on Cloudflare's backbone — no second client RTT, no
|
|
1671
|
+
// second TLS handshake, no redirect processing. The edge still verifies
|
|
1672
|
+
// the seal, DMCA deny-set and cache exactly as if the browser had fetched
|
|
1673
|
+
// the sealed URL itself.
|
|
1674
|
+
//
|
|
1675
|
+
// Cache semantics: the OLD 302 was `private, max-age=300` so a browser
|
|
1676
|
+
// re-resolved (revocation / key rotation / catalog edits) within 5
|
|
1677
|
+
// minutes, while the sealed CDN response stayed immutable. The single-leg
|
|
1678
|
+
// response answers on the PUBLIC url, so it must keep the resolver-layer
|
|
1679
|
+
// semantics — override the edge's immutable header with the redirect-era
|
|
1680
|
+
// policy. rsv_* Server-Timing entries expose the resolver's own stages
|
|
1681
|
+
// next to the edge/box entries (acct = KV/backend account load, limits =
|
|
1682
|
+
// rate-limit verdict, product = catalog fetch).
|
|
1683
|
+
// rsv_total = the resolver's OWN work only (auth, limits, product, seal),
|
|
1684
|
+
// captured BEFORE the edge call — the edge stamps edge_total itself, and
|
|
1685
|
+
// overlapping totals make waterfalls unreadable (browser wait then reads:
|
|
1686
|
+
// transit + rsv_total + edge_total, no envelope arithmetic needed).
|
|
1687
|
+
const resolverMs = Date.now() - t0;
|
|
1688
|
+
const edgeRes = await env.RENDER_EDGE.fetch(
|
|
1689
|
+
new Request(urlObj.toString(), {
|
|
1690
|
+
method: "GET",
|
|
1691
|
+
headers: request.headers,
|
|
1692
|
+
})
|
|
1693
|
+
);
|
|
1694
|
+
const headers = new Headers(edgeRes.headers);
|
|
1695
|
+
headers.set("Cache-Control", edgeRes.ok ? "private, max-age=300" : "no-store");
|
|
1696
|
+
headers.set("Access-Control-Allow-Origin", "*");
|
|
1697
|
+
headers.set("Timing-Allow-Origin", "*");
|
|
1698
|
+
headers.append(
|
|
1699
|
+
"Server-Timing",
|
|
1700
|
+
`rsv_acct;dur=${acctMs}, rsv_limits;dur=${limitsMs}, ` +
|
|
1701
|
+
`rsv_product;dur=${productMs}, rsv_total;dur=${resolverMs}`
|
|
1702
|
+
);
|
|
1703
|
+
return new Response(edgeRes.body, {
|
|
1704
|
+
status: edgeRes.status,
|
|
1705
|
+
statusText: edgeRes.statusText,
|
|
1706
|
+
headers,
|
|
1517
1707
|
});
|
|
1518
1708
|
}
|
|
1519
1709
|
|
|
1520
1710
|
// Cloudflare Worker entry point
|
|
1521
1711
|
export default {
|
|
1522
1712
|
async fetch(request: Request, env: Env, ctx: any): Promise<Response> {
|
|
1523
|
-
//
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
// Try to write a test key
|
|
1528
|
-
await env.ACCOUNTS.put("test-key", "test-value");
|
|
1529
|
-
|
|
1530
|
-
// Try to read all keys
|
|
1531
|
-
const keys = await env.ACCOUNTS.list();
|
|
1532
|
-
|
|
1533
|
-
// Try to read our test key
|
|
1534
|
-
const testValue = await env.ACCOUNTS.get("test-key");
|
|
1535
|
-
|
|
1536
|
-
// Try to read account123
|
|
1537
|
-
const account123 = await env.ACCOUNTS.get("account123");
|
|
1538
|
-
|
|
1539
|
-
return new Response(
|
|
1540
|
-
JSON.stringify({
|
|
1541
|
-
testWrite: "success",
|
|
1542
|
-
testRead: testValue,
|
|
1543
|
-
keys: keys,
|
|
1544
|
-
account123: account123,
|
|
1545
|
-
}),
|
|
1546
|
-
{
|
|
1547
|
-
headers: { "Content-Type": "application/json" },
|
|
1548
|
-
}
|
|
1549
|
-
);
|
|
1550
|
-
} catch (error: any) {
|
|
1551
|
-
return new Response(
|
|
1552
|
-
JSON.stringify({
|
|
1553
|
-
error: `KV test failed: ${error.message || String(error)}`,
|
|
1554
|
-
}),
|
|
1555
|
-
{
|
|
1556
|
-
status: 500,
|
|
1557
|
-
headers: { "Content-Type": "application/json" },
|
|
1558
|
-
}
|
|
1559
|
-
);
|
|
1560
|
-
}
|
|
1561
|
-
}
|
|
1713
|
+
// SECURITY: the former unauthenticated `/test-kv` debug endpoint was removed.
|
|
1714
|
+
// It dumped/enumerated/wrote the ACCOUNTS KV (account configs, key hashes,
|
|
1715
|
+
// L3 secrets) with no auth, live in production. Nothing depends on it; do
|
|
1716
|
+
// not reintroduce a KV-dumping route without auth + a non-prod gate.
|
|
1562
1717
|
|
|
1563
1718
|
// Handle CORS preflight
|
|
1564
1719
|
if (request.method === "OPTIONS") {
|
|
@@ -1662,6 +1817,37 @@ export default {
|
|
|
1662
1817
|
const accountId = authResult.accountId!;
|
|
1663
1818
|
|
|
1664
1819
|
if (url.pathname === "/sign") {
|
|
1820
|
+
// SECURITY: /sign mints the internal RELAY `seal` (URL_SIGNING_SECRET)
|
|
1821
|
+
// that rendercenter trusts — the SAME credential handlePublicResolve
|
|
1822
|
+
// produces only AFTER the L2 asset-origin allowlist and L3 requireSig
|
|
1823
|
+
// checks. Signing here does NOT re-run those checks (an authenticated
|
|
1824
|
+
// integrator is trusted to sign its own renders, like /mockups/url), so
|
|
1825
|
+
// this endpoint must never be reachable with only a PUBLIC shop id —
|
|
1826
|
+
// otherwise it is an open signing oracle that launders a disallowed
|
|
1827
|
+
// origin/host past L2/L3. Require a real API-key credential: with the
|
|
1828
|
+
// x-api-key header present, authenticate() above took Method 1 (hash +
|
|
1829
|
+
// 'mockups' scope, validated against THIS shop) — the rate-limited
|
|
1830
|
+
// public fallback (Method 2) can no longer satisfy /sign.
|
|
1831
|
+
//
|
|
1832
|
+
// Gated to production the same way handleMockupUrl/loadAccountByKey are:
|
|
1833
|
+
// local dev runs with the 'dev-unsigned' secret (seals are worthless
|
|
1834
|
+
// off-box) and has no provisioned API keys, so the dev flow is unchanged.
|
|
1835
|
+
const isDevUnsigned =
|
|
1836
|
+
!env.URL_SIGNING_SECRET || env.URL_SIGNING_SECRET === "dev-unsigned";
|
|
1837
|
+
if (!isDevUnsigned && !request.headers.get("x-api-key")) {
|
|
1838
|
+
const errorResponse = new Response(
|
|
1839
|
+
JSON.stringify({
|
|
1840
|
+
error:
|
|
1841
|
+
"The /sign endpoint requires an API key with the 'mockups' scope (X-API-Key header). A public shop id is not sufficient.",
|
|
1842
|
+
}),
|
|
1843
|
+
{
|
|
1844
|
+
status: 401,
|
|
1845
|
+
headers: { "Content-Type": "application/json" },
|
|
1846
|
+
}
|
|
1847
|
+
);
|
|
1848
|
+
return addCorsHeaders(errorResponse, request);
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1665
1851
|
// Get the URL to sign from the query parameter
|
|
1666
1852
|
let urlToSign = url.searchParams.get("url");
|
|
1667
1853
|
let isRelativeUrl = false;
|
package/src/public-params.ts
CHANGED
|
@@ -20,7 +20,15 @@ import {
|
|
|
20
20
|
* (4 different `view=` values → 4 identical images). Pre-launch, fail loudly.
|
|
21
21
|
*/
|
|
22
22
|
export function rejectUnknownPublicParams(url: URL): Response | null {
|
|
23
|
-
const unknown = unknownPublicParams(url.searchParams)
|
|
23
|
+
const unknown = unknownPublicParams(url.searchParams).filter(
|
|
24
|
+
// Operator debug passthrough (ADR-0096): `debug=<RENDER_DEBUG_SECRET>`
|
|
25
|
+
// is transport, not public grammar — with the 302 retired, waterfall
|
|
26
|
+
// replays re-fetch the PUBLIC url, so the resolver must accept the
|
|
27
|
+
// param (it forwards it under the seal; the render box gates its
|
|
28
|
+
// value). Deliberately NOT added to mockup-url's PARAMS: it is an
|
|
29
|
+
// operator surface, not part of the developer contract.
|
|
30
|
+
(p) => p !== "debug",
|
|
31
|
+
);
|
|
24
32
|
if (unknown.length === 0) return null;
|
|
25
33
|
return new Response(
|
|
26
34
|
JSON.stringify({ error: unknownPublicParamsMessage(unknown) }),
|
package/wrangler.jsonc
CHANGED
|
@@ -43,6 +43,11 @@
|
|
|
43
43
|
// against, read with the same public search key.
|
|
44
44
|
"MEILISEARCH_DESIGNS_INDEX": "snowcone-designs"
|
|
45
45
|
},
|
|
46
|
+
"services": [
|
|
47
|
+
// ADR-0096: single-leg renders — after sealing, the resolver calls the
|
|
48
|
+
// render edge in-process and streams bytes back (the 302 hop is retired).
|
|
49
|
+
{ "binding": "RENDER_EDGE", "service": "mockup-edge-cache-production" }
|
|
50
|
+
],
|
|
46
51
|
"kv_namespaces": [
|
|
47
52
|
{
|
|
48
53
|
"binding": "ACCOUNTS",
|