@snowcone-app/mockup-resolver 1.0.6 → 1.0.8

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.
Files changed (3) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/package.json +2 -2
  3. package/src/index.ts +103 -13
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @snowcone-app/mockup-resolver
2
2
 
3
+ ## 1.0.8
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`a1a9095`](https://github.com/snowcone-app/snowcone-monorepo/commit/a1a909566506c63bcdc322fbd8de10b51043b9e0)]:
8
+ - @snowcone-app/mockup-url@0.3.4
9
+
10
+ ## 1.0.7
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [[`e82940a`](https://github.com/snowcone-app/snowcone-monorepo/commit/e82940a934cb00d870160d46b75a8b17b95a1c55)]:
15
+ - @snowcone-app/mockup-url@0.3.3
16
+
3
17
  ## 1.0.6
4
18
 
5
19
  ### Patch Changes
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@snowcone-app/mockup-resolver",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
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.2"
9
+ "@snowcone-app/mockup-url": "0.3.4"
10
10
  },
11
11
  "devDependencies": {
12
12
  "@cloudflare/workers-types": "^4.20250303.0",
package/src/index.ts CHANGED
@@ -408,6 +408,29 @@ async function hashApiKey(apiKey: string): Promise<string> {
408
408
  * invisible at a 20rps limit — while burst latency drops to ~0. A DENIED
409
409
  * verdict is cached for its window too, so hammering stays cheap.
410
410
  */
411
+ /**
412
+ * In-isolate TTL caches for the resolver's two remaining lookups (ADR-0096
413
+ * "rest of rsv to ~0"): account config (KV, changes rarely — revocation and
414
+ * limit edits lag <=60s on public renders) and product data (catalog fetch —
415
+ * edits lag <=30s; the render boxes' own product cache has explicit
416
+ * invalidation, this only delays the resolver's view). Both flatten the
417
+ * per-isolate warm path to ~0ms; a cold isolate still pays first-fetch.
418
+ */
419
+ const ACCT_CACHE_TTL_MS = 60_000;
420
+ const PRODUCT_CACHE_TTL_MS = 30_000;
421
+ const ttlCache = new Map<string, { until: number; value: unknown }>();
422
+
423
+ function ttlGet<T>(key: string): T | undefined {
424
+ const e = ttlCache.get(key);
425
+ if (!e || Date.now() >= e.until) return undefined;
426
+ return e.value as T;
427
+ }
428
+
429
+ function ttlSet(key: string, value: unknown, ttlMs: number): void {
430
+ if (ttlCache.size > 5_000) ttlCache.clear();
431
+ ttlCache.set(key, { until: Date.now() + ttlMs, value });
432
+ }
433
+
411
434
  const publicLimitBurstCache = new Map<
412
435
  string,
413
436
  { windowEnd: number; used: number; allowed: boolean }
@@ -415,16 +438,16 @@ const publicLimitBurstCache = new Map<
415
438
 
416
439
  /** grant = allowed locally (skip the DO await); deny = cached denial;
417
440
  * miss = no fresh window — do the authoritative DO round-trip. */
418
- function burstAllow(key: string, rps: number): "grant" | "deny" | "miss" {
441
+ function burstAllow(key: string, rps: number): "grant" | "deny" | "cold" | "exhausted" {
419
442
  const entry = publicLimitBurstCache.get(key);
420
443
  const nowMs = Date.now();
421
- if (!entry || nowMs >= entry.windowEnd) return "miss";
444
+ if (!entry || nowMs >= entry.windowEnd) return "cold";
422
445
  if (!entry.allowed) return "deny";
423
446
  if (entry.used < rps) {
424
447
  entry.used++;
425
448
  return "grant";
426
449
  }
427
- return "miss";
450
+ return "exhausted";
428
451
  }
429
452
 
430
453
  function burstRecord(key: string, allowed: boolean): void {
@@ -788,9 +811,23 @@ async function authenticate(
788
811
  globalVerdict = { allowed: false, scope: "second", retryAfter: 1000 } as Awaited<
789
812
  ReturnType<RateLimiterStub["checkPublicLimits"]>
790
813
  >;
814
+ } else if (globalGrant === "cold") {
815
+ // Kevin-approved optimistic first-sight (2026-08-15): a COLD per-IP DO
816
+ // wake measured 565ms synchronously on a visitor's FIRST render — an
817
+ // absurd tax for an abuse-guard. Allow immediately, settle the
818
+ // authoritative verdict in the background; a denial lands in the
819
+ // window cache and bites from the next request. Slack = one request
820
+ // per IP per window per isolate; daily caps still accrue in the DO.
821
+ globalVerdict = { allowed: true } as Awaited<
822
+ ReturnType<RateLimiterStub["checkPublicLimits"]>
823
+ >;
824
+ void globalRateLimiter
825
+ .checkPublicLimits(GLOBAL_IP_RATE_LIMIT_RPS, GLOBAL_DAILY_IP_RATE_LIMIT)
826
+ .then((v) => burstRecord(globalBurstKey, v.allowed))
827
+ .catch(() => {});
791
828
  } 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).
829
+ // Local window EXHAUSTED — the rate limit may genuinely be engaging;
830
+ // this is the one case that must await the authoritative verdict.
794
831
  globalVerdict = await globalRateLimiter.checkPublicLimits(
795
832
  GLOBAL_IP_RATE_LIMIT_RPS,
796
833
  GLOBAL_DAILY_IP_RATE_LIMIT
@@ -863,6 +900,13 @@ async function authenticate(
863
900
  result = { allowed: false, retryAfter: 1000 } as Awaited<
864
901
  ReturnType<RateLimiterStub["checkRateLimit"]>
865
902
  >;
903
+ } else if (acctGrant === "cold") {
904
+ // Same optimistic first-sight as the global limiter (cold DO wake).
905
+ result = { allowed: true } as Awaited<ReturnType<RateLimiterStub["checkRateLimit"]>>;
906
+ void rateLimiter
907
+ .checkRateLimit(accountData.public.rateLimit)
908
+ .then((v) => burstRecord(acctBurstKey, v.allowed))
909
+ .catch(() => {});
866
910
  } else {
867
911
  // Call the method directly on the Durable Object via RPC
868
912
  result = await rateLimiter.checkRateLimit(accountData.public.rateLimit);
@@ -1321,7 +1365,11 @@ async function handlePublicResolve(
1321
1365
 
1322
1366
  // 1. Shop ID lookup → AccountData (404 unknown, 403 revoked).
1323
1367
  const tAcct = Date.now();
1324
- const account = await loadAccountByKey(key, env);
1368
+ let account = ttlGet<AccountData | null>(`acct:${key}`);
1369
+ if (account === undefined) {
1370
+ account = await loadAccountByKey(key, env);
1371
+ ttlSet(`acct:${key}`, account, ACCT_CACHE_TTL_MS);
1372
+ }
1325
1373
  const acctMs = Date.now() - tAcct;
1326
1374
  if (!account) return errResp(404, "Unknown shop");
1327
1375
  if (account.revoked) return errResp(403, "Shop revoked");
@@ -1404,11 +1452,17 @@ async function handlePublicResolve(
1404
1452
  }
1405
1453
 
1406
1454
  const tLimits = Date.now();
1407
- const productPromise = fetchProduct(
1408
- productCode,
1409
- { host: meiliHost, apiKey: meiliKey, index: meiliIndex },
1410
- env.ACCOUNTS
1411
- );
1455
+ const cachedProduct = ttlGet<Awaited<ReturnType<typeof fetchProduct>>>(`prod:${productCode}`);
1456
+ const productPromise = cachedProduct !== undefined
1457
+ ? Promise.resolve(cachedProduct)
1458
+ : fetchProduct(
1459
+ productCode,
1460
+ { host: meiliHost, apiKey: meiliKey, index: meiliIndex },
1461
+ env.ACCOUNTS
1462
+ ).then((p) => {
1463
+ ttlSet(`prod:${productCode}`, p, PRODUCT_CACHE_TTL_MS);
1464
+ return p;
1465
+ });
1412
1466
  // Detached guard: when a limit blocks below, this promise is never awaited —
1413
1467
  // without a no-op catch, a fetch failure there would surface as an unhandled
1414
1468
  // rejection. The real `await productPromise` further down still rethrows.
@@ -1421,10 +1475,29 @@ async function handlePublicResolve(
1421
1475
  };
1422
1476
  const globalCheck: Promise<LimitVerdict> = (async () => {
1423
1477
  try {
1478
+ // Kevin-approved optimistic limiting (2026-08-15): a cold per-IP DO
1479
+ // wake measured 565ms synchronously on a visitor's first render, and
1480
+ // even warm the RPC costs ~60ms per request. Same-window repeats and
1481
+ // first-sights allow immediately with the authoritative verdict
1482
+ // settling in the background (denials cached, bite from the next
1483
+ // request); only an EXHAUSTED local window — the limit genuinely
1484
+ // engaging — awaits the DO.
1485
+ const burstKey = `g:${clientIp}`;
1486
+ const grant = burstAllow(burstKey, 20);
1487
+ if (grant === "deny") return { allowed: false, scope: "second", retryAfter: 1000 };
1424
1488
  const globalRl = env.API_RATE_LIMITER.get(
1425
1489
  env.API_RATE_LIMITER.idFromName(`global:public:${clientIp}`)
1426
1490
  );
1427
- return await globalRl.checkPublicLimits(20, 50000);
1491
+ if (grant === "grant" || grant === "cold") {
1492
+ void globalRl
1493
+ .checkPublicLimits(20, 50000)
1494
+ .then((v) => burstRecord(burstKey, v.allowed))
1495
+ .catch(() => {});
1496
+ return { allowed: true };
1497
+ }
1498
+ const v = await globalRl.checkPublicLimits(20, 50000);
1499
+ burstRecord(burstKey, v.allowed);
1500
+ return v;
1428
1501
  } catch (e) {
1429
1502
  console.error(`Public resolve: global rate-limit error (fail open): ${e}`);
1430
1503
  return { allowed: true };
@@ -1433,10 +1506,27 @@ async function handlePublicResolve(
1433
1506
  const acctCheck: Promise<LimitVerdict> = (async () => {
1434
1507
  if (!account.public?.rateLimit) return { allowed: true };
1435
1508
  try {
1509
+ // Same optimistic pattern as the global check above.
1510
+ const burstKey = `${accountId}:${clientIp}`;
1511
+ const acctRps = Math.max(
1512
+ 1,
1513
+ Number((account.public.rateLimit as { requestsPerSecond?: number }).requestsPerSecond) || 5
1514
+ );
1515
+ const grant = burstAllow(burstKey, acctRps);
1516
+ if (grant === "deny") return { allowed: false, retryAfter: 1000 };
1436
1517
  const acctRl = env.API_RATE_LIMITER.get(
1437
1518
  env.API_RATE_LIMITER.idFromName(`${accountId}:public:${clientIp}`)
1438
1519
  );
1439
- return await acctRl.checkRateLimit(account.public.rateLimit);
1520
+ if (grant === "grant" || grant === "cold") {
1521
+ void acctRl
1522
+ .checkRateLimit(account.public.rateLimit)
1523
+ .then((v) => burstRecord(burstKey, v.allowed))
1524
+ .catch(() => {});
1525
+ return { allowed: true };
1526
+ }
1527
+ const v = await acctRl.checkRateLimit(account.public.rateLimit);
1528
+ burstRecord(burstKey, v.allowed);
1529
+ return v;
1440
1530
  } catch (e) {
1441
1531
  console.error(`Public resolve: account rate-limit error (fail open): ${e}`);
1442
1532
  return { allowed: true };