Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

security(irl): give the location reads their own rate-limit budget, fail closed

nirholasa926d7ae0f54
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 59e7819cc..8968d1585 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -1134,6 +1134,18 @@ export const limits = {
// still stops a scripted flood. Page-load-critical clusters additionally get
// their own dedicated buckets below so one surface can never starve another.
publicIp: (ip) => getLimiter('public:ip', { limit: 240, window: '1 m', local: true }).limit(ip),
+ // /irl coordinate reads (pins nearby, drops nearby, world-lines nearby). These
+ // are the only public reads that reveal WHERE another user placed something, so
+ // their ceiling is a privacy budget, not a flood guard, and it must not drift
+ // with the generic read bucket: when publicIp was raised 60 -> 240 for unrelated
+ // page-load fan-out, the /irl grid-sweep cost quietly dropped 4x (the H7 threat
+ // model still documented 60). A dedicated bucket pins the number to the surface
+ // it protects. 60/min against a legit viewer's ~6/min (a 10s nearby poll) leaves
+ // 10x headroom, and no page fans out to more than one of these at a time.
+ // local: an in-memory bucket never throws on a Redis outage, which is what lets
+ // the callers fail CLOSED on it without inventing an availability risk.
+ // See docs/irl/THREAT-MODEL.md.
+ irlNearbyIp: (ip) => getLimiter('irl:nearby:ip', { limit: 60, window: '1 m', local: true }).limit(ip),
// Agent profile reads (networth, patronage, achievements, reputation, tiers).
// One profile view fans out to 7-8 of these; isolate them so opening a few
// profiles can't drain the budget shared with markets/home/oracle surfaces.
@@ -1585,6 +1597,34 @@ export const limits = {
bnbRegisterIp: (ip) => getLimiter('bnb:register:ip', { limit: 10, window: '10 m', critical: true }).limit(ip),
};
+// ── Fail-closed limiter call for privacy-boundary reads (H7) ─────────────────
+// Most call sites fail OPEN when a limiter throws: the request is bounded by
+// something else downstream (a DB cap, an ownership check), so a limiter outage
+// should not deny legitimate traffic. A read that returns someone else's LOCATION
+// has no such downstream bound, so its degradation path is the opposite: if the
+// limiter cannot decide, deny with a retryable `rate_limiter_unavailable` verdict
+// rather than open an unmetered scrape window. Shared by the three /irl coordinate
+// reads (pins, drops, world-lines nearby) so the guarantee is one implementation
+// instead of three drifting copies. See docs/irl/THREAT-MODEL.md.
+//
+// `name` ties the warning to a bucket; the cooldown keeps an outage that hits every
+// request from flooding the logs with the same line.
+const _failClosedWarnedAt = new Map();
+const FAIL_CLOSED_WARN_COOLDOWN_MS = 60_000;
+export async function limitFailClosedRead(name, fn, ...args) {
+ try {
+ return await fn(...args);
+ } catch (err) {
+ const last = _failClosedWarnedAt.get(name) || 0;
+ const now = Date.now();
+ if (now - last >= FAIL_CLOSED_WARN_COOLDOWN_MS) {
+ _failClosedWarnedAt.set(name, now);
+ console.warn(`[rate-limit] read limiter "${name}" failed, failing CLOSED (deny):`, err?.message || err);
+ }
+ return { success: false, reason: 'rate_limiter_unavailable', reset: Date.now() + 60_000 };
+ }
+}
+
// Trust only proxy headers that Vercel itself sets and signs. Naively reading
// X-Forwarded-For (or X-Real-IP, which clients can also supply directly) lets
// callers bypass per-IP rate limits by rotating the claimed address.
diff --git a/api/irl/drops.js b/api/irl/drops.js
index 74ec7cf06..18cf321fc 100644
--- a/api/irl/drops.js
+++ b/api/irl/drops.js
@@ -25,7 +25,7 @@ import {
} from '@solana/spl-token';
import { cors, json, wrap, error, rateLimited, readJson } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
+import { limits, clientIp, limitFailClosedRead } from '../_lib/rate-limit.js';
import { getSessionUser } from '../_lib/auth.js';
import { readDeviceToken } from '../_lib/irl-auth.js';
import { verifyFixToken, fixEnforced } from '../_lib/irl-presence.js';
@@ -81,7 +81,12 @@ export default wrap(async (req, res) => {
// ── reads ───────────────────────────────────────────────────────────────
if (req.method === 'GET') {
- const rl = await limits.publicIp(clientIp(req)).catch(() => ({ success: true }));
+ // Every drops read either returns a coordinate or is the caller's own data, so
+ // the limiter FAILS CLOSED here (H7): a blind limiter on a location read has
+ // nothing bounding it downstream, and the backing buckets are in-memory
+ // `local` limiters that never touch Redis, so failing closed costs no real
+ // availability. See docs/irl/THREAT-MODEL.md.
+ const rl = await limitFailClosedRead('publicIp', limits.publicIp, clientIp(req));
if (!rl.success) return rateLimited(res, rl);
if (id) {
@@ -119,6 +124,12 @@ export default wrap(async (req, res) => {
if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
return error(res, 400, 'bad_request', 'lat and lng are required');
}
+ // Same dedicated coordinate-read budget as the pins nearby feed: this is a
+ // discovery read over other people's placements, so it draws on the /irl
+ // location bucket (60/min/IP) rather than only the generic public ceiling.
+ const nearbyRl = await limitFailClosedRead('irlNearbyIp', limits.irlNearbyIp, clientIp(req));
+ if (!nearbyRl.success) return rateLimited(res, nearbyRl);
+
// Same presence gate as the pins nearby read: you only see drops where you
// stand. Enforced only when proof-of-presence is configured (prod).
if (fixEnforced()) {
diff --git a/api/irl/pins.js b/api/irl/pins.js
index ac5da57b9..686dee36a 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -18,7 +18,7 @@
import { cors, json, wrap, rateLimited } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
+import { limits, clientIp, limitFailClosedRead } from '../_lib/rate-limit.js';
import { WORD_BLACKLIST } from '../../src/profanity.js';
import { guardianConfig, assess, decide } from '../_lib/granite-guardian.js';
import { encodeGeohash } from '../_lib/geohash.js';
@@ -271,31 +271,6 @@ async function limitOrFailOpen(name, fn, ...args) {
}
}
-// The PUBLIC nearby read fails CLOSED (H7). This read is the only surface that ever
-// reveals another agent's location, so its degradation path is a privacy boundary,
-// not a convenience one: if the limiter that bounds it can't make a decision, we
-// must NOT open an unmetered scrape window. Unlike the write paths above (which the
-// DB density/owner caps still bound when the limiter is blind), an unmetered read is
-// exactly the bulk-harvest hole the rate limit exists to close. So on a limiter
-// throw we return a retryable `rate_limiter_unavailable` verdict — surfaced to the
-// client as a 429 "temporarily unavailable, retrying" — rather than allowing the
-// read. The backing bucket (limits.publicIp) is an in-memory `local` limiter that
-// never touches Redis, so in practice it never throws; this guard makes the
-// fail-closed guarantee explicit and asserted rather than incidental.
-async function limitFailClosedRead(name, fn, ...args) {
- try {
- return await fn(...args);
- } catch (err) {
- const last = _rlWarnedAt.get(name) || 0;
- const now = Date.now();
- if (now - last >= RL_WARN_COOLDOWN_MS) {
- _rlWarnedAt.set(name, now);
- console.warn(`[irl/pins] read limiter "${name}" failed — failing CLOSED (deny):`, err?.message || err);
- }
- return { success: false, reason: 'rate_limiter_unavailable', reset: Date.now() + 60_000 };
- }
-}
-
// ── Sweep anomaly detection (H7) ─────────────────────────────────────────────
// A real /irl user stays in ~1 geocell: they poll the same spot every ~10 s. A
// scraper reading many DISTINCT cells in a short window is sweep-shaped, even if
@@ -890,11 +865,13 @@ export default wrap(async (req, res) => {
// Every public GET read (the nearby feed + my-pins) is IP rate-limited so the
// tight proximity feed can't be systematically gridded into a bulk location
- // scrape. A legit viewer polls nearby every ~10 s (≈6/min) — well under the
- // 60/min public ceiling — while a scripted sweep trips it fast. This read FAILS
- // CLOSED (H7): if the limiter can't decide, we deny with a retryable
- // `rate_limiter_unavailable` rather than open an unmetered scrape window — an
- // unbounded location read is the exact hole the limit exists to close.
+ // scrape. This read FAILS CLOSED (H7): if the limiter can't decide, we deny with
+ // a retryable `rate_limiter_unavailable` rather than open an unmetered scrape
+ // window: an unbounded location read is the exact hole the limit exists to
+ // close. The generic 240/min read ceiling applies to every GET here; the
+ // coordinate-returning nearby branch below adds the tighter, dedicated
+ // `irlNearbyIp` bucket (60/min) that the H7 sweep-cost numbers are computed
+ // against. See docs/irl/THREAT-MODEL.md.
if (req.method === 'GET') {
const rl = await limitFailClosedRead('publicIp', limits.publicIp, clientIp(req));
if (!rl.success) return rateLimited(res, rl);
@@ -1076,6 +1053,14 @@ export default wrap(async (req, res) => {
return json(res, 400, { error: 'lat and lng are required' });
}
+ // Dedicated coordinate-read budget (H7), on top of the generic GET ceiling
+ // above. This is the number the threat model's grid-sweep cost is computed
+ // from, so it lives in its own bucket rather than riding the shared public
+ // read limit, which is tuned for page-load fan-out and has been raised for
+ // reasons that have nothing to do with location privacy. Fails CLOSED.
+ const nearbyRl = await limitFailClosedRead('irlNearbyIp', limits.irlNearbyIp, clientIp(req));
+ if (!nearbyRl.success) return rateLimited(res, nearbyRl);
+
// Proof-of-presence (H3): bind the read to a genuine fix. The caller mints a
// short-lived, HMAC-signed token from their real GPS via POST /fix-token; this
// read only answers for the coarse area that token was minted in, so a viewer
diff --git a/api/irl/world-lines.js b/api/irl/world-lines.js
index 5364228dd..c5c06a400 100644
--- a/api/irl/world-lines.js
+++ b/api/irl/world-lines.js
@@ -30,7 +30,7 @@ import { cors, json, wrap, rateLimited, readJson } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
+import { limits, clientIp, limitFailClosedRead } from '../_lib/rate-limit.js';
import { readDeviceToken } from '../_lib/irl-auth.js';
import { verifyFixToken, fixEnforced } from '../_lib/irl-presence.js';
import { insertNotification } from '../_lib/notify.js';
@@ -189,7 +189,10 @@ export default wrap(async (req, res) => {
if (req.method === 'GET') {
// Public reads share the generic per-IP read ceiling; the fix-gated reads add
// the proof-of-presence binding on top so a quest's spot can't be browsed remotely.
- const rl = await limits.publicIp(clientIp(req));
+ // Fail-closed: `nearby` and `detail` hand back quest coordinates, so a limiter
+ // that cannot decide must deny with a retryable 429 rather than 500 the read
+ // (or, worse, wave it through unmetered).
+ const rl = await limitFailClosedRead('publicIp', limits.publicIp, clientIp(req));
if (!rl.success) return rateLimited(res, rl);
if (action === 'nearby') return handleNearby(req, res);
if (action === 'browse') return handleBrowse(req, res);
@@ -412,6 +415,14 @@ async function handleNearby(req, res) {
if (!Number.isFinite(parsed)) return json(res, 400, { error: 'invalid radius' });
const radius = Math.min(NEARBY_MAX_RADIUS_M, Math.max(30, parsed));
+ // Dedicated coordinate-read budget (H7), fail-closed. This is by far the widest
+ // location read on the platform (600 m vs 60 m for pins), so one call covers
+ // ~100x the area of a pin read and it is the cheapest surface to sweep. It draws
+ // on the same 60/min/IP /irl location bucket as the tighter reads rather than
+ // the generic public ceiling. See docs/irl/THREAT-MODEL.md.
+ const nearbyRl = await limitFailClosedRead('irlNearbyIp', limits.irlNearbyIp, clientIp(req));
+ if (!nearbyRl.success) return rateLimited(res, nearbyRl);
+
// Same fix-gate as the pin proximity read: a quest's location is only revealed to a
// caller proven to be standing near it.
if (fixEnforced()) {
diff --git a/docs/irl/THREAT-MODEL.md b/docs/irl/THREAT-MODEL.md
index 7648b2b09..17b64ef66 100644
--- a/docs/irl/THREAT-MODEL.md
+++ b/docs/irl/THREAT-MODEL.md
@@ -11,6 +11,12 @@ radius: `GET /api/irl/pins?lat&lng&radius` (≤60 m, the per-viewer proximity fe
(≤600 m). The pins feed is the one the controls below are written against; drops and
World Lines shipped later and inherit the same fix gate.
+One further read returns a coordinate without a presence gate: `GET /api/irl/drops/:id`
+answers for a drop the caller already knows the id of, and coarsens the point to 3
+decimals (~110 m) for anyone but the owner. It is id-addressed, not discoverable, so
+it cannot be swept into a grid; it is listed here because "all location reads are
+presence-gated" would otherwise be one endpoint short of true.
+
(`/api/irl/pins/mine`, `agent-card`, `agent-summary`, `interactions*`, `report`,
`share-frame` do not return others' coordinates. That was established by a
location-leak audit of the pins feed, which predates drops and World Lines and so
@@ -22,7 +28,7 @@ does not cover them.)
|---|---|---|
| **Remote browsing** ("show me agents in Tokyo from my couch") | The caller must send their **own** `lat`/`lng`; results are filtered to `distance_m <= radius`. There is no bbox/window/roster feed and no realtime pin broadcast. | `api/irl/pins.js` nearby branch; `multiplayer/src/rooms/IrlRoom.js` (syncs no pins) |
| **Wide-radius scrape** | `radius` is clamped to `[10, 60]` m server-side; a present-but-non-finite radius is rejected (no NaN box). | `api/irl/pins.js` `Math.min(60, Math.max(10, …))` |
-| **Bulk grid harvest** | Per-IP rate limit on every read; **fail-closed** if the limiter can't decide (deny, never an unmetered window). Distinct-cell **sweep detection** fires a deduped, coordinate-free ops alert when one caller reads many geocells in a short window. | `limitFailClosedRead`, `recordCellRead` in `api/irl/pins.js`; `limits.publicIp` in `api/_lib/rate-limit.js` |
+| **Bulk grid harvest** | All three coordinate reads share a **dedicated** 60/min/IP budget (`limits.irlNearbyIp`), separate from the generic public read ceiling, and **fail closed** if the limiter can't decide (deny, never an unmetered window). Distinct-cell **sweep detection** fires a deduped, coordinate-free ops alert when one caller reads many geocells in a short window. | `limits.irlNearbyIp`, `limitFailClosedRead` in `api/_lib/rate-limit.js`; `recordCellRead` in `api/irl/pins.js` |
| **De-anonymization** (who placed this agent?) | The public projection is an explicit allow-list: `user_id` / `device_token` are never returned; only an `is_mine` boolean computed server-side. | `api/irl/pins.js` nearby projection |
| **Coordinate fingerprinting** | Returned coordinates are coarsened to 5 decimals (~1.1 m, finer than GPS error but stripped of the false-precision tail). The room origin is coarsened too; exact intra-room layout rides relative offsets, not absolute coords. | `roundCoord`, `PUBLIC_COORD_DP` in `api/irl/pins.js` |
| **Credential / position leak via logs** | `req.url` (which carries `lat`/`lng`/`deviceToken`) is redacted before any log/Sentry/Telegram sink. The sweep alert carries only a SHA-256 IP hash + a count — never a coordinate, IP, or geocell. | `redactUrl` in `api/_lib/http.js`; `recordCellRead` alert payload |
@@ -32,10 +38,12 @@ does not cover them.)
- **Limiter degraded / throws on the read** → **fail closed**: the read returns a
retryable `rate_limiter_unavailable` (HTTP 429), surfaced to the client as
- "temporarily unavailable, retrying." It never serves an unmetered read. The
- backing bucket (`limits.publicIp`) is an in-memory `local` limiter that never
- touches Redis, so it does not throw in practice; `limitFailClosedRead` makes the
- guarantee explicit and asserted (`tests/api/irl-pins-hardening.test.js`).
+ "temporarily unavailable, retrying." It never serves an unmetered read. This
+ holds on all three coordinate reads (the drops read used to fail *open* here).
+ The backing buckets are in-memory `local` limiters that never touch Redis, so they
+ do not throw in practice; `limitFailClosedRead` makes the guarantee explicit and
+ asserted (`tests/api/irl-nearby-limit.test.js` against the real limiter,
+ `tests/api/irl-pins-hardening.test.js` through the handler).
- **Write limiter degraded** (place/edit/delete) → **fail open**: the DB density,
per-owner, and report-dedup caps still bound writes, so an infra hiccup never
blocks a legitimate placement. This asymmetry is deliberate: a blind limiter on a
@@ -84,6 +92,17 @@ surface by far — its 600 m radius covers ~1.13 km² per read, so the same area
in under a minute. Rotating IPs collapses all of these numbers. Presence enforcement
is a speed bump with a real slope; it is not a wall.
+> **Why the read ceiling is its own bucket.** Those minutes are a direct function of
+> 60/min, so that number is a privacy budget and has to be pinned to the surface it
+> protects. It was not: the coordinate reads rode the generic public read bucket,
+> which was raised 60 → 240 on 2026-07-10 for unrelated page-load fan-out (~166
+> endpoints share it and a single page can fire 7-8). Nothing about /irl was
+> considered in that change, and nothing failed: the sweep cost quietly dropped 4x
+> while this file still said 90 minutes. The reads now draw on `limits.irlNearbyIp`,
+> a dedicated 60/min/IP bucket, and `tests/api/irl-nearby-limit.test.js` asserts the
+> number against the real limiter so the next tuning pass of an unrelated ceiling
+> cannot silently re-open it.
+
> **Per-IP means per-IP only if the IP is real.** From the Vercel→Cloud Run migration
> until 2026-07-09, `clientIp()` fell back to `req.socket.remoteAddress` — the load
> balancer — so every per-IP bucket on the platform was in fact one global bucket.
diff --git a/tests/api/irl-nearby-limit.test.js b/tests/api/irl-nearby-limit.test.js
new file mode 100644
index 000000000..c0b5a7169
--- /dev/null
+++ b/tests/api/irl-nearby-limit.test.js
@@ -0,0 +1,72 @@
+// The /irl coordinate-read budget, asserted against the REAL rate-limit module.
+//
+// Two properties the H7 threat model (docs/irl/THREAT-MODEL.md) states as fact, and
+// which nothing else in the suite fences:
+//
+// · The three reads that reveal where another user placed something (pins nearby,
+// drops nearby, world-lines nearby) draw on their OWN 60/min/IP bucket. They used
+// to ride the shared `publicIp` ceiling, which was raised 60 -> 240 for unrelated
+// page-load fan-out; that quietly cut the documented cost of a grid sweep by 4x.
+// A dedicated bucket is what keeps the published sweep-cost numbers honest.
+//
+// · A limiter that cannot decide DENIES on those reads. Everywhere else on the
+// platform a blind limiter fails open, because a DB cap or an ownership check
+// still bounds the request. An unmetered location read has no such backstop.
+//
+// This file imports the real limiter (no vi.mock) so a change to either number or to
+// the degradation policy fails here rather than only drifting the doc.
+
+import { describe, it, expect, vi } from 'vitest';
+import { limits, limitFailClosedRead } from '../../api/_lib/rate-limit.js';
+
+describe('irlNearbyIp, the dedicated /irl coordinate-read bucket', () => {
+ it('allows a legitimate viewer\'s poll rate and denies a scripted sweep within the minute', async () => {
+ // A real viewer polls nearby every ~10 s (~6/min). A sweeper spends the whole
+ // budget in seconds. Use a unique key so a parallel test can't drain this one.
+ const ip = `198.51.100.${Math.floor(process.pid % 200) + 1}-nearby`;
+ const verdicts = [];
+ for (let i = 0; i < 61; i++) verdicts.push(await limits.irlNearbyIp(ip));
+
+ expect(verdicts[0].success).toBe(true);
+ expect(verdicts[5].success).toBe(true); // 6/min viewer poll is nowhere near the cap
+ expect(verdicts[59].success).toBe(true); // 60th call still inside the window
+ expect(verdicts[60].success).toBe(false); // 61st is the sweep, denied
+ });
+
+ it('is a separate bucket from the generic public read ceiling', async () => {
+ // Draining the /irl budget must not touch the page-load budget, and vice
+ // versa: they exist for different reasons and are tuned independently.
+ const ip = `198.51.100.${Math.floor(process.pid % 200) + 1}-isolated`;
+ for (let i = 0; i < 61; i++) await limits.irlNearbyIp(ip);
+ expect((await limits.irlNearbyIp(ip)).success).toBe(false);
+ expect((await limits.publicIp(ip)).success).toBe(true);
+ });
+});
+
+describe('limitFailClosedRead: degradation policy for location reads', () => {
+ it('passes the limiter verdict through untouched when the limiter works', async () => {
+ const allow = await limitFailClosedRead('test', async () => ({ success: true, reset: 1 }));
+ expect(allow).toEqual({ success: true, reset: 1 });
+ const deny = await limitFailClosedRead('test', async () => ({ success: false, reset: 2 }));
+ expect(deny.success).toBe(false);
+ });
+
+ it('DENIES with a retryable reason when the limiter throws, never an unmetered read', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const v = await limitFailClosedRead('irlNearbyIp-throwing', async () => {
+ throw new Error('redis: max requests limit exceeded');
+ });
+ expect(v.success).toBe(false);
+ expect(v.reason).toBe('rate_limiter_unavailable');
+ expect(v.reset).toBeGreaterThan(Date.now()); // retryable, not a permanent block
+ warn.mockRestore();
+ });
+
+ it('logs a degraded limiter once per cooldown, not once per request', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const boom = async () => { throw new Error('limiter down'); };
+ for (let i = 0; i < 5; i++) await limitFailClosedRead('irlNearbyIp-flooding', boom);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockRestore();
+ });
+});
diff --git a/tests/api/irl-pins-hardening.test.js b/tests/api/irl-pins-hardening.test.js
index 62d16a751..467fe95a5 100644
--- a/tests/api/irl-pins-hardening.test.js
+++ b/tests/api/irl-pins-hardening.test.js
@@ -75,13 +75,24 @@ function verdict() {
if (limiterThrows) throw new Error('redis: max requests limit exceeded');
return { success: true, reset: Date.now() + 60_000 };
}
+// `irlNearbyIp` is the dedicated coordinate-read bucket the H7 sweep-cost numbers are
+// computed against; `nearbyDenied` flips it to a plain (non-throwing) denial so we can
+// prove the nearby branch actually consults it. limitFailClosedRead mirrors the real
+// helper's contract; the real implementation is asserted against directly in
+// tests/api/irl-nearby-limit.test.js.
+let nearbyDenied = false;
vi.mock('../../api/_lib/rate-limit.js', () => ({
limits: {
publicIp: vi.fn(async () => verdict()),
+ irlNearbyIp: vi.fn(async () => (nearbyDenied ? { success: false, reset: Date.now() + 60_000 } : verdict())),
irlPinIp: vi.fn(async () => verdict()),
irlPinBurst: vi.fn(async () => verdict()),
irlPinHourly: vi.fn(async () => verdict()),
},
+ limitFailClosedRead: async (_name, fn, ...args) => {
+ try { return await fn(...args); }
+ catch { return { success: false, reason: 'rate_limiter_unavailable', reset: Date.now() + 60_000 }; }
+ },
clientIp: () => '127.0.0.1',
}));
@@ -129,6 +140,7 @@ beforeEach(() => {
bakeSpy.mockResolvedValue({ url: 'https://three.ws/cdn/irl/pins/x/abc.glb' });
deleteResult = [{ id: 'del-1', lat: 1, lng: 2 }];
limiterThrows = false;
+ nearbyDenied = false;
sessionUser = null;
resetGuardianDegraded();
pinRow = {
@@ -371,6 +383,18 @@ describe('rate limiter degradation', () => {
/lat BETWEEN/i.test(Array.isArray(s) ? s.join(' ') : String(s)));
expect(ranSelect).toBe(false);
});
+ it('the nearby read is bounded by the DEDICATED coordinate bucket, not just the shared public one (H7)', async () => {
+ // The generic public read ceiling is tuned for page-load fan-out and has been
+ // raised for reasons unrelated to location privacy. The grid-sweep cost in the
+ // threat model is computed from `irlNearbyIp`, so the branch must actually
+ // consult it and deny on it.
+ nearbyDenied = true;
+ const { res } = await get({ query: { lat: '40.7128', lng: '-74.006', radius: '40' } });
+ expect(res.statusCode).toBe(429);
+ const ranSelect = sqlMock.mock.calls.some(([s]) =>
+ /lat BETWEEN/i.test(Array.isArray(s) ? s.join(' ') : String(s)));
+ expect(ranSelect).toBe(false);
+ });
it('a throwing limiter does not 500 a DELETE — write fails open, ownership still enforced (task 12)', async () => {
limiterThrows = true;
const { res } = await del({ id: UUID, deviceToken: 'device-A' });
diff --git a/tests/api/irl-pins-location-guards.test.js b/tests/api/irl-pins-location-guards.test.js
index d7858b5d4..fede241e2 100644
--- a/tests/api/irl-pins-location-guards.test.js
+++ b/tests/api/irl-pins-location-guards.test.js
@@ -65,7 +65,17 @@ vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => nul
let publicVerdict = { success: true, reset: Date.now() + 60_000 };
vi.mock('../../api/_lib/rate-limit.js', () => ({
- limits: { publicIp: vi.fn(async () => publicVerdict) },
+ limits: {
+ publicIp: vi.fn(async () => publicVerdict),
+ irlNearbyIp: vi.fn(async () => publicVerdict),
+ },
+ // limitFailClosedRead + irlNearbyIp: the nearby branch draws on a dedicated
+ // coordinate-read bucket and denies when the limiter cannot decide. Behaviour is
+ // owned by tests/api/irl-nearby-limit.test.js; here they just have to exist.
+ limitFailClosedRead: async (_name, fn, ...args) => {
+ try { return await fn(...args); }
+ catch { return { success: false, reason: 'rate_limiter_unavailable', reset: Date.now() + 60_000 }; }
+ },
clientIp: () => '127.0.0.1',
}));
diff --git a/tests/api/irl-pins-mine-owner-scope.test.js b/tests/api/irl-pins-mine-owner-scope.test.js
index e67b22640..babb25ea0 100644
--- a/tests/api/irl-pins-mine-owner-scope.test.js
+++ b/tests/api/irl-pins-mine-owner-scope.test.js
@@ -48,7 +48,17 @@ let sessionUser = null;
vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => sessionUser) }));
vi.mock('../../api/_lib/rate-limit.js', () => ({
- limits: { publicIp: vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 })) },
+ limits: {
+ publicIp: vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 })),
+ irlNearbyIp: vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 })),
+ },
+ // limitFailClosedRead + irlNearbyIp: the nearby branch draws on a dedicated
+ // coordinate-read bucket and denies when the limiter cannot decide. Behaviour is
+ // owned by tests/api/irl-nearby-limit.test.js; here they just have to exist.
+ limitFailClosedRead: async (_name, fn, ...args) => {
+ try { return await fn(...args); }
+ catch { return { success: false, reason: 'rate_limiter_unavailable', reset: Date.now() + 60_000 }; }
+ },
clientIp: () => '127.0.0.1',
}));
diff --git a/tests/api/irl-pins-room.test.js b/tests/api/irl-pins-room.test.js
index 674b29690..7b9a2e968 100644
--- a/tests/api/irl-pins-room.test.js
+++ b/tests/api/irl-pins-room.test.js
@@ -54,6 +54,14 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
irlPinBurst: vi.fn(async () => ({ success: true })),
irlPinHourly: vi.fn(async () => ({ success: true })),
publicIp: vi.fn(async () => ({ success: true })),
+ irlNearbyIp: vi.fn(async () => ({ success: true })),
+ },
+ // limitFailClosedRead + irlNearbyIp: the nearby branch draws on a dedicated
+ // coordinate-read bucket and denies when the limiter cannot decide. Behaviour is
+ // owned by tests/api/irl-nearby-limit.test.js; here they just have to exist.
+ limitFailClosedRead: async (_name, fn, ...args) => {
+ try { return await fn(...args); }
+ catch { return { success: false, reason: 'rate_limiter_unavailable', reset: Date.now() + 60_000 }; }
},
clientIp: () => '127.0.0.1',
}));
diff --git a/tests/api/irl-privacy.test.js b/tests/api/irl-privacy.test.js
index e720918fa..85f8c1a41 100644
--- a/tests/api/irl-privacy.test.js
+++ b/tests/api/irl-privacy.test.js
@@ -63,6 +63,14 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
irlPinBurst: vi.fn(async () => ({ success: true })),
irlPinHourly: vi.fn(async () => ({ success: true })),
publicIp: vi.fn(async () => ({ success: true })),
+ irlNearbyIp: vi.fn(async () => ({ success: true })),
+ },
+ // limitFailClosedRead + irlNearbyIp: the nearby branch draws on a dedicated
+ // coordinate-read bucket and denies when the limiter cannot decide. Behaviour is
+ // owned by tests/api/irl-nearby-limit.test.js; here they just have to exist.
+ limitFailClosedRead: async (_name, fn, ...args) => {
+ try { return await fn(...args); }
+ catch { return { success: false, reason: 'rate_limiter_unavailable', reset: Date.now() + 60_000 }; }
},
clientIp: () => '127.0.0.1',
}));